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