]> git.mxchange.org Git - mailer.git/blob - inc/libs/rallye_functions.php
22ddd6cb3d03af37173fbb65bfd981b95dfad69c
[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
325                 // Load data
326                 if (getExtensionVersion('rallye') >= '0.2.0') {
327                         list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
328                 } else {
329                         list($id, $title, $start, $end, $notify) = SQL_FETCHROW($result);
330                 }
331
332                 // Free result
333                 SQL_FREERESULT($result);
334
335                 if ($notify == 'Y') {
336                         // Transfer all neccessary data to the global $content array
337                         $content['start'] = generateDateTime($start, 2);
338                         $content['end']   = generateDateTime($end  , 2);
339                         $content['now_t'] = generateDateTime(time(), 2);
340                         $content['title'] = $title;
341                         $content['id']    = $id;  // id for the rallye details link
342                         $content['ref']   = '0';
343                         $content['refs']  = countSumTotalData($userid, 'user_data', 'userid', 'refid', true);
344
345                         // Load prices
346                         $content['prices'] = addReferalRallyePrices($id);
347
348                         // Determine min_users/prices tring
349                         $content['min_users']  = determineReferalRallyeMinimumUsers($min_users);
350                         $content['min_prices'] = determineReferalRallyeMinimumPrices($min_prices);
351
352                         // Send notification to member
353                         $message = loadEmailTemplate('member_rallye_notify', $content, $userid);
354                         sendEmail($userid, sprintf(getMessage('RALLYE_MEMBER_NOTIFY'), $title), $message);
355                 } // END - if
356
357                 // Check if line is already included...
358                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s AND `userid`=%s LIMIT 1",
359                         array(
360                                 bigintval($id),
361                                 bigintval($userid)
362                         ), __FUNCTION__, __LINE__);
363
364                 // Is this user added?
365                 if (SQL_NUMROWS($result) < 1) {
366                         // Add userid and his ref count to table
367                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_rallye_users` (`rallye_id`, `userid`, `refs`)
368 VALUES ('%s','%s',0)",
369                                 array(
370                                         bigintval($id),
371                                         bigintval($userid)
372                                 ), __FUNCTION__, __LINE__);
373                 } // END - if
374
375                 // Free memory
376                 SQL_FREERESULT($result);
377         } // END - if
378 }
379
380 //
381 function markReferalRallyesAsExpired ($result) {
382         global $DATA;
383
384         // Load rallye data
385         list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
386
387         // Free result
388         SQL_FREERESULT($result);
389
390         // Load users array (!) with assigned prices
391         $prices = getArrayFromReferalRallyeUsers($id);
392
393         // Init array
394         $DATA = array(); $cnt = '0';
395         $users = array();
396         $DATA['title']  = $title;
397         $DATA['start']  = generateDateTime($start, 1);
398         $DATA['end']    = generateDateTime($end  , 1);
399         $DATA['now_t']  = generateDateTime(time(), 1);
400
401         // Just count...
402         $total = '0';
403         foreach($prices['userid'] as $key => $userid) {
404                 // Check status
405                 //   active = 1: account is still confirmed
406                 //   active = '0': account is deleted or locked
407                 $result = SQL_QUERY_ESC("SELECT
408         COUNT(`userid`) AS active
409 FROM
410         `{?_MYSQL_PREFIX?}_user_data`
411 WHERE
412         `userid`=%s AND `status`='CONFIRMED'
413 LIMIT 1",
414                         array(bigintval($userid)), __FUNCTION__, __LINE__);
415                 list($active) = SQL_FETCHROW($result);
416                 SQL_FREERESULT($result);
417
418                 $prices['active'][$key] = $active;
419
420                 // Allow valid and active users with at least one ref to get points
421                 if (($userid > 0) && ($prices['ref'][$key] > 0) && ($active == 1) && ($prices['cpoints'][$key] > 0)) {
422                         $total++;
423                 } // END - if
424         } // END - foreach
425
426         if (($total < $min_prices) || ($total == '0')) {
427                 // Do not end this rallye!
428                 unset($DATA);
429                 return;
430         } // END - if
431
432         // Expire rallye
433         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_rallye_data` SET `expired`='Y' WHERE `id`=%s LIMIT 1",
434         array(bigintval($id)), __FUNCTION__, __LINE__);
435
436         // Run array through (by userid is the most important 2nd-level-array)
437         foreach($prices['userid'] as $key => $userid) {
438                 // Allow valid and active users with at least one ref to get points
439                 if (($userid > 0) && ($prices['ref'][$key] > 0) && ($prices['active'][$key] == 1) && ($prices['cpoints'][$key] > 0)) {
440                         // Transfer data to array for the mail template
441                         $DATA['level']  = $prices['level'][$key];
442                         $DATA['points'] = $prices['points'][$key];
443                         $DATA['info']   = $prices['info'][$key];
444                         $DATA['ref']    = $prices['ref'][$key];
445
446                         // Default is other
447                         $winnerLevel = 'other';
448
449                         // Determine winner level
450                         if ($DATA['level'] == 1) {
451                                 // The winner!
452                                 $winnerLevel = '_gold';
453                         } elseif ($DATA['level'] == 2) {
454                                 // The vice winner!
455                                 $winnerLevel = '_silver';
456                         } elseif ($DATA['level'] == 3) {
457                                 // The bronce winner
458                                 $winnerLevel = '_bronce';
459                         }
460
461                         if ($DATA['points'] > 0) {
462                                 // Add points directly to user's account
463                                 addPointsDirectly('rallye_winner' . $winnerLevel, $userid, $DATA['points']);
464                         } // END - if
465
466                         if ($notify == 'Y') {
467                                 // Prepare infos for the mail template
468                                 if (!empty($DATA['info'])) {
469                                         // Take direct infos
470                                         $DATA['infos'] = $DATA['info'];
471                                 } else {
472                                         // Take points
473                                         $DATA['infos'] = $DATA['points'] . ' {?POINTS?}';
474                                 }
475
476                                 // Add suffix to template name
477                                 $template = 'member_rallye_expired' . $winnerLevel;
478
479                                 // Load template
480                                 $message = loadEmailTemplate($template, $DATA, $userid);
481                                 sendEmail($userid, sprintf(getMessage('RALLYE_MEMBER_EXPIRED_SUBJ'), $DATA['level']), $message);
482                         } // END - if
483
484                         // Count userid
485                         $cnt++;
486                         $users['userid'][$userid] = $userid;
487                         $users['poi'][$userid] = $DATA['infos'];
488                 } // END - if
489         } // END - foreach
490
491         // Select template depending on notfication is switch on / off
492         if ($notify == 'Y') {
493                 $templ = "admin_rallye_expired";
494         } elseif (is_array($users['userid'])) {
495                 $templ = "admin_rallye_expired_no";
496                 $cnt = getReferalRallyeUserDataFromArray($users);
497         }
498
499         // Send mail to admin
500         sendAdminNotification(sprintf(getMessage('RALLYE_ADMIN_EXPIRED_SUBJ'), $title), $templ, $cnt, 0);
501
502         // Add task
503         createNewTask('{--RALLYE_ADMIN_EXPIRED--}: ' . $title, '{--RALLYE_ADMIN_EXPIRED_TEXT--}', 'RALLYE_EXPIRED');
504 }
505
506 //
507 function getReferalRallyeUserDataFromArray ($userIds) {
508         // Implode user ids
509         $userid_string = implode(',', $userIds['userid']);
510
511         // Init result string
512         $ret = '';
513
514         // Load users
515         $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",
516                 array($userid_string, count($userIds)), __FUNCTION__, __LINE__);
517         while ($content = SQL_FETCHARRAY($result)) {
518                 // Construct the message masked and add it
519                 $ret .= sprintf("%s %s %s (%s) - %s\n",
520                         translateGender($content['gender']),
521                         $content['surname'],
522                         $content['family'],
523                         $content['email'],
524                         $userIds['poi'][$content['userid']]
525                 );
526         } // END - while
527
528         // Return result
529         return substr($ret, 0, -1);
530 }
531
532 //
533 function getArrayFromReferalRallyePrices ($rallye) {
534         // Init multi array
535         $prices = array(
536                 'level'  => array(),
537                 'points' => array(),
538                 'info'   => array()
539         );
540
541         // Load prices
542         $result = SQL_QUERY_ESC("SELECT price_level, points, info FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE rallye_id=%s ORDER BY price_level",
543         array(bigintval($rallye)), __FUNCTION__, __LINE__);
544
545         // Transfer elements
546         while ($content = SQL_FETCHARRAY($result)) {
547                 $prices['level'][]  = $content['price_level'];
548                 $prices['points'][] = $content['points'];
549                 $prices['info'][]   = $content['info'];
550         } // END - while
551
552         // Free memory
553         SQL_FREERESULT($result);
554
555         // Return array
556         return $prices;
557 }
558
559 //
560 function getArrayFromReferalRallyeUsers ($rallye) {
561         // Fix zero points to 0.00000
562         if (getConfig('ref_payout') == '0') setConfigEntry('ref_payout', '0.00000');
563
564         // Init multi array
565         $users = array(
566                 'userid'     => array(),
567                 'ref'     => array(),
568                 'cpoints' => array(),
569         );
570
571         // Load users                          userid    old   points earned
572         $result_user = SQL_QUERY_ESC("SELECT `userid`, `refs`, `curr_points` FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s ORDER BY `userid` ASC",
573                 array(bigintval($rallye)), __FUNCTION__, __LINE__);
574         while ($content = SQL_FETCHARRAY($result_user)) {
575                 // Load current ref count
576                 $cnt = getReferalRallyeRefsCount($content['userid'], $content['refs']);
577
578                 // Points of ref's
579                 $result_ref = SQL_QUERY_ESC("SELECT
580         SUM(p.points) AS points
581 FROM
582         `{?_MYSQL_PREFIX?}_user_points` AS p
583 LEFT JOIN
584         `{?_MYSQL_PREFIX?}_user_data` AS d
585 ON
586         p.userid=d.userid
587 WHERE
588         d.`status`='CONFIRMED' AND
589         d.max_mails > 0 AND
590         d.mails_confirmed >= {?ref_payout?} AND
591         p.ref_depth=1 AND
592         p.points > 0 AND
593         d.userid=%s
594 LIMIT 1",
595                         array(bigintval($content['userid'])), __FUNCTION__, __LINE__);
596
597                 // Get points
598                 list($refpoints) = SQL_FETCHROW($result_ref);
599
600                 // Free result
601                 SQL_FREERESULT($result_ref);
602
603                 // Fix empty refpoints
604                 if (empty($refpoints)) $refpoints = '0';
605
606                 // Store calculated new refs to array
607                 $users['userid'][]     = $content['userid'];
608                 $users['ref'][]     = abs($cnt - $content['refs']);
609                 $users['cpoints'][] = $refpoints - $content['curr_points'];
610         } // END - while
611
612         // Free memory
613         SQL_FREERESULT($result_user);
614
615         // Sort array for refs (descending)
616         array_pk_sort($users, array("ref", "cpoints"), 0, 1, true);
617
618         // Load prices array (!)
619         $prices = getArrayFromReferalRallyePrices($rallye);
620
621         // Merge users into prices
622         foreach ($prices['level'] as $k => $level) {
623                 // We only need to check one element in $users, see above while() block
624                 if (isset($users['userid'][$k])) {
625                         $prices['userid'][$k]  = $users['userid'][$k];
626                         if (empty($prices['userid'][$k])) $prices['userid'][$k]  = '---';
627                         $prices['ref'][$k] = $users['ref'][$k];
628                         if (empty($prices['ref'][$k])) $prices['ref'][$k] = '---';
629                         $prices['cpoints'][$k] = $users['cpoints'][$k];
630                 } // END - if
631         } // END - foreach
632
633         // Return completed array
634         return $prices;
635 }
636
637 //
638 function addReferalRallyeWinners ($rallye, $default=0) {
639         // First check how many prices are set
640         $result_prices = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s ORDER BY `price_level` ASC",
641                 array(bigintval($rallye)), __FUNCTION__, __LINE__);
642         $prices = SQL_NUMROWS($result_prices);
643         SQL_FREERESULT($result_prices);
644
645         // Load data
646         $DATA = getArrayFromReferalRallyeUsers($rallye);
647
648         // Generate table
649         $OUT = loadTemplate('guest_rallye_expired_header', true);
650         $SW = 2;
651         for ($idx = '0'; $idx < $prices; $idx++) {
652                 // Check status
653                 //   active = 1: account is still confirmed
654                 //   active = '0': account is deleted or locked
655                 $active = countSumTotalData($DATA['userid'][$idx], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED'");
656
657                 if (empty($DATA['userid'][$idx])) $DATA['userid'][$idx] = '---';
658                 if ((empty($DATA['ref'][$idx])) || ($DATA['ref'][$idx] == '0') || ($active == '0') || ("".round($DATA['cpoints'][$idx])."" == '0') || (empty($DATA['cpoints'][$idx]))) {
659                         // Allow valid and active users with at least one ref to get points
660                         $DATA['ref'][$idx]   = '---';
661                         $DATA['userid'][$idx]   = '---';
662                 } // END - if
663
664                 if (!empty($DATA['info'][$idx])) {
665                         // Take direct infos
666                         $DATA['infos'][$idx] = $DATA['info'][$idx];
667                 } else {
668                         // Take ppints
669                         $DATA['infos'][$idx] = $DATA['points'][$idx] . ' {?POINTS?}';
670                 }
671
672                 // Add row
673                 $add = '';
674                 $OUT .= "<tr>
675   <td class=\"switch_sw".$SW." bottom2".$add."\">&nbsp;&nbsp;".($idx+1).".</td>
676   <td align=\"center\" class=\"switch_sw".$SW." bottom2".$add."\">";
677                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= "<strong>";
678                 $OUT .= $DATA['userid'][$idx];
679                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= "</strong>";
680                 $OUT .= "</td>
681   <td align=\"center\" class=\"switch_sw".$SW." bottom2".$add."\">";
682                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= "<strong>";
683                 $OUT .= $DATA['ref'][$idx];
684                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= "</strong>";
685                 $OUT .= "</td>
686   <td align=\"center\" class=\"switch_sw".$SW." bottom2".$add."\">";
687                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= "<strong>";
688                 $OUT .= $DATA['infos'][$idx];
689                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= "</strong>";
690                 $OUT .= "</td>
691 </tr>\n";
692                 $SW = 3 - $SW;
693         } // END - for
694
695         // Add footer
696         $OUT .= loadTemplate('guest_rallye_expired_footer', true);
697
698         // And finnally return the output
699         return $OUT;
700 }
701
702 //
703 function purgeExpiredReferalRallyes () {
704         // Check for expired rallyes
705         $EXPIRE = 3; // @TODO The hard-coded value...
706         $result_rallye = SQL_QUERY_ESC("SELECT id, title, start_time, end_time
707 FROM `{?_MYSQL_PREFIX?}_rallye_data`
708 WHERE end_time <= (UNIX_TIMESTAMP() - {?ONE_DAY?} - %s) AND expired='Y'",
709                 array($EXPIRE), __FUNCTION__, __LINE__);
710
711         if (SQL_NUMROWS($result_rallye) > 0) {
712                 // Init SQLs
713                 initSqls();
714
715                 // Expire found rallyes and notify admin
716                 while ($content = SQL_FETCHARRAY($result_rallye)) {
717                         // Prepare data for mail template
718                         $content['start_time']  = generateDateTime($content['start_time'], 1);
719                         $content['end_time']    = generateDateTime($content['end_time']  , 1);
720                         $content['now_time']    = generateDateTime(time(), 1);
721
722                         // Send mail to admin
723                         sendAdminNotification(sprintf(getMessage('RALLYE_ADMIN_PURGED_SUBJ'), $content['title']), 'admin_rallye_purged', $content, 0);
724
725                         // Purge whole rallye
726                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_data` WHERE `id`=%s LIMIT 1",
727                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
728                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE rallye_id=%s LIMIT 1",
729                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
730                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE rallye_id=%s LIMIT 1",
731                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
732
733                         // Add task
734                         createNewTask('{--RALLYE_ADMIN_PURGED--}: ' . $content['title'], '{--RALLYE_ADMIN_PURGED_TEXT--}', 'RALLYE_PURGED');
735                 } // END - while
736
737                 // Run all SQLs
738                 runFilterChain('run_sqls');
739         } // END - if
740
741         // Free memory
742         SQL_FREERESULT($result_rallye);
743 }
744
745 //
746 function addReferalRallyeTemplateSelection ($name = 'template', $default = '') {
747         // Init variables
748         $OUT = '';
749         $ral = array();
750
751         // Check templates directory
752         $basePath = sprintf("templates/%s/html/rallye/", getLanguage());
753
754         // Read the directory
755         $templates = getArrayFromDirectory($basePath, 'rallye_', false, true, array(), '.tpl');
756
757         // And walk through
758         foreach ($templates as $read) {
759                 // Cut prefix and extension away
760                 $read = substr($read, 7, strpos($read, '.') - 7);
761
762                 // Accept only template names between 1 and 255 chars length
763                 if ((strlen($read) < 256) && (!empty($read))) $ral[] = $read;
764         } // END - while
765
766         // Do we have found templates which we can link with the new rallye?
767         if (!empty($ral[0])) {
768                 // Generate selection box for all found templates
769                 // @TODO Rewrite this to our API function
770                 $OUT  = "<select name=\"".$name."\" size=\"1\" class=\"admin_select\">
771   <option value=\"\">{--SELECT_NONE--}</option>\n";
772                 foreach ($ral as $rallye) {
773                         $OUT .= "  <option value=\"".$rallye."\"";
774                         if ($default == $rallye) $OUT .= ' selected="selected"';
775                         $OUT .= ">".$rallye."</option>\n";
776                 } // END - foreach
777                 $OUT .= "</select>\n";
778         } else {
779                 // No rallye templates found
780                 $OUT = getMessage('RALLYE_NO_TEMPLATES_FOUND');
781         }
782
783         // Return selection
784         return $OUT;
785 }
786
787 //
788 function getReferalRallyeRefsCount ($userid, $old = '0') {
789         // Check current refs
790         if (getExtensionVersion('cache') >= '0.1.2') {
791                 // Get refs from cache
792                 $cnt = '0';
793                 foreach ($GLOBALS['cache_array']['refsystem']['userid'] as $id => $userid) {
794                         // Do we have a ref for this user?
795                         //* DEBUG: */ print("id={$id},userid={$userid},userid={$userid},old={$old},level={$GLOBALS['cache_array']['refsystem']['level'][$id]}<br />");
796                         if (($userid == $userid) && ($GLOBALS['cache_array']['refsystem']['level'][$id] == 1)) {
797                                 //* DEBUG: */ print("userid matches!<br />");
798                                 foreach ($GLOBALS['cache_array']['refdepths']['level'] as $level) {
799                                         if (($level == $GLOBALS['cache_array']['refsystem']['level'][$id]) && ($level == 1)) {
800                                                 // Level does exist so abort here
801                                                 $cnt = $GLOBALS['cache_array']['refsystem']['counter'][$id];
802                                                 //* DEBUG: */ print("*".$userid.'/'.$cnt."*<br />");
803                                                 break;
804                                         } elseif ($level > 1) {
805                                                 // Not interesting here...
806                                                 break;
807                                         }
808                                 } // END - foreach
809
810                                 // Abort also here!
811                                 if ($cnt > 0) break;
812                         } // END - if
813                 } // END - foreach
814
815                 //* DEBUG: */ print("<pre>");
816                 //* DEBUG: */ print(print_r($GLOBALS['cache_array']['refsystem'], true));
817                 //* DEBUG: */ print("</pre>");
818                 //* DEBUG: */ shutdown();
819
820                 if ($cnt > 0) {
821                         // Count cache hits
822                         incrementStatsEntry('cache_hits');
823
824                         // Remove old refs
825                         //* DEBUG: */ print('+'.$cnt.'/'.$old."+<br />");
826                         $cnt -= $old;
827                 } // END - if
828         } else {
829                 // Load current refs from database
830                 $result_ref = SQL_QUERY_ESC("SELECT SUM(s.counter) AS cnt
831 FROM `{?_MYSQL_PREFIX?}_refsystem` AS s
832 LEFT JOIN `{?_MYSQL_PREFIX?}_refdepths` AS d
833 ON s.level=d.level
834 WHERE s.userid=%s AND s.level=1", array(bigintval($userid)), __FUNCTION__, __LINE__);
835                 list($cnt) = SQL_FETCHROW($result_ref);
836                 SQL_FREERESULT($result_ref);
837                 if (empty($cnt)) {
838                         $cnt = '0';
839                 } else {
840                         $cnt -= $old;
841                 }
842         }
843
844         // Return count
845         //* DEBUG: */ print("*".$userid.'/'.$old.'/'.$cnt."*<br />");
846         return $cnt;
847 }
848
849 // Determines the right language string for min_users
850 function determineReferalRallyeMinimumUsers ($min_users) {
851         // Rallye ends without user limitation is the default
852         $return = getMessage('RALLYE_END_NO_USER_LIMITATION');
853
854         if ($min_users > 0) {
855                 // Rallye ends when X members are totally in your exchange
856                 $return = sprintf(getMessage('RALLYE_END_USERS'), $min_users);
857         } // END - if
858
859         // Return
860         return $return;
861 }
862
863 // Determines the right language string for min_prices
864 function determineReferalRallyeMinimumPrices ($min_prices) {
865         // Rallye ends without user limitation is the default
866         $return = getMessage('RALLYE_END_NO_PRICE_LIMITATION');
867
868         if ($min_prices > 0) {
869                 // Rallye ends when X members are totally in your exchange
870                 $return = sprintf(getMessage('RALLYE_END_PRICES'), $min_prices);
871         } // END - if
872
873         // Return
874         return $return;
875 }
876
877 // Filter for extra-autpurge
878 function FILTER_RALLYE_EXTRA_AUTOPURGE () {
879         // Check expired rallyes (hard-coded 3 days limit for displaying expired rallyes!)
880         purgeExpiredReferalRallyes();
881 }
882
883 // [EOF]
884 ?>