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