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