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