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