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