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