More rewrites to make use of (cached) wrapper 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  * 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 />\n"; 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         $result_prices = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s ORDER BY `price_level` ASC",
704                 array(bigintval($rallye)), __FUNCTION__, __LINE__);
705         $prices = SQL_NUMROWS($result_prices);
706         SQL_FREERESULT($result_prices);
707
708         // Load data
709         $DATA = getArrayFromReferalRallyeUsers($rallye);
710
711         // Generate table
712         $OUT = '';
713         for ($idx = '0'; $idx < $prices; $idx++) {
714                 // Check status
715                 //   active = 1: account is still confirmed
716                 //   active = 0: account is deleted or locked
717                 $active = countSumTotalData($DATA['userid'][$idx], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED'");
718
719                 if ((empty($DATA['ref'][$idx])) || ($DATA['ref'][$idx] == '0') || ($active == '0') || ('' . round($DATA['cpoints'][$idx]) . '' == '0') || (empty($DATA['cpoints'][$idx]))) {
720                         // Allow valid and active users with at least one ref to get points
721                         $DATA['ref'][$idx]   = '---';
722                         $DATA['userid'][$idx]   = '---';
723                 } // END - if
724
725                 if (!empty($DATA['info'][$idx])) {
726                         // Take direct infos
727                         $DATA['infos'][$idx] = $DATA['info'][$idx];
728                 } else {
729                         // Take ppints
730                         $DATA['infos'][$idx] = $DATA['points'][$idx] . ' {?POINTS?}';
731                 }
732
733                 // Prepare marking of default (maybe current user's) id
734                 $start = ''; $end = '';
735                 if (($DATA['userid'][$idx] == $default) && ($default > 0)) {
736                         $start = '<strong>';
737                         $end   = '</strong>';
738                 } // END - if
739
740                 // Prepare content
741                 $content = array(
742                         'idx'    => ($idx + 1),
743                         'userid' => $DATA['userid'][$idx],
744                         'ref'    => $DATA['ref'][$idx],
745                         'infos'  => $DATA['infos'][$idx],
746                         'start'  => $start,
747                         'end'    => $end
748                 );
749
750                 // Load row template
751                 $OUT .= loadTemplate('guest_rallye_row', true, $content);
752         } // END - for
753
754         // Prepare content
755         $content = array(
756                 'rows'       => $OUT,
757                 'min_users'  => '???',
758                 'min_prices' => '???'
759         );
760
761         // Load main template and finnally return the output
762         return loadTemplate('guest_rallye', true, $content);
763 }
764
765 //
766 function purgeExpiredReferalRallyes () {
767         // Check for expired rallyes
768         $EXPIRE = 3; // @TODO The hard-coded value...
769         $result_rallye = SQL_QUERY_ESC("SELECT
770         `id`, `title`, `start_time`, `end_time`
771 FROM
772         `{?_MYSQL_PREFIX?}_rallye_data`
773 WHERE
774         `end_time` <= (UNIX_TIMESTAMP() - {?ONE_DAY?} - %s) AND
775         `expired`='Y'",
776                 array($EXPIRE), __FUNCTION__, __LINE__);
777
778         if (!SQL_HASZERONUMS($result_rallye)) {
779                 // Init SQLs
780                 initSqls();
781
782                 // Expire found rallyes and notify admin
783                 while ($content = SQL_FETCHARRAY($result_rallye)) {
784                         // Prepare data for mail template
785                         $content['start_time']  = generateDateTime($content['start_time'], 1);
786                         $content['end_time']    = generateDateTime($content['end_time']  , 1);
787                         $content['now_time']    = generateDateTime(time(), 1);
788
789                         // Send mail to admin
790                         sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_PURGED_SUBJECT', $content['title']), 'admin_rallye_purged', $content);
791
792                         // Purge whole rallye
793                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_data` WHERE `id`=%s LIMIT 1",
794                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
795                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s LIMIT 1",
796                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
797                         addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s LIMIT 1",
798                                 array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
799
800                         // Add task (we ignore the task id here
801                         createNewTask('{--RALLYE_ADMIN_PURGED--}: ' . $content['title'], '{--RALLYE_ADMIN_PURGED_TEXT--}', 'RALLYE_PURGED');
802                 } // END - while
803
804                 // Run all SQLs
805                 runFilterChain('run_sqls');
806         } // END - if
807
808         // Free memory
809         SQL_FREERESULT($result_rallye);
810 }
811
812 //
813 function addReferalRallyeTemplateSelection ($name = 'template', $default = '') {
814         // Init variables
815         $OUT = '';
816         $ral = array();
817
818         // Check templates directory
819         $basePath = sprintf("templates/%s/html/rallye/", getLanguage());
820
821         // Read the directory
822         $templates = getArrayFromDirectory($basePath, 'rallye_', false, true, array(), '.tpl');
823
824         // And walk through
825         foreach ($templates as $read) {
826                 // Cut prefix and extension away
827                 $read = substr($read, 7, strpos($read, '.') - 7);
828
829                 // Accept only template names between 1 and 255 chars length
830                 if ((strlen($read) < 256) && (!empty($read))) {
831                         // Valid entry found!
832                         $ral[$read] = $read;
833                 } else {
834                         // Log invalid
835                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("WARNING: Template %s not used.", $read));
836                 }
837         } // END - foreach
838
839         // Do we have found templates which we can link with the new rallye?
840         if (!empty($ral[0])) {
841                 // Generate selection box for all found templates
842                 $OUT  = '<select name="' . $name . '" size="1" class="admin_select">';
843                 $OUT .= generateOptionList('/ARRAY/', array_keys($ral), array_values($ral), $default, '', 'none');
844                 $OUT .= '</select>';
845         } else {
846                 // No rallye templates found
847                 $OUT = '{--RALLYE_NO_TEMPLATES_FOUND--}';
848         }
849
850         // Return selection
851         return $OUT;
852 }
853
854 // @TODO Please document this function
855 function getReferalRallyeRefsCount ($currUserid, $old = '0') {
856         // Check current refs
857         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
858                 // Get refs from cache
859                 $cnt = '0';
860                 foreach ($GLOBALS['cache_array']['refsystem']['userid'] as $id => $userid) {
861                         // Do we have a ref for this user?
862                         //* DEBUG: */ debugOutput('id='.$id.',userid='.$userid.',userid='.$userid.',old='.$old.',level='.$GLOBALS['cache_array']['refsystem']['level'][$id]);
863                         if (($currUserid == $userid) && ($GLOBALS['cache_array']['refsystem']['level'][$id] == 1)) {
864                                 //* DEBUG: */ debugOutput('userid matches!');
865                                 foreach ($GLOBALS['cache_array']['refdepths']['level'] as $level) {
866                                         if (($level == $GLOBALS['cache_array']['refsystem']['level'][$id]) && ($level == 1)) {
867                                                 // Level does exist so abort here
868                                                 $cnt = $GLOBALS['cache_array']['refsystem']['counter'][$id];
869                                                 //* DEBUG: */ debugOutput('*'.$userid.'/'.$cnt.'*');
870                                                 break;
871                                         } elseif ($level > 1) {
872                                                 // Not interesting here...
873                                                 break;
874                                         }
875                                 } // END - foreach
876
877                                 // Abort also here!
878                                 if ($cnt > 0) break;
879                         } // END - if
880                 } // END - foreach
881
882                 //* DEBUG: */ debugOutput('<pre>'.print_r($GLOBALS['cache_array']['refsystem'], true).'</pre>');
883                 //* DEBUG: */ shutdown();
884
885                 if ($cnt > 0) {
886                         // Count cache hits
887                         incrementStatsEntry('cache_hits');
888
889                         // Remove old refs
890                         //* DEBUG: */ debugOutput('+'.$cnt.'/'.$old.'+');
891                         $cnt -= $old;
892                 } // END - if
893         } else {
894                 // Load current refs from database
895                 $result_ref = SQL_QUERY_ESC("SELECT
896         SUM(s.counter) AS cnt
897 FROM
898         `{?_MYSQL_PREFIX?}_refsystem` AS s
899 LEFT JOIN
900         `{?_MYSQL_PREFIX?}_refdepths` AS d
901 ON
902         s.level=d.level
903 WHERE
904         s.userid=%s AND
905         s.level=1",
906                         array(
907                                 bigintval($userid)
908                         ), __FUNCTION__, __LINE__);
909
910                 // Load count @TODO Can't we rewrite this to our API?
911                 list($cnt) = SQL_FETCHROW($result_ref);
912
913                 // Free result
914                 SQL_FREERESULT($result_ref);
915                 if (empty($cnt)) {
916                         $cnt = '0';
917                 } else {
918                         $cnt -= $old;
919                 }
920         }
921
922         // Return count
923         //* DEBUG: */ debugOutput('*'.$userid.'/'.$old.'/'.$cnt.'*');
924         return $cnt;
925 }
926
927 // Determines the right language string for min_users
928 function determineReferalRallyeMinimumUsers ($min_users) {
929         // Rallye ends without user limitation is the default
930         $return = '{--RALLYE_END_NO_USER_LIMITATION--}';
931
932         if ($min_users > 0) {
933                 // Rallye ends when X members are totally in your exchange
934                 $return = getMaskedMessage('RALLYE_END_USERS', $min_users);
935         } // END - if
936
937         // Return
938         return $return;
939 }
940
941 // Determines the right language string for min_prices
942 function determineReferalRallyeMinimumPrices ($min_prices) {
943         // Rallye ends without user limitation is the default
944         $return = '{--RALLYE_END_NO_PRICE_LIMITATION--}';
945
946         if ($min_prices > 0) {
947                 // Rallye ends when X members are totally in your exchange
948                 $return = getMaskedMessage('RALLYE_END_PRICES', $min_prices);
949         } // END - if
950
951         // Return
952         return $return;
953 }
954
955 // Filter for extra-autpurge
956 function FILTER_RALLYE_EXTRA_AUTOPURGE () {
957         // Check expired rallyes (hard-coded 3 days limit for displaying expired rallyes!)
958         purgeExpiredReferalRallyes();
959 }
960
961 // [EOF]
962 ?>