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