New debugging function debugOutput() introduced, some rewrites to EL:
[mailer.git] / inc / libs / rallye_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/22/2004 *
4  * ===================                          Last change: 08/24/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : rallye_functions.php                             *
8  * -------------------------------------------------------------------- *
9  * Short description : Special functions for rallye extension           *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Spezielle Funktion fuer rallye-Erweiterung       *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // Auto-start referal rallyes
46 function autostartReferalRallyes ($result) {
47         // Load all rallyes (usally we have only one rallye active per time!
48         list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
49
50         // Free result
51         SQL_FREERESULT($result);
52
53         // Set notified to Y
54         SQL_QUERY_ESC("UPDATE
55         `{?_MYSQL_PREFIX?}_rallye_data`
56 SET
57         `notified`='Y'
58 WHERE
59         `id`=%s
60 LIMIT 1",
61                 array(bigintval($id)), __FUNCTION__, __LINE__);
62
63         // Transfer all neccessary data to the $content array
64         $content['userid_cnt'] = getTotalConfirmedUser();
65         $content['start']      = generateDateTime($start, 2);
66         $content['end']        = generateDateTime($end  , 2);
67         $content['now_t']      = generateDateTime(time(), 2);
68         $content['title']      = $title;
69         $content['id']         = $id;  // id for the rallye details link
70
71         // Determine min_users and min_prices
72         $content['min_users']  = determineReferalRallyeMinimumUsers($min_users);
73         $content['min_prices'] = determineReferalRallyeMinimumPrices($min_prices);
74
75         // Load prices
76         $content['prices'] = addReferalRallyePrices($id);
77
78         // Query all users
79         $result_user = SQL_QUERY("SELECT
80         `userid`
81 FROM
82         `{?_MYSQL_PREFIX?}_user_data`
83 WHERE
84         `status`='CONFIRMED'
85 ORDER BY
86         `userid` ASC", __FUNCTION__, __LINE__);
87
88         // Let's begin with the userids...
89         while ($row = SQL_FETCHARRAY($result_user)) {
90                 // Merge both arrays
91                 $content = merge_array($content, $row);
92
93                 $un = false;
94
95                 // Get refs by userid
96                 $cnt = getReferalRallyeRefsCount($content['userid']);
97                 if (empty($cnt)) $cnt = '0'; // Added prevent some unknown troubles... :-?
98
99                 // Check if line is already included...
100                 $result_ref = SQL_QUERY_ESC("SELECT
101         `id`
102 FROM
103         `{?_MYSQL_PREFIX?}_rallye_users`
104 WHERE
105         `rallye_id`=%s AND
106         `userid`=%s
107 LIMIT 1",
108                         array(bigintval($id), bigintval($content['userid'])), __FUNCTION__, __LINE__);
109                 if (SQL_NUMROWS($result_ref) == 0) {
110                         // Free memory
111                         SQL_FREERESULT($result_ref);
112
113                         // Add userid and his ref count to table
114                         $result_ref = SQL_QUERY_ESC("SELECT 
115         SUM(p.points) AS points
116 FROM
117         `{?_MYSQL_PREFIX?}_user_points` AS p
118 LEFT JOIN
119         `{?_MYSQL_PREFIX?}_user_data` AS d
120 ON
121         p.userid=d.userid
122 WHERE
123         d.`status`='CONFIRMED' AND
124         d.max_mails > 0 AND
125         d.mails_confirmed >= {?ref_payout?} AND
126         p.ref_depth=1 AND
127         p.points > 0 AND
128         d.userid=%s",
129                                 array(bigintval($content['userid'])), __FUNCTION__, __LINE__);
130
131                         // Get points
132                         list($cpoints) = SQL_FETCHROW($result_ref);
133
134                         // Free result
135                         SQL_FREERESULT($result_ref);
136
137                         if (empty($cpoints)) $cpoints = '0.00000';
138
139                         // Add info line
140                         SQL_QUERY_ESC("INSERT INTO
141         `{?_MYSQL_PREFIX?}_rallye_users`
142 (`rallye_id`, `userid`, `refs`, `curr_points`)
143         VALUES
144 (%s, %s, %s, %s)",
145                                 array(
146                                         bigintval($id),
147                                         bigintval($content['userid']),
148                                         bigintval($cnt),
149                                         $cpoints
150                                 ), __FUNCTION__, __LINE__);
151                         $un = true;
152                 } // END - if
153
154                 // Ignored but for the template required refs (made before start of rallye)
155                 $content['refs']  = $cnt;
156
157                 // Shall I notify this member?
158                 if (($notify == 'Y') && ($un)) {
159                         // Load email template and send it to the user
160                         $message = loadEmailTemplate('member_rallye_notify', $content, $content['userid']);
161                         sendEmail($content['userid'], getMaskedMessage('RALLYE_MEMBER_NOTIFY', $title), $message);
162                 } // END - if
163         } // END - while
164
165         // Choose the right admin template
166         $templ = 'admin_rallye_no_notify';
167         if ($notify == 'Y') $templ = 'admin_rallye_notify';
168
169         // Send email to admin
170         sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_NOTIFY', $title), $templ, $prices);
171
172         // Free memory
173         SQL_FREERESULT($result_user);
174 }
175
176 //
177 function addReferalRallyePrices ($rallye, $mode = 'email') {
178         // Output mode
179         switch($mode) {
180                 case 'email': $mode = "\n";       break;
181                 case 'html' : $mode = "<br />\n"; break;
182         } // END - switch
183
184         // Load prices
185         $result_prices = SQL_QUERY_ESC("SELECT
186         `price_level`, `points`, `info`
187 FROM
188         `{?_MYSQL_PREFIX?}_rallye_prices`
189 WHERE
190         `rallye_id`=%s
191 ORDER BY
192         `price_level` ASC",
193                 array($rallye), __FUNCTION__, __LINE__);
194
195         // Entries found?
196         if (SQL_NUMROWS($result_prices) > 0) {
197                 // Load prices
198                 if ($mode == "\n") $prices = '{--RALLYE_MEMBER_PRICES_ADDED--}:' . $mode . '------------------------------' . $mode;
199
200                 $prices = '';
201                 while ($content = SQL_FETCHARRAY($result_prices)) {
202                         $prices .= $content['price_level']. '{--RALLYE_PRICE--}: ';
203                         if (!empty($content['info'])) {
204                                 $prices .= $content['info'];
205                         } else {
206                                 $prices .= $content['points'] . ' {?POINTS?}';
207                         }
208                         $prices .= '' . $mode;
209                 } // END - if
210
211                 // Free memory
212                 SQL_FREERESULT($result_prices);
213         } else {
214                 // No prices???
215                 $prices = getMaskedMessage('RALLYE_MEMBER_NO_PRICES', $mode);
216         }
217
218         // Add last line for email mode
219         if ($mode == "\n") $prices .= '------------------------------';
220
221         // Return price list
222         return $prices;
223 }
224
225 //
226 function addReferalRallyeTopUsers ($rallye, $default=0) {
227         // Init variables
228         $min_users = 0; $min_prices = 0;
229
230         // First check how many prices are set
231         $prices = countSumTotalData($rallye, 'rallye_prices', 'id', 'rallye_id', true);
232
233         // And load only limited users
234         $result = SQL_QUERY_ESC("SELECT
235         u.userid, u.refs, u.curr_points, rd.min_users, rd.min_prices
236 FROM
237         `{?_MYSQL_PREFIX?}_rallye_users` AS u
238 LEFT JOIN
239         `{?_MYSQL_PREFIX?}_refsystem` AS r
240 ON
241         u.userid=r.userid
242 LEFT JOIN
243         `{?_MYSQL_PREFIX?}_rallye_data` AS rd
244 ON
245         u.rallye_id=rd.id
246 WHERE
247         u.`rallye_id`=%s AND
248         r.counter > 0
249 ORDER BY
250         u.refs DESC",
251                 array(bigintval($rallye)), __FUNCTION__, __LINE__);
252
253         // Load users
254         $DATA = array(
255                 'userid'  => array(),
256                 'ref'     => array(),
257                 'cpoints' => array()
258         );
259
260         // Load all users
261         while ($content = SQL_FETCHARRAY($result)) {
262                 // Get current refs
263                 $cnt = getReferalRallyeRefsCount($content['userid'], $content['refs']);
264
265                 // Points of ref's
266                 $result_ref = SQL_QUERY_ESC("SELECT
267         p.points
268 FROM
269         `{?_MYSQL_PREFIX?}_user_points` AS p
270 LEFT JOIN
271         `{?_MYSQL_PREFIX?}_user_data` AS d
272 ON
273         p.userid=d.userid
274 WHERE
275         d.userid=%s AND
276         d.`status`='CONFIRMED' AND
277         p.ref_depth=1 AND
278         d.max_mails > 0 AND
279         d.mails_confirmed >= {?ref_payout?}
280 LIMIT 1",
281                         array(bigintval($content['userid'])), __FUNCTION__, __LINE__);
282
283                 // Get points
284                 list($refpoints) = SQL_FETCHROW($result_ref);
285
286                 // Free result
287                 SQL_FREERESULT($result_ref);
288
289                 if (empty($refpoints)) $refpoints = '0';
290
291                 // Init userid for list
292                 $userid = '---';
293
294                 // List only users with at least one ref!
295                 //* DEBUG: */ debugOutput('*'.$cnt.'/'.$content['userid'].'/'.$content['curr_points'].'/'.$refpoints.'*');
296                 if (($cnt > 0) && ($refpoints > $content['curr_points'])) { $userid = $content['userid']; } else { $cnt = ''; }
297
298                 // Save values to array
299                 $DATA['userid'][]   = $userid;
300                 $DATA['ref'][]      = $cnt;
301                 $DATA['cpoints'][]  = $content['curr_points'];
302                 $min_users  = $content['min_users'];
303                 $min_prices = $content['min_prices'];
304         } // END - while
305
306         // Free memory
307         SQL_FREERESULT($result);
308
309         // Sort whole array
310         array_pk_sort($DATA, array('ref', 'cpoints'), 0, 1, true);
311
312         // Generate table
313         $OUT = '';
314         $SW = 2;
315         for ($idx = '0'; $idx < $prices; $idx++) {
316                 if (empty($DATA['userid'][$idx])) $DATA['userid'][$idx] = '---';
317                 if (empty($DATA['ref'][$idx])) $DATA['ref'][$idx] = '---';
318
319                 // Prepare marking of default (maybe current user's) id
320                 $start = ''; $end = '';
321                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) {
322                         $start = '<strong>';
323                         $end   = '</strong>';
324                 } // END - if
325
326                 // Prepare content
327                 $content = array(
328                         'sw'     => $SW,
329                         'idx'    => ($idx + 1),
330                         'start'  => $start,
331                         'end'    => $end,
332                         'userid' => $DATA['userid'][$idx],
333                         'ref'    => $DATA['ref'][$idx],
334                         'info'   => ''
335                 );
336
337                 // Load row template and switch color
338                 $OUT .= loadTemplate('guest_rallye_row', true, $content);
339                 $SW = 3 - $SW;
340         } // END - for
341
342         // Add min_prices/users
343         $content['rows']       = $OUT;
344         $content['min_prices'] = bigintval($min_prices);
345         $content['min_users']  = bigintval($min_users);
346
347         // And finnally return the output
348         return loadTemplate('guest_rallye', true, $content);
349 }
350
351 // Run this function only when a new member has confirmed his email address!
352 function addUserToReferalRallye ($userid, $content = array()) {
353         $add = '';
354
355         // Updated extension?
356         if (isExtensionInstalledAndNewer('rallye', '0.2.0')) {
357                 $add .= ', `min_users`, `min_prices`';
358         } // END - if
359
360         // Check for an auto-add rallye
361         $result = SQL_QUERY("SELECT
362         `id`, `title`, `start_time`, `end_time`, `send_notify`".$add."
363 FROM
364         `{?_MYSQL_PREFIX?}_rallye_data`
365 WHERE
366         `is_active`='Y' AND
367         `notified`='Y' AND
368         `auto_add_new_user`='Y' AND
369         `expired`='N'
370 LIMIT 1", __FUNCTION__, __LINE__);
371         if (SQL_NUMROWS($result) == 1) {
372                 // Init variables
373                 $min_users = '0'; $min_prices = '0';
374
375                 // Load data
376                 if (isExtensionInstalledAndNewer('rallye', '0.2.0')) {
377                         list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
378                 } else {
379                         list($id, $title, $start, $end, $notify) = SQL_FETCHROW($result);
380                 }
381
382                 // Free result
383                 SQL_FREERESULT($result);
384
385                 if ($notify == 'Y') {
386                         // Transfer all neccessary data to $content array
387                         $content['start'] = generateDateTime($start, 2);
388                         $content['end']   = generateDateTime($end  , 2);
389                         $content['now_t'] = generateDateTime(time(), 2);
390                         $content['title'] = $title;
391                         $content['id']    = $id;  // id for the rallye details link
392                         $content['ref']   = '0';
393                         $content['refs']  = countSumTotalData($userid, 'user_data', 'userid', 'refid', true);
394
395                         // Load prices
396                         $content['prices'] = addReferalRallyePrices($id);
397
398                         // Determine min_users/prices tring
399                         $content['min_users']  = determineReferalRallyeMinimumUsers($min_users);
400                         $content['min_prices'] = determineReferalRallyeMinimumPrices($min_prices);
401
402                         // Send notification to member
403                         $message = loadEmailTemplate('member_rallye_notify', $content, $userid);
404                         sendEmail($userid, getMaskedMessage('RALLYE_MEMBER_NOTIFY', $title), $message);
405                 } // END - if
406
407                 // Check if line is already included...
408                 $result = SQL_QUERY_ESC("SELECT
409         `id`
410 FROM
411         `{?_MYSQL_PREFIX?}_rallye_users`
412 WHERE
413         `rallye_id`=%s AND
414         `userid`=%s
415 LIMIT 1",
416                         array(
417                                 bigintval($id),
418                                 bigintval($userid)
419                         ), __FUNCTION__, __LINE__);
420
421                 // Is this user added?
422                 if (SQL_NUMROWS($result) < 1) {
423                         // Add userid and his ref count to table
424                         SQL_QUERY_ESC("INSERT INTO
425         `{?_MYSQL_PREFIX?}_rallye_users`
426 (`rallye_id`, `userid`, `refs`)
427         VALUES
428 (%s,%s,0)",
429                                 array(
430                                         bigintval($id),
431                                         bigintval($userid)
432                                 ), __FUNCTION__, __LINE__);
433                 } // END - if
434
435                 // Free memory
436                 SQL_FREERESULT($result);
437         } // END - if
438 }
439
440 //
441 function markReferalRallyesAsExpired ($result) {
442         global $DATA;
443
444         // Load rallye data
445         list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
446
447         // Free result
448         SQL_FREERESULT($result);
449
450         // Load users array (!) with assigned prices
451         $prices = getArrayFromReferalRallyeUsers($id);
452
453         // Init array
454         $DATA = array();
455         $cnt = '0';
456         $users = array();
457         $DATA['title']  = $title;
458         $DATA['start']  = generateDateTime($start, 1);
459         $DATA['end']    = generateDateTime($end  , 1);
460         $DATA['now_t']  = generateDateTime(time(), 1);
461
462         // Just count...
463         $total = '0';
464         foreach($prices['userid'] as $key => $userid) {
465                 // Check status
466                 //   active = 1: account is still confirmed
467                 //   active = 0: account is deleted or locked
468                 $active = countSumTotalData($DATA['userid'][$idx], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED'");
469
470                 $prices['active'][$key] = $active;
471
472                 // Allow valid and active users with at least one ref to get points
473                 if (($userid > 0) && ($prices['ref'][$key] > 0) && ($active == 1) && ($prices['cpoints'][$key] > 0)) {
474                         $total++;
475                 } // END - if
476         } // END - foreach
477
478         if (($total < $min_prices) || ($total == '0')) {
479                 // Do not end this rallye!
480                 unset($DATA);
481                 return;
482         } // END - if
483
484         // Expire rallye
485         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_rallye_data` SET `expired`='Y' WHERE `id`=%s LIMIT 1",
486                 array(bigintval($id)), __FUNCTION__, __LINE__);
487
488         // Run array through (by userid is the most important 2nd-level-array)
489         foreach($prices['userid'] as $key => $userid) {
490                 // Allow valid and active users with at least one ref to get points
491                 if (($userid > 0) && ($prices['ref'][$key] > 0) && ($prices['active'][$key] == 1) && ($prices['cpoints'][$key] > 0)) {
492                         // Transfer data to array for the mail template
493                         $DATA['level']  = $prices['level'][$key];
494                         $DATA['points'] = $prices['points'][$key];
495                         $DATA['info']   = $prices['info'][$key];
496                         $DATA['ref']    = $prices['ref'][$key];
497
498                         // Default is other
499                         $winnerLevel = 'other';
500
501                         // Determine winner level
502                         if ($DATA['level'] == 1) {
503                                 // The winner!
504                                 $winnerLevel = '_gold';
505                         } elseif ($DATA['level'] == 2) {
506                                 // The vice winner!
507                                 $winnerLevel = '_silver';
508                         } elseif ($DATA['level'] == 3) {
509                                 // The bronce winner
510                                 $winnerLevel = '_bronce';
511                         }
512
513                         if ($DATA['points'] > 0) {
514                                 // Add points directly to user's account
515                                 addPointsDirectly('rallye_winner' . $winnerLevel, $userid, $DATA['points']);
516                         } // END - if
517
518                         if ($notify == 'Y') {
519                                 // Prepare infos for the mail template
520                                 if (!empty($DATA['info'])) {
521                                         // Take direct infos
522                                         $DATA['infos'] = $DATA['info'];
523                                 } else {
524                                         // Take points
525                                         $DATA['infos'] = $DATA['points'] . ' {?POINTS?}';
526                                 }
527
528                                 // Add suffix to template name
529                                 $template = 'member_rallye_expired' . $winnerLevel;
530
531                                 // Load template
532                                 $message = loadEmailTemplate($template, $DATA, $userid);
533                                 sendEmail($userid, getMaskedMessage('RALLYE_MEMBER_EXPIRED_SUBJ', $DATA['level']), $message);
534                         } // END - if
535
536                         // Count userid
537                         $cnt++;
538                         $users['userid'][$userid] = $userid;
539                         $users['poi'][$userid] = $DATA['infos'];
540                 } // END - if
541         } // END - foreach
542
543         // Select template depending on notfication is switch on / off
544         if ($notify == 'Y') {
545                 $templ = 'admin_rallye_expired';
546         } elseif (is_array($users['userid'])) {
547                 $templ = 'admin_rallye_expired_no';
548                 $cnt = getReferalRallyeUserDataFromArray($users);
549         }
550
551         // Send mail to admin
552         sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_EXPIRED_SUBJ', $title), $templ, $cnt);
553
554         // Add task
555         createNewTask('{--RALLYE_ADMIN_EXPIRED--}: ' . $title, '{--RALLYE_ADMIN_EXPIRED_TEXT--}', 'RALLYE_EXPIRED');
556 }
557
558 //
559 function getReferalRallyeUserDataFromArray ($userIds) {
560         // Implode user ids
561         $userid_string = implode(',', $userIds['userid']);
562
563         // Init result string
564         $ret = '';
565
566         // Load users
567         $result = SQL_QUERY_ESC("SELECT
568         `userid`, `gender`, `surname`, `family`, `email`
569 FROM
570         `{?_MYSQL_PREFIX?}_user_data`
571 WHERE
572         `userid` IN(%s) AND
573         `status`='CONFIRMED'
574 ORDER BY
575         `userid` ASC
576 LIMIT %s",
577                 array(
578                         $userid_string,
579                         count($userIds)
580                 ), __FUNCTION__, __LINE__);
581         while ($content = SQL_FETCHARRAY($result)) {
582                 // Construct the message masked and add it
583                 $ret .= sprintf("%s %s %s (%s) - %s\n",
584                         translateGender($content['gender']),
585                         $content['surname'],
586                         $content['family'],
587                         $content['email'],
588                         $userIds['poi'][$content['userid']]
589                 );
590         } // END - while
591
592         // Return result
593         return substr($ret, 0, -1);
594 }
595
596 //
597 function getArrayFromReferalRallyePrices ($rallye) {
598         // Init multi array
599         $prices = array(
600                 'level'  => array(),
601                 'points' => array(),
602                 'info'   => array()
603         );
604
605         // Load prices
606         $result = SQL_QUERY_ESC("SELECT
607         `price_level`, `points`, `info`
608 FROM
609         `{?_MYSQL_PREFIX?}_rallye_prices`
610 WHERE
611         `rallye_id`=%s
612 ORDER BY
613         `price_level` ASC",
614                 array(bigintval($rallye)), __FUNCTION__, __LINE__);
615
616         // Transfer elements
617         while ($content = SQL_FETCHARRAY($result)) {
618                 $prices['level'][]  = $content['price_level'];
619                 $prices['points'][] = $content['points'];
620                 $prices['info'][]   = $content['info'];
621         } // END - while
622
623         // Free memory
624         SQL_FREERESULT($result);
625
626         // Return array
627         return $prices;
628 }
629
630 //
631 function getArrayFromReferalRallyeUsers ($rallye) {
632         // Fix zero points to 0.00000
633         if (getConfig('ref_payout') == '0') setConfigEntry('ref_payout', '0.00000');
634
635         // Init multi array
636         $users = array(
637                 'userid'  => array(),
638                 'ref'     => array(),
639                 'cpoints' => array(),
640         );
641
642         // Load users                          userid    old   points earned
643         $result_user = SQL_QUERY_ESC("SELECT `userid`, `refs`, `curr_points` FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s ORDER BY `userid` ASC",
644                 array(bigintval($rallye)), __FUNCTION__, __LINE__);
645         while ($content = SQL_FETCHARRAY($result_user)) {
646                 // Load current ref count
647                 $cnt = getReferalRallyeRefsCount($content['userid'], $content['refs']);
648
649                 // Points of ref's
650                 $result_ref = SQL_QUERY_ESC("SELECT
651         SUM(p.points) AS points
652 FROM
653         `{?_MYSQL_PREFIX?}_user_points` AS p
654 LEFT JOIN
655         `{?_MYSQL_PREFIX?}_user_data` AS d
656 ON
657         p.userid=d.userid
658 WHERE
659         d.`status`='CONFIRMED' AND
660         d.max_mails > 0 AND
661         d.mails_confirmed >= {?ref_payout?} AND
662         p.ref_depth=1 AND
663         p.points > 0 AND
664         d.userid=%s
665 LIMIT 1",
666                         array(bigintval($content['userid'])), __FUNCTION__, __LINE__);
667
668                 // Get points
669                 list($refpoints) = SQL_FETCHROW($result_ref);
670
671                 // Free result
672                 SQL_FREERESULT($result_ref);
673
674                 // Fix empty refpoints
675                 if (empty($refpoints)) $refpoints = '0';
676
677                 // Store calculated new refs to array
678                 $users['userid'][]  = $content['userid'];
679                 $users['ref'][]     = abs($cnt - $content['refs']);
680                 $users['cpoints'][] = $refpoints - $content['curr_points'];
681         } // END - while
682
683         // Free memory
684         SQL_FREERESULT($result_user);
685
686         // Sort array for refs (descending)
687         array_pk_sort($users, array('ref', 'cpoints'), 0, 1, true);
688
689         // Load prices array (!)
690         $prices = getArrayFromReferalRallyePrices($rallye);
691
692         // Merge users into prices
693         foreach ($prices['level'] as $k => $level) {
694                 // We only need to check one element in $users, see above while() block
695                 if (isset($users['userid'][$k])) {
696                         $prices['userid'][$k]  = $users['userid'][$k];
697                         if (empty($prices['userid'][$k])) $prices['userid'][$k]  = '---';
698                         $prices['ref'][$k] = $users['ref'][$k];
699                         if (empty($prices['ref'][$k])) $prices['ref'][$k] = '---';
700                         $prices['cpoints'][$k] = $users['cpoints'][$k];
701                 } // END - if
702         } // END - foreach
703
704         // Return completed array
705         return $prices;
706 }
707
708 // @TODO This function does not load min_users, min_prices, please encapsulate loading rallye data with e.g. getRallyeDataFromId()
709 function addReferalRallyeWinners ($rallye, $default=0) {
710         // First check how many prices are set
711         $result_prices = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s ORDER BY `price_level` ASC",
712                 array(bigintval($rallye)), __FUNCTION__, __LINE__);
713         $prices = SQL_NUMROWS($result_prices);
714         SQL_FREERESULT($result_prices);
715
716         // Load data
717         $DATA = getArrayFromReferalRallyeUsers($rallye);
718
719         // Generate table
720         $OUT = ''; $SW = 2;
721         for ($idx = '0'; $idx < $prices; $idx++) {
722                 // Check status
723                 //   active = 1: account is still confirmed
724                 //   active = 0: account is deleted or locked
725                 $active = countSumTotalData($DATA['userid'][$idx], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED'");
726
727                 if (empty($DATA['userid'][$idx])) $DATA['userid'][$idx] = '---';
728                 if ((empty($DATA['ref'][$idx])) || ($DATA['ref'][$idx] == '0') || ($active == '0') || ("".round($DATA['cpoints'][$idx])."" == '0') || (empty($DATA['cpoints'][$idx]))) {
729                         // Allow valid and active users with at least one ref to get points
730                         $DATA['ref'][$idx]   = '---';
731                         $DATA['userid'][$idx]   = '---';
732                 } // END - if
733
734                 if (!empty($DATA['info'][$idx])) {
735                         // Take direct infos
736                         $DATA['infos'][$idx] = $DATA['info'][$idx];
737                 } else {
738                         // Take ppints
739                         $DATA['infos'][$idx] = $DATA['points'][$idx] . ' {?POINTS?}';
740                 }
741
742                 // Prepare marking of default (maybe current user's) id
743                 $start = ''; $end = '';
744                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) {
745                         $start = '<strong>';
746                         $end   = '</strong>';
747                 } // END - if
748
749                 // Prepare content
750                 $content = array(
751                         'sw'     => $SW,
752                         'idx'    => ($idx + 1),
753                         'userid' => $DATA['userid'][$idx],
754                         'ref'    => $DATA['ref'][$idx],
755                         'infos'  => $DATA['infos'][$idx],
756                         'start'  => $start,
757                         'end'    => $end
758                 );
759
760                 // Load row template
761                 $OUT .= loadTemplate('guest_rallye_row', true, $content);
762                 $SW = 3 - $SW;
763         } // END - for
764
765         // Prepare content
766         $content = array(
767                 'rows'       => $OUT,
768                 'min_users'  => '???',
769                 'min_prices' => '???'
770         );
771
772         // Load main template and finnally return the output
773         return loadTemplate('guest_rallye', true, $content);
774 }
775
776 //
777 function purgeExpiredReferalRallyes () {
778         // Check for expired rallyes
779         $EXPIRE = 3; // @TODO The hard-coded value...
780         $result_rallye = SQL_QUERY_ESC("SELECT
781         `id`, `title`, `start_time`, `end_time`
782 FROM
783         `{?_MYSQL_PREFIX?}_rallye_data`
784 WHERE
785         `end_time` <= (UNIX_TIMESTAMP() - {?ONE_DAY?} - %s) AND
786         `expired`='Y'",
787                 array($EXPIRE), __FUNCTION__, __LINE__);
788
789         if (SQL_NUMROWS($result_rallye) > 0) {
790                 // Init SQLs
791                 initSqls();
792
793                 // Expire found rallyes and notify admin
794                 while ($content = SQL_FETCHARRAY($result_rallye)) {
795                         // Prepare data for mail template
796                         $content['start_time']  = generateDateTime($content['start_time'], 1);
797                         $content['end_time']    = generateDateTime($content['end_time']  , 1);
798                         $content['now_time']    = generateDateTime(time(), 1);
799
800                         // Send mail to admin
801                         sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_PURGED_SUBJ', $content['title']), 'admin_rallye_purged', $content);
802
803                         // Purge whole rallye
804                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_data` WHERE `id`=%s LIMIT 1",
805                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
806                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s LIMIT 1",
807                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
808                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s LIMIT 1",
809                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
810
811                         // Add task
812                         createNewTask('{--RALLYE_ADMIN_PURGED--}: ' . $content['title'], '{--RALLYE_ADMIN_PURGED_TEXT--}', 'RALLYE_PURGED');
813                 } // END - while
814
815                 // Run all SQLs
816                 runFilterChain('run_sqls');
817         } // END - if
818
819         // Free memory
820         SQL_FREERESULT($result_rallye);
821 }
822
823 //
824 function addReferalRallyeTemplateSelection ($name = 'template', $default = '') {
825         // Init variables
826         $OUT = '';
827         $ral = array();
828
829         // Check templates directory
830         $basePath = sprintf("templates/%s/html/rallye/", getLanguage());
831
832         // Read the directory
833         $templates = getArrayFromDirectory($basePath, 'rallye_', false, true, array(), '.tpl');
834
835         // And walk through
836         foreach ($templates as $read) {
837                 // Cut prefix and extension away
838                 $read = substr($read, 7, strpos($read, '.') - 7);
839
840                 // Accept only template names between 1 and 255 chars length
841                 if ((strlen($read) < 256) && (!empty($read))) {
842                         // Valid entry found!
843                         $ral[$read] = $read;
844                 } else {
845                         // Log invalid
846                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("WARNING: Template %s not used.", $read));
847                 }
848         } // END - foreach
849
850         // Do we have found templates which we can link with the new rallye?
851         if (!empty($ral[0])) {
852                 // Generate selection box for all found templates
853                 $OUT  = '<select name="' . $name . '" size="1" class="admin_select">';
854                 $OUT .= generateOptionList('/ARRAY/', array_keys($ral), array_values($ral), $default, '', 'none');
855                 $OUT .= '</select>';
856         } else {
857                 // No rallye templates found
858                 $OUT = getMessage('RALLYE_NO_TEMPLATES_FOUND');
859         }
860
861         // Return selection
862         return $OUT;
863 }
864
865 // @TODO Please document this function
866 function getReferalRallyeRefsCount ($currUserid, $old = '0') {
867         // Check current refs
868         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
869                 // Get refs from cache
870                 $cnt = '0';
871                 foreach ($GLOBALS['cache_array']['refsystem']['userid'] as $id => $userid) {
872                         // Do we have a ref for this user?
873                         //* DEBUG: */ debugOutput('id='.$id.',userid='.$userid.',userid='.$userid.',old='.$old.',level='.$GLOBALS['cache_array']['refsystem']['level'][$id]);
874                         if (($currUserid == $userid) && ($GLOBALS['cache_array']['refsystem']['level'][$id] == 1)) {
875                                 //* DEBUG: */ debugOutput('userid matches!');
876                                 foreach ($GLOBALS['cache_array']['refdepths']['level'] as $level) {
877                                         if (($level == $GLOBALS['cache_array']['refsystem']['level'][$id]) && ($level == 1)) {
878                                                 // Level does exist so abort here
879                                                 $cnt = $GLOBALS['cache_array']['refsystem']['counter'][$id];
880                                                 //* DEBUG: */ debugOutput('*'.$userid.'/'.$cnt.'*');
881                                                 break;
882                                         } elseif ($level > 1) {
883                                                 // Not interesting here...
884                                                 break;
885                                         }
886                                 } // END - foreach
887
888                                 // Abort also here!
889                                 if ($cnt > 0) break;
890                         } // END - if
891                 } // END - foreach
892
893                 //* DEBUG: */ debugOutput('<pre>'.print_r($GLOBALS['cache_array']['refsystem'], true).'</pre>');
894                 //* DEBUG: */ shutdown();
895
896                 if ($cnt > 0) {
897                         // Count cache hits
898                         incrementStatsEntry('cache_hits');
899
900                         // Remove old refs
901                         //* DEBUG: */ debugOutput('+'.$cnt.'/'.$old.'+');
902                         $cnt -= $old;
903                 } // END - if
904         } else {
905                 // Load current refs from database
906                 $result_ref = SQL_QUERY_ESC("SELECT
907         SUM(s.counter) AS cnt
908 FROM
909         `{?_MYSQL_PREFIX?}_refsystem` AS s
910 LEFT JOIN
911         `{?_MYSQL_PREFIX?}_refdepths` AS d
912 ON
913         s.level=d.level
914 WHERE
915         s.userid=%s AND
916         s.level=1",
917                         array(
918                                 bigintval($userid)
919                         ), __FUNCTION__, __LINE__);
920
921                 // Load count @TODO Can't we rewrite this to our API?
922                 list($cnt) = SQL_FETCHROW($result_ref);
923
924                 // Free result
925                 SQL_FREERESULT($result_ref);
926                 if (empty($cnt)) {
927                         $cnt = '0';
928                 } else {
929                         $cnt -= $old;
930                 }
931         }
932
933         // Return count
934         //* DEBUG: */ debugOutput('*'.$userid.'/'.$old.'/'.$cnt.'*');
935         return $cnt;
936 }
937
938 // Determines the right language string for min_users
939 function determineReferalRallyeMinimumUsers ($min_users) {
940         // Rallye ends without user limitation is the default
941         $return = getMessage('RALLYE_END_NO_USER_LIMITATION');
942
943         if ($min_users > 0) {
944                 // Rallye ends when X members are totally in your exchange
945                 $return = getMaskedMessage('RALLYE_END_USERS', $min_users);
946         } // END - if
947
948         // Return
949         return $return;
950 }
951
952 // Determines the right language string for min_prices
953 function determineReferalRallyeMinimumPrices ($min_prices) {
954         // Rallye ends without user limitation is the default
955         $return = getMessage('RALLYE_END_NO_PRICE_LIMITATION');
956
957         if ($min_prices > 0) {
958                 // Rallye ends when X members are totally in your exchange
959                 $return = getMaskedMessage('RALLYE_END_PRICES', $min_prices);
960         } // END - if
961
962         // Return
963         return $return;
964 }
965
966 // Filter for extra-autpurge
967 function FILTER_RALLYE_EXTRA_AUTOPURGE () {
968         // Check expired rallyes (hard-coded 3 days limit for displaying expired rallyes!)
969         purgeExpiredReferalRallyes();
970 }
971
972 // [EOF]
973 ?>