Fix added for extension update with always active extensions, thanks to profi-concept
[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                 case "email": $mode = "\n";     break;
146                 case "html" : $mode = "<br />\n"; break;
147         }
148
149         // Load prices
150         $result_prices = SQL_QUERY("SELECT price_level, points, info FROM "._MYSQL_PREFIX."_rallye_prices WHERE rallye_id='".$rallye."' ORDER BY price_level", __FILE__, __LINE__);
151         if (SQL_NUMROWS($result_prices) > 0)
152         {
153                 // Load prices
154                 if ($mode == "\n") $prices = RALLYE_MEMBER_PRICES_ADDED.":".$mode."------------------------------".$mode;
155                 $prices = "";
156                 while (list($level, $points, $info) = SQL_FETCHROW($result_prices))
157                 {
158                         $prices .= $level.RALLYE_PRICE.": ";
159                         if (!empty($info))
160                         {
161                                 $prices .= $info;
162                         }
163                          else
164                         {
165                                 $prices .= $points." ".POINTS;
166                         }
167                         $prices .= "".$mode;
168                 }
169
170                 // Free memory
171                 SQL_FREERESULT($result_prices);
172         }
173          else
174         {
175                 // No prices???
176                 $prices = RALLYE_MEMBER_NO_PRICES.$mode;
177         }
178         // Add last line for email mode
179         if ($mode == "\n") $prices .= "------------------------------";
180
181         // Return price list
182         return $prices;
183 }
184 //
185 function RALLYE_ADD_TOPUSERS($rallye,$default=0)
186 {
187         global $_CONFIG;
188
189         // First check how many prices are set
190         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_rallye_prices WHERE rallye_id=%s ORDER BY price_level",
191          array(bigintval($rallye)), __FILE__, __LINE__);
192         $prices = SQL_NUMROWS($result);
193         SQL_FREERESULT($result);
194
195         // And load only limited users
196         $result = SQL_QUERY_ESC("SELECT DISTINCT u.userid, u.refs, u.curr_points FROM "._MYSQL_PREFIX."_rallye_users AS u
197 LEFT JOIN "._MYSQL_PREFIX."_refsystem AS r
198 ON u.userid=r.userid
199 WHERE u.rallye_id=%s AND r.counter > 0 ORDER BY u.refs DESC",
200  array(bigintval($rallye)), __FILE__, __LINE__);
201
202         // Load users
203         $DATA = array(
204                 'uid'      => array(),
205                 'ref'      => array(),
206                 'cpoints'  => array()
207         );
208
209         while(list($uid, $refs, $cpoints) = SQL_FETCHROW($result))
210         {
211                 // Get current refs
212                 $cnt = RALLYE_GET_REFCOUNT($uid, $refs);
213
214                 // Points of ref's
215                 $result_ref = SQL_QUERY_ESC("SELECT DISTINCT p.points FROM "._MYSQL_PREFIX."_user_points AS p
216 LEFT JOIN "._MYSQL_PREFIX."_user_data AS d
217 ON p.userid=d.userid
218 WHERE d.userid=%s AND d.status='CONFIRMED' AND p.ref_depth=1 AND d.max_mails > 0 AND d.mails_confirmed >= %s
219 LIMIT 1", array(bigintval($uid), $_CONFIG['ref_payout']), __FILE__, __LINE__);
220                 list($refpoints) = SQL_FETCHROW($result_ref);
221                 SQL_FREERESULT($result_ref);
222
223                 if (empty($refpoints)) $refpoints = 0;
224
225                 // Init userid for list
226                 $_uid = "---";
227                 // List only users with at least one ref!
228                 //* DEBUG: */ echo "*".$cnt."/".$uid."/".$cpoints."/".$refpoints."*<br />\n";
229                 if (($cnt > 0) && ($refpoints > $cpoints)) { $_uid = $uid; } else { $cnt = ""; }
230
231                 // Save values to array
232                 $DATA['uid'][]     = $_uid;
233                 $DATA['ref'][]     = $cnt;
234                 $DATA['cpoints'][] = $cpoints;
235         }
236
237         // Free memory
238         SQL_FREERESULT($result);
239
240         // Sort whole array
241         array_pk_sort($DATA, array("ref", "cpoints"), 0, 1, true);
242
243         // Generate table
244         $OUT = LOAD_TEMPLATE("guest_rallye_header", true);
245         $SW = 2;
246         for ($idx = 0; $idx < $prices; $idx++)
247         {
248                 if (empty($DATA['uid'][$idx])) $DATA['uid'][$idx] = "---";
249                 if (empty($DATA['ref'][$idx])) $DATA['ref'][$idx] = "---";
250                 // Add row
251                 $OUT .= "<TR>
252   <TD class=\"switch_sw".$SW." bottom2\">&nbsp;&nbsp;".($idx+1).".</TD>
253   <TD align=\"center\" class=\"switch_sw".$SW." bottom2\">";
254                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "<STRONG>";
255                 $OUT .= $DATA['uid'][$idx];
256                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "</STRONG>";
257                 $OUT .= "</TD>
258   <TD align=\"center\" class=\"switch_sw".$SW." bottom2\">";
259                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "<STRONG>";
260                 $OUT .= $DATA['ref'][$idx];
261                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "</STRONG>";
262                 $OUT .= "</TD>
263 </TR>\n";
264                 $SW = 3 - $SW;
265         }
266         // Add footer
267         $OUT .= LOAD_TEMPLATE("guest_rallye_footer", true);
268
269         // And finnally return the output
270         return $OUT;
271 }
272 // Run this function only when a new member has confirmed his email address!
273 function RALLYE_AUTOADD_USER($uid)
274 {
275         global $DATA;
276         $ADD = "";
277
278         // Updated extension?
279         if (GET_EXT_VERSION("rallye") >= "0.2.0") {
280                 $ADD .= ", min_users, min_prices";
281         } // END - if
282
283         // Check for an auto-add rallye
284         $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__);
285         if (SQL_NUMROWS($result) == 1) {
286                 // Init variables
287                 $min_users = 0; $min_prices = 0;
288                 // Load data
289                 if (GET_EXT_VERSION("rallye") >= "0.2.0") {
290                         list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
291                 } else {
292                         list($id, $title, $start, $end, $notify) = SQL_FETCHROW($result);
293                 }
294
295                 // Free result
296                 SQL_FREERESULT($result);
297
298                 // Check if line is already included...
299                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_rallye_users WHERE rallye_id=%s AND userid=%s LIMIT 1",
300                         array(bigintval($id), bigintval($uid)), __FILE__, __LINE__);
301
302                 // Is this user added?
303                 if (SQL_NUMROWS($result) == 0) {
304                         // Add userid and his ref count to table
305                         $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_rallye_users (rallye_id, userid, refs)
306 VALUES ('%s','%s','0')",
307  array(bigintval($id), bigintval($uid)), __FILE__, __LINE__);
308                 } else {
309                         // Free memory
310                         SQL_FREERESULT($result);
311                 }
312
313                 if ($notify == "Y") {
314                         // Transfer all neccessary data to the global $DATA array
315                         $DATA['start'] = MAKE_DATETIME($start, "2");
316                         $DATA['end']   = MAKE_DATETIME($end  , "2");
317                         $DATA['now_t'] = MAKE_DATETIME(time(), "2");
318                         $DATA['title'] = $title;
319                         $DATA['id']    = $id;  // ID for the rallye details link
320                         $DATA['ref']   = 0;
321                         $DATA['refs']  = GET_TOTAL_DATA($uid, "user_data", "userid", "refid", true);
322
323                         // Load prices
324                         $prices = RALLYE_ADD_PRICES($id);
325
326                         if ($min_users == 0) {
327                                 // Rallye ends without user limitation
328                                 $DATA['min_users'] = RALLYE_END_NO_USER_LIMITATION;
329                         } else {
330                                 // Rallye ends when X members are totally in your exchange
331                                 $DATA['min_users'] = RALLYE_END_USERS_1." ".$min_users." ".RALLYE_END_USERS_2;
332                         }
333
334                         if ($min_prices == 0) {
335                                 // Rallye ends without user limitation
336                                 $DATA['min_prices'] = RALLYE_END_NO_PRICE_LIMITATION;
337                         } else {
338                                 // Rallye ends when X members are totally in your exchange
339                                 $DATA['min_prices'] = RALLYE_END_PRICES_1." ".$min_prices." ".RALLYE_END_PRICES_2;
340                         }
341
342                         // Send notification to member
343                         $msg = LOAD_EMAIL_TEMPLATE("member_rallye_notify", array('prices' => $prices), $uid);
344                         SEND_EMAIL($uid, RALLYE_MEMBER_NOTIFY.$title, $msg);
345                 } // END - if
346         } // END - if
347 }
348 //
349 function RALLYE_EXPIRE_RALLYES($result)
350 {
351         global $DATA, $_CONFIG;
352
353         // Load rallye data
354         list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
355         SQL_FREERESULT($result);
356
357         // Load users array (!) with assigned prices
358         $prices = RALLYE_LOAD_USERS_ARRAY($id);
359
360         // Init array
361         $DATA = array(); $cnt = 0;
362         $users = array();
363         $DATA['title']  = $title;
364         $DATA['start']  = MAKE_DATETIME($start, "1");
365         $DATA['end']    = MAKE_DATETIME($end  , "1");
366         $DATA['now_t']  = MAKE_DATETIME(time(), "1");
367
368         // Just count...
369         $TOTAL = 0;
370         foreach($prices['uid'] as $key => $uid) {
371                 // Check status
372                 //   active = 1: account is still confirmed
373                 //   active = 0: account is deleted or locked
374                 $result = SQL_QUERY_ESC("SELECT COUNT(userid) AS active
375 FROM "._MYSQL_PREFIX."_user_data
376 WHERE userid=%s AND status='CONFIRMED'
377 LIMIT 1", array(bigintval($uid)), __FILE__, __LINE__);
378                 list($active) = SQL_FETCHROW($result);
379                 SQL_FREERESULT($result);
380
381                 $prices['active'][$key] = $active;
382
383                 // Allow valid and active users with at least one ref to get points
384                 if (($uid > 0) && ($prices['ref'][$key] > 0) && ($active == 1) && ($prices['cpoints'][$key] > 0)) {
385                         $TOTAL++;
386                 } // END - if
387         } // END - foreach
388
389         if (($TOTAL < $min_prices) || ($TOTAL == 0)) {
390                 // Do not end this rallye!
391                 unset($DATA);
392                 return;
393         } // END - if
394
395         // Expire rallye
396         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_rallye_data SET expired='Y' WHERE id=%s LIMIT 1",
397                 array(bigintval($id)), __FILE__, __LINE__);
398
399         // Run array through (by uid is the most important 2nd-level-array)
400         foreach($prices['uid'] as $key => $uid) {
401                 // Allow valid and active users with at least one ref to get points
402                 if (($uid > 0) && ($prices['ref'][$key] > 0) && ($prices['active'][$key] == 1) && ($prices['cpoints'][$key] > 0)) {
403                         // Transfer data to array for the mail template
404                         $DATA['level']  = $prices['level'][$key];
405                         $DATA['points'] = $prices['points'][$key];
406                         $DATA['info']   = $prices['info'][$key];
407                         $DATA['ref']    = $prices['ref'][$key];
408
409                         if ($DATA['points'] > 0) {
410                                 // Add points directly to user's account
411                                 ADD_POINTS_REFSYSTEM($uid, $DATA['points'], false, "0", false, "direct");
412                         } // END - if
413
414                         if ($notify == "Y") {
415                                 // Prepare infos for the mail template
416                                 if (!empty($DATA['info'])) {
417                                         // Take direct infos
418                                         $DATA['infos'] = $DATA['info'];
419                                 } else {
420                                         // Take points
421                                         $DATA['infos'] = $DATA['points']." ".POINTS;
422                                 }
423
424                                 // Add suffix to template name
425                                 $template = "member_rallye_expired";
426                                 if ($DATA['level'] == 1) {
427                                         // The winner!
428                                         $template .= "_gold";
429                                 } elseif ($DATA['level'] == 2) {
430                                         // The vice winner!
431                                         $template .= "_silver";
432                                 } elseif ($DATA['level'] == 3) {
433                                         // The bronce winner
434                                         $template .= "_bronce";
435                                 }
436
437                                 // Load template
438                                 $msg = LOAD_EMAIL_TEMPLATE($template, $DATA, $uid);
439                                 SEND_EMAIL($uid, RALLYE_MEMBER_EXPIRED.": ".$DATA['level']." "._RALLYE_PRICE, $msg);
440                         } // END - if
441
442                         // Count userid
443                         $cnt++;
444                         $users['uid'][$uid] = $uid;
445                         $users['poi'][$uid] = $DATA['infos'];
446                 } // END - if
447         } // END - foreach
448
449         // Select template depending on notfication is switch on / off
450         if ($notify == "Y") {
451                 $templ = "admin_rallye_expired";
452         } elseif (is_array($users['uid'])) {
453                 $templ = "admin_rallye_expired_no";
454                 $cnt = RALLYE_LOAD_USER_DATA($users);
455         }
456
457         // Send mail to admin
458         SEND_ADMIN_NOTIFICATION(RALLYE_ADMIN_EXPIRED.": ".$title, $templ, $cnt, 0);
459
460         // Add task
461         $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (status, task_type, subject, text, task_created)
462 VALUES ('NEW','RALLYE_EXPIRED','".RALLYE_ADMIN_EXPIRED.": %s','".RALLYE_ADMIN_EXPIRED_TEXT."',UNIX_TIMESTAMP())",
463  array($title), __FILE__, __LINE__);
464
465         // All work done here...
466 }
467 //
468 function RALLYE_LOAD_USER_DATA($uids_array)
469 {
470         // Implode user ids
471         $uid_string = implode(",", $uids_array['uid']);
472
473         // Load users
474         $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",
475          array($uid_string, count($uids_array)), __FILE__, __LINE__);
476         $ret = "";
477         while (list($u, $gender, $surname, $family, $email) = SQL_FETCHROW($result))
478         {
479                 $ret .= TRANSLATE_GENDER($gender)." ".$surname." ".$family." (".$email.") - ".$uids_array['poi'][$u]."\n";
480         }
481
482         // Return result
483         return substr($ret, 0, -1);
484 }
485 //
486 function RALLYE_LOAD_PRICES_ARRAY($rallye)
487 {
488         // Init multi array
489         $prices = array(
490                 'level'  => array(),
491                 'points' => array(),
492                 'info'   => array()
493         );
494
495         // Load prices
496         $result = SQL_QUERY_ESC("SELECT price_level, points, info FROM "._MYSQL_PREFIX."_rallye_prices WHERE rallye_id=%s ORDER BY price_level",
497          array(bigintval($rallye)), __FILE__, __LINE__);
498         while(list($level, $points, $info) = SQL_FETCHROW($result))
499         {
500                 $prices['level'][]  = $level;
501                 $prices['points'][] = $points;
502                 $prices['info'][]   = $info;
503         }
504
505         // Free memory
506         SQL_FREERESULT($result);
507
508         // Return array
509         return $prices;
510 }
511 //
512 function RALLYE_LOAD_USERS_ARRAY($rallye)
513 {
514         global $_CONFIG;
515
516         // Fix zero points to 0.00000
517         if ($_CONFIG['ref_payout'] == "0") $_CONFIG['ref_payout'] = "0.00000";
518
519         // Init multi array
520         $users = array(
521                 'uid'     => array(),
522                 'ref'     => array(),
523                 'cpoints' => array(),
524         );
525
526         // Load users                          uid    old  points earned
527         $result_user = SQL_QUERY_ESC("SELECT userid, refs, curr_points FROM "._MYSQL_PREFIX."_rallye_users WHERE rallye_id=%s ORDER BY userid",
528          array(bigintval($rallye)), __FILE__, __LINE__);
529         while(list($uid, $refs, $cpoints) = SQL_FETCHROW($result_user))
530         {
531                 // Load current ref count
532                 $cnt = RALLYE_GET_REFCOUNT($uid, $refs);
533
534                 // Points of ref's
535                 $result_ref = SQL_QUERY_ESC("SELECT DISTINCT SUM(p.points)
536 FROM "._MYSQL_PREFIX."_user_points AS p
537 LEFT JOIN "._MYSQL_PREFIX."_user_data AS d
538 ON p.userid=d.userid
539 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",
540  array($_CONFIG['ref_payout'], bigintval($uid)), __FILE__, __LINE__);
541                 list($refpoints) = SQL_FETCHROW($result_ref);
542                 SQL_FREERESULT($result_ref);
543
544                 if (empty($refpoints)) $refpoints = 0;
545
546                 // Store calculated new refs to array
547                 $users['uid'][]     = $uid;
548                 $users['ref'][]     = abs($cnt - $refs);
549                 $users['cpoints'][] = $refpoints - $cpoints;
550         }
551
552         // Free memory
553         SQL_FREERESULT($result_user);
554
555         // Sort array for refs (descending)
556         array_pk_sort($users, array("ref", "cpoints"), 0, 1, true);
557
558         // Load prices array (!)
559         $prices = RALLYE_LOAD_PRICES_ARRAY($rallye);
560
561         // Merge users into prices
562         foreach ($prices['level'] as $k => $lvl)
563         {
564                 $prices['uid'][$k]  = $users['uid'][$k];
565                 if (empty($prices['uid'][$k])) $prices['uid'][$k]  = "---";
566                 $prices['ref'][$k] = $users['ref'][$k];
567                 if (empty($prices['ref'][$k])) $prices['ref'][$k] = "---";
568                 $prices['cpoints'][$k] = $users['cpoints'][$k];
569         }
570
571         // Return completed array
572         return $prices;
573 }
574 //
575 function RALLYE_LIST_WINNERS($rallye,$default=0)
576 {
577         // First check how many prices are set
578         $result_prices = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_rallye_prices WHERE rallye_id=%s ORDER BY price_level",
579          array(bigintval($rallye)), __FILE__, __LINE__);
580         $prices = SQL_NUMROWS($result_prices);
581         SQL_FREERESULT($result_prices);
582
583         // Load data
584         $DATA = RALLYE_LOAD_USERS_ARRAY($rallye);
585
586         // Generate table
587         $OUT = LOAD_TEMPLATE("guest_rallye_expired_header", true);
588         $SW = 2;
589         for ($idx = 0; $idx < $prices; $idx++)
590         {
591                 // Check status
592                 //   active = 1: account is still confirmed
593                 //   active = 0: account is deleted or locked
594                 $result_active = SQL_QUERY_ESC("SELECT COUNT(userid) FROM "._MYSQL_PREFIX."_user_data WHERE userid=%s AND status='CONFIRMED' LIMIT 1",
595                  array(bigintval($DATA['uid'][$idx])), __FILE__, __LINE__);
596                 list($active) = SQL_FETCHROW($result_active);
597                 SQL_FREERESULT($result_active);
598
599                 if (empty($DATA['uid'][$idx])) $DATA['uid'][$idx] = "---";
600                 if ((empty($DATA['ref'][$idx])) || ($DATA['ref'][$idx] == 0) || ($active == 0) || ("".round($DATA['cpoints'][$idx])."" == "0") || (empty($DATA['cpoints'][$idx])))
601                 {
602                         // Allow valid and active users with at least one ref to get points
603                         $DATA['ref'][$idx]   = "---";
604                         $DATA['uid'][$idx]   = "---";
605                 }
606                 if (!empty($DATA['info'][$idx]))
607                 {
608                         // Take direct infos
609                         $DATA['infos'][$idx] = $DATA['info'][$idx];
610                 }
611                  else
612                 {
613                         // Take ppints
614                         $DATA['infos'][$idx] = $DATA['points'][$idx]." ".POINTS;
615                 }
616
617                 // Add row
618                 $ADD = "";
619                 $OUT .= "<TR>
620   <TD class=\"switch_sw".$SW." bottom2".$ADD."\">&nbsp;&nbsp;".($idx+1).".</TD>
621   <TD align=\"center\" class=\"switch_sw".$SW." bottom2".$ADD."\">";
622                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "<STRONG>";
623                 $OUT .= $DATA['uid'][$idx];
624                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "</STRONG>";
625                 $OUT .= "</TD>
626   <TD align=\"center\" class=\"switch_sw".$SW." bottom2".$ADD."\">";
627                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "<STRONG>";
628                 $OUT .= $DATA['ref'][$idx];
629                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "</STRONG>";
630                 $OUT .= "</TD>
631   <TD align=\"center\" class=\"switch_sw".$SW." bottom2".$ADD."\">";
632                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "<STRONG>";
633                 $OUT .= $DATA['infos'][$idx];
634                 if (($DATA['uid'][$idx] == $default) && ($default > 0)) $OUT .= "</STRONG>";
635                 $OUT .= "</TD>
636 </TR>\n";
637                 $SW = 3 - $SW;
638         }
639         // Add footer
640         $OUT .= LOAD_TEMPLATE("guest_rallye_expired_footer", true);
641
642         // And finnally return the output
643         return $OUT;
644 }
645 //
646 function RALLYE_DELETE_EXPIRED_RALLYES()
647 {
648         global $DATA, $_CONFIG;
649
650         // Check for expired rallyes
651         $EXPIRE = $_CONFIG['one_day'] * 3; // @TODO The hard-coded value...
652         $result_rallye = SQL_QUERY_ESC("SELECT id, title, start_time, end_time
653 FROM "._MYSQL_PREFIX."_rallye_data
654 WHERE end_time <= (UNIX_TIMESTAMP() - %s) AND expired='Y'",
655                 array($EXPIRE), __FILE__, __LINE__);
656
657         if (SQL_NUMROWS($result_rallye) > 0)
658         {
659                 // Expire found rallyes and notify admin
660                 while(list($id, $title, $start, $end) = SQL_FETCHROW($result_rallye))
661                 {
662                         // Prepare data for mail template
663                         $DATA['title']  = $title;
664                         $DATA['start']  = MAKE_DATETIME($start, "1");
665                         $DATA['end']    = MAKE_DATETIME($end  , "1");
666                         $DATA['now_t']  = MAKE_DATETIME(time(), "1");
667
668                         // Send mail to admin
669                         SEND_ADMIN_NOTIFICATION(RALLYE_ADMIN_PURGED.": ".$title, "admin_rallye_purged", "", 0);
670
671                         // Purge whole rallye
672                         $result_purge = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_rallye_data WHERE id=%s LIMIT 1",
673                          array(bigintval($id)), __FILE__, __LINE__);
674                         $result_purge = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_rallye_prices WHERE rallye_id=%s LIMIT 1",
675                          array(bigintval($id)), __FILE__, __LINE__);
676                         $result_purge = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_rallye_users WHERE rallye_id=%s LIMIT 1",
677                          array(bigintval($id)), __FILE__, __LINE__);
678                 }
679
680                 // Add task
681                 $result_task = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (status, task_type, subject, text, task_created)
682 VALUES ('NEW','RALLYE_PURGED','".RALLYE_ADMIN_PURGED.": %s','".RALLYE_ADMIN_PURGED_TEXT."',UNIX_TIMESTAMP())",
683  array($title), __FILE__, __LINE__);
684         }
685
686         // Free memory
687         SQL_FREERESULT($result_rallye);
688 }
689 //
690 function RALLYE_TEMPLATE_SELECTION($name="template", $default="")
691 {
692         // Check templates directory
693         $OUT = ""; $ral = array();
694         $BASE = sprintf("%stemplates/%s/html/rallye/", PATH, GET_LANGUAGE());
695         $dir = opendir($BASE);
696         while ($read = readdir($dir))
697         {
698                 // If it is no dir (so a file)
699                 if (!is_dir($BASE.$read))
700                 {
701                         // Accept only templates matching with rallye_????.tpl.xx
702                         if (eregi("^rallye_.*\.tpl", $read))
703                         {
704                                 $read = substr($read, 7, strpos($read, ".") - 7);
705                                 // Accept only template names between 1 and 255 chars length
706                                 if ((strlen($read) < 256) && (!empty($read))) $ral[] = $read;
707                         }
708                 }
709         }
710         closedir($dir);
711
712         // Do we have found templates which we can link with the new rallye?
713         if (!empty($ral[0]))
714         {
715                 // Generate selection box for all found templates
716                 $OUT  = "<SELECT name=\"".$name."\" size=\"1\" class=\"admin_select\">
717   <OPTION value=\"\">".SELECT_NONE."</OPTION>\n";
718                 foreach ($ral as $rallye)
719                 {
720                      $OUT .= "  <OPTION value=\"".$rallye."\"";
721                         if ($default == $rallye) $OUT .= " selected default";
722                         $OUT .= ">".$rallye."</OPTION>\n";
723                 }
724                 $OUT .= "</SELECT>\n";
725         }
726          else
727         {
728                 // No rallye templates found
729                 $OUT = RALLYE_NO_TEMPLATES_FOUND;
730         }
731
732         // Return selection
733         return $OUT;
734 }
735 //
736 function RALLYE_GET_REFCOUNT($uid, $old=0) {
737         global $_CONFIG, $cacheArray;
738
739         // Check current refs
740         if (GET_EXT_VERSION("cache") >= "0.1.2") {
741                 // Get refs from cache
742                 $cnt = 0;
743                 foreach ($cacheArray['ref_system']['userid'] as $id => $u_id) {
744                         // Do we have a ref for this user?
745                         //* DEBUG: */ echo "id={$id},u_id={$u_id},uid={$uid},old={$old},level={$cacheArray['ref_system']['level'][$id]}<br />\n";
746                         if (($u_id == $uid) && ($cacheArray['ref_system']['level'][$id] == 1)) {
747                                 //* DEBUG: */ echo "uid matches!<br />\n";
748                                 foreach ($cacheArray['ref_depths']['level'] as $level) {
749                                         if (($level == $cacheArray['ref_system']['level'][$id]) && ($level == 1)) {
750                                                 // Level does exist so abort here
751                                                 $cnt = $cacheArray['ref_system']['counter'][$id];
752                                                 //* DEBUG: */ echo "*".$uid."/".$cnt."*<br />";
753                                                 break;
754                                         } elseif ($level > 1) {
755                                                 // Not interesting here...
756                                                 break;
757                                         }
758                                 }
759
760                                 // Abort also here!
761                                 if ($cnt > 0) break;
762                         }
763                 }
764                 //* DEBUG: */ echo "<PRE>";
765                 //* DEBUG: */ print_r($cacheArray['ref_system']);
766                 //* DEBUG: */ echo "</PRE>";
767                 //* DEBUG: */ die();
768
769                 if ($cnt > 0) {
770                         // Count cache hits
771                         if (isset($_CONFIG['cache_hits'])) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
772
773                         // Remove old refs
774                         //* DEBUG: */ echo "+".$cnt."/".$old."+<br />";
775                         $cnt -= $old;
776                 }
777         } else {
778                 // Load current refs from database
779                 $result_ref = SQL_QUERY_ESC("SELECT DISTINCT SUM(s.counter) AS cnt
780 FROM "._MYSQL_PREFIX."_refsystem AS s
781 LEFT JOIN "._MYSQL_PREFIX."_refdepths AS d
782 ON s.level=d.level
783 WHERE s.userid=%s AND s.level=1", array(bigintval($uid)), __FILE__, __LINE__);
784                 list($cnt) = SQL_FETCHROW($result_ref);
785                 SQL_FREERESULT($result_ref);
786                 if (empty($cnt))
787                 {
788                         $cnt = 0;
789                 }
790                  else
791                 {
792                         $cnt -= $old;
793                 }
794         }
795
796         // Return count
797         //* DEBUG: */ echo "*".$uid."/".$old."/".$cnt."*<br />";
798         return $cnt;
799 }
800 //
801 ?>