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