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