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