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