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