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