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