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