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