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