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