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