Extension 'ext-coupon' moved to branch, SQLs improved:
[mailer.git] / inc / libs / rallye_functions.php
index 5526567afe1615b3510e381820f45065b1963dfb..4fbc604ad9172a2b642901f00183e75c12ef4b37 100644 (file)
  * $Date::                                                            $ *
  * $Tag:: 0.2.1-FINAL                                                 $ *
  * $Author::                                                          $ *
- * Needs to be in all Files and every File needs "svn propset           *
- * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
+ * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
  * For more information visit: http://www.mxchange.org                  *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -51,11 +49,17 @@ function autostartReferalRallyes ($result) {
        SQL_FREERESULT($result);
 
        // Set notified to Y
-       SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_rallye_data` SET `notified`='Y' WHERE `id`=%s LIMIT 1",
+       SQL_QUERY_ESC("UPDATE
+       `{?_MYSQL_PREFIX?}_rallye_data`
+SET
+       `notified`='Y'
+WHERE
+       `id`=%s
+LIMIT 1",
                array(bigintval($id)), __FUNCTION__, __LINE__);
 
        // Transfer all neccessary data to the $content array
-       $content['userid_cnt'] = countSumTotalData('CONFIRMED','user_data','userid','status',true);
+       $content['userid_cnt'] = getTotalConfirmedUser();
        $content['start']      = generateDateTime($start, 2);
        $content['end']        = generateDateTime($end  , 2);
        $content['now_t']      = generateDateTime(time(), 2);
@@ -70,26 +74,41 @@ function autostartReferalRallyes ($result) {
        $content['prices'] = addReferalRallyePrices($id);
 
        // Query all users
-       $result_user = SQL_QUERY("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `status`='CONFIRMED' ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
+       $result_user = SQL_QUERY("SELECT
+       `userid`
+FROM
+       `{?_MYSQL_PREFIX?}_user_data`
+WHERE
+       `status`='CONFIRMED'
+ORDER BY
+       `userid` ASC", __FUNCTION__, __LINE__);
 
        // Let's begin with the userids...
-       while ($content = merge_array($content, SQL_FETCHARRAY($result_user))) {
+       while ($row = SQL_FETCHARRAY($result_user)) {
+               // Merge both arrays
+               $content = merge_array($content, $row);
+
                $un = false;
 
                // Get refs by userid
-               $cnt = getReferalRallyeRefsCount($content['userid']);
-               if (empty($cnt)) $cnt = '0'; // Added prevent some unknown troubles... :-?
+               $count = getReferalRallyeRefsCount($content['userid']);
+               if (empty($count)) $count = '0'; // Added prevent some unknown troubles... :-?
 
                // Check if line is already included...
-               $result_ref = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s AND `userid`=%s LIMIT 1",
+               $result_ref = SQL_QUERY_ESC("SELECT
+       `id`
+FROM
+       `{?_MYSQL_PREFIX?}_rallye_users`
+WHERE
+       `rallye_id`=%s AND
+       `userid`=%s
+LIMIT 1",
                        array(bigintval($id), bigintval($content['userid'])), __FUNCTION__, __LINE__);
-               if (SQL_NUMROWS($result_ref) == '0') {
-                       // Free memory
-                       SQL_FREERESULT($result_ref);
+               if (SQL_HASZERONUMS($result_ref)) {
 
                        // Add userid and his ref count to table
                        $result_ref = SQL_QUERY_ESC("SELECT 
-       SUM(p.points) AS points
+       SUM(p.points) AS `points`
 FROM
        `{?_MYSQL_PREFIX?}_user_points` AS p
 LEFT JOIN
@@ -101,8 +120,8 @@ WHERE
        d.max_mails > 0 AND
        d.mails_confirmed >= {?ref_payout?} AND
        p.ref_depth=1 AND
-       p.points > 0
-       AND d.userid=%s",
+       p.points > 0 AND
+       d.userid=%s",
                                array(bigintval($content['userid'])), __FUNCTION__, __LINE__);
 
                        // Get points
@@ -114,19 +133,25 @@ WHERE
                        if (empty($cpoints)) $cpoints = '0.00000';
 
                        // Add info line
-                       SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_rallye_users` (`rallye_id`, `userid`, `refs`, `curr_points`)
-VALUES (%s, %s, %s, %s)",
+                       SQL_QUERY_ESC("INSERT INTO
+       `{?_MYSQL_PREFIX?}_rallye_users`
+(`rallye_id`, `userid`, `refs`, `curr_points`)
+       VALUES
+(%s, %s, %s, %s)",
                                array(
                                        bigintval($id),
                                        bigintval($content['userid']),
-                                       bigintval($cnt),
+                                       bigintval($count),
                                        $cpoints
                                ), __FUNCTION__, __LINE__);
                        $un = true;
                } // END - if
 
+               // Free memory
+               SQL_FREERESULT($result_ref);
+
                // Ignored but for the template required refs (made before start of rallye)
-               $content['refs']  = $cnt;
+               $content['refs']  = $count;
 
                // Shall I notify this member?
                if (($notify == 'Y') && ($un)) {
@@ -148,29 +173,32 @@ VALUES (%s, %s, %s, %s)",
 }
 
 //
-function addReferalRallyePrices ($rallye, $mode='email') {
+function addReferalRallyePrices ($rallye, $mode = 'email') {
        // Output mode
        switch($mode) {
                case 'email': $mode = "\n";     break;
-               case 'html' : $mode = "<br />\n"; break;
+               case 'html' : $mode = '<br />'; break;
        } // END - switch
 
        // Load prices
-       $result_prices = SQL_QUERY("SELECT
+       $result_prices = SQL_QUERY_ESC("SELECT
        `price_level`, `points`, `info`
 FROM
        `{?_MYSQL_PREFIX?}_rallye_prices`
 WHERE
-       `rallye_id`='".$rallye."'
+       `rallye_id`=%s
 ORDER BY
        `price_level` ASC",
-               __FUNCTION__, __LINE__);
-       if (SQL_NUMROWS($result_prices) > 0) {
+               array($rallye), __FUNCTION__, __LINE__);
+
+       // Entries found?
+       if (!SQL_HASZERONUMS($result_prices)) {
                // Load prices
-               if ($mode == "\n") $prices = "{--RALLYE_MEMBER_PRICES_ADDED--}:".$mode."------------------------------".$mode;
+               if ($mode == "\n") $prices = '{--RALLYE_MEMBER_PRICES_ADDED--}:' . $mode . '------------------------------' . $mode;
+
                $prices = '';
                while ($content = SQL_FETCHARRAY($result_prices)) {
-                       $prices .= $content['price_level'].getMessage('RALLYE_PRICE').": ";
+                       $prices .= $content['price_level']. '{--RALLYE_PRICE--}: ';
                        if (!empty($content['info'])) {
                                $prices .= $content['info'];
                        } else {
@@ -195,11 +223,11 @@ ORDER BY
 
 //
 function addReferalRallyeTopUsers ($rallye, $default=0) {
+       // Init variables
+       $min_users = 0; $min_prices = 0;
+
        // First check how many prices are set
-       $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s ORDER BY price_level",
-               array(bigintval($rallye)), __FUNCTION__, __LINE__);
-       $prices = SQL_NUMROWS($result);
-       SQL_FREERESULT($result);
+       $prices = countSumTotalData($rallye, 'rallye_prices', 'id', 'rallye_id', true);
 
        // And load only limited users
        $result = SQL_QUERY_ESC("SELECT
@@ -215,21 +243,23 @@ LEFT JOIN
 ON
        u.rallye_id=rd.id
 WHERE
-       u.`rallye_id`=%s AND r.counter > 0
+       u.`rallye_id`=%s AND
+       r.counter > 0
 ORDER BY
        u.refs DESC",
                array(bigintval($rallye)), __FUNCTION__, __LINE__);
 
        // Load users
        $DATA = array(
-               'userid'   => array(),
-               'ref'      => array(),
-               'cpoints'  => array()
+               'userid'  => array(),
+               'ref'     => array(),
+               'cpoints' => array()
        );
 
+       // Load all users
        while ($content = SQL_FETCHARRAY($result)) {
                // Get current refs
-               $cnt = getReferalRallyeRefsCount($content['userid'], $content['refs']);
+               $count = getReferalRallyeRefsCount($content['userid'], $content['refs']);
 
                // Points of ref's
                $result_ref = SQL_QUERY_ESC("SELECT
@@ -261,12 +291,16 @@ LIMIT 1",
                $userid = '---';
 
                // List only users with at least one ref!
-               //* DEBUG: */ print("*".$cnt.'/'.$content['userid'].'/'.$content['curr_points'].'/'.$refpoints."*<br />");
-               if (($cnt > 0) && ($refpoints > $content['curr_points'])) { $userid = $content['userid']; } else { $cnt = ''; }
+               //* DEBUG: */ debugOutput('*'.$count.'/'.$content['userid'].'/'.$content['curr_points'].'/'.$refpoints.'*');
+               if (($count > 0) && ($refpoints > $content['curr_points'])) {
+                       $userid = $content['userid'];
+               } else {
+                       $count = '';
+               }
 
                // Save values to array
                $DATA['userid'][]   = $userid;
-               $DATA['ref'][]      = $cnt;
+               $DATA['ref'][]      = $count;
                $DATA['cpoints'][]  = $content['curr_points'];
                $min_users  = $content['min_users'];
                $min_prices = $content['min_prices'];
@@ -279,37 +313,36 @@ LIMIT 1",
        array_pk_sort($DATA, array('ref', 'cpoints'), 0, 1, true);
 
        // Generate table
-       $OUT = loadTemplate('guest_rallye_header', true);
-       $SW = 2;
+       $OUT = '';
        for ($idx = '0'; $idx < $prices; $idx++) {
-               if (empty($DATA['userid'][$idx])) $DATA['userid'][$idx] = '---';
-               if (empty($DATA['ref'][$idx])) $DATA['ref'][$idx] = '---';
-               // Add row
-               $OUT .= "<tr>
-  <td class=\"switch_sw".$SW." bottom\">".($idx+1).".</td>
-  <td align=\"center\" class=\"switch_sw".$SW." bottom\">";
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '<strong>';
-               $OUT .= $DATA['userid'][$idx];
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '</strong>';
-               $OUT .= "</td>
-  <td align=\"center\" class=\"switch_sw".$SW." bottom\">";
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '<strong>';
-               $OUT .= $DATA['ref'][$idx];
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '</strong>';
-               $OUT .= "</td>
-</tr>\n";
-               $SW = 3 - $SW;
-       } // END - for
+               // Prepare marking of default (maybe current user's) id
+               $start = ''; $end = '';
+               if (($DATA['userid'][$idx] == $default) && ($default > 0)) {
+                       $start = '<strong>';
+                       $end   = '</strong>';
+               } // END - if
 
-       // Translate min_prices/users
-       $content['min_prices'] = determineReferalRallyeMinimumPrices($min_prices);
-       $content['min_users']  = determineReferalRallyeMinimumUsers($min_users);
+               // Prepare content
+               $content = array(
+                       'idx'    => ($idx + 1),
+                       'start'  => $start,
+                       'end'    => $end,
+                       'userid' => $DATA['userid'][$idx],
+                       'ref'    => $DATA['ref'][$idx],
+                       'infos'  => ''
+               );
+
+               // Load row template and switch color
+               $OUT .= loadTemplate('guest_rallye_row', true, $content);
+       } // END - for
 
-       // Add footer
-       $OUT .= loadTemplate('guest_rallye_footer', true, $content);
+       // Add min_prices/users
+       $content['rows']       = $OUT;
+       $content['min_prices'] = bigintval($min_prices);
+       $content['min_users']  = bigintval($min_users);
 
        // And finnally return the output
-       return $OUT;
+       return loadTemplate('guest_rallye', true, $content);
 }
 
 // Run this function only when a new member has confirmed his email address!
@@ -317,8 +350,8 @@ function addUserToReferalRallye ($userid, $content = array()) {
        $add = '';
 
        // Updated extension?
-       if (getExtensionVersion('rallye') >= '0.2.0') {
-               $add .= ", `min_users`, `min_prices`";
+       if (isExtensionInstalledAndNewer('rallye', '0.2.0')) {
+               $add .= ', `min_users`, `min_prices`';
        } // END - if
 
        // Check for an auto-add rallye
@@ -337,7 +370,7 @@ LIMIT 1", __FUNCTION__, __LINE__);
                $min_users = '0'; $min_prices = '0';
 
                // Load data
-               if (getExtensionVersion('rallye') >= '0.2.0') {
+               if (isExtensionInstalledAndNewer('rallye', '0.2.0')) {
                        list($id, $title, $start, $end, $notify, $min_users, $min_prices) = SQL_FETCHROW($result);
                } else {
                        list($id, $title, $start, $end, $notify) = SQL_FETCHROW($result);
@@ -369,17 +402,27 @@ LIMIT 1", __FUNCTION__, __LINE__);
                } // END - if
 
                // Check if line is already included...
-               $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s AND `userid`=%s LIMIT 1",
+               $result = SQL_QUERY_ESC("SELECT
+       `id`
+FROM
+       `{?_MYSQL_PREFIX?}_rallye_users`
+WHERE
+       `rallye_id`=%s AND
+       `userid`=%s
+LIMIT 1",
                        array(
                                bigintval($id),
                                bigintval($userid)
                        ), __FUNCTION__, __LINE__);
 
                // Is this user added?
-               if (SQL_NUMROWS($result) < 1) {
+               if (SQL_HASZERONUMS($result)) {
                        // Add userid and his ref count to table
-                       SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_rallye_users` (`rallye_id`, `userid`, `refs`)
-VALUES ('%s','%s',0)",
+                       SQL_QUERY_ESC("INSERT INTO
+       `{?_MYSQL_PREFIX?}_rallye_users`
+(`rallye_id`, `userid`, `refs`)
+       VALUES
+(%s,%s,0)",
                                array(
                                        bigintval($id),
                                        bigintval($userid)
@@ -405,7 +448,8 @@ function markReferalRallyesAsExpired ($result) {
        $prices = getArrayFromReferalRallyeUsers($id);
 
        // Init array
-       $DATA = array(); $cnt = '0';
+       $DATA = array();
+       $count = '0';
        $users = array();
        $DATA['title']  = $title;
        $DATA['start']  = generateDateTime($start, 1);
@@ -414,25 +458,16 @@ function markReferalRallyesAsExpired ($result) {
 
        // Just count...
        $total = '0';
-       foreach($prices['userid'] as $key => $userid) {
+       foreach ($prices['userid'] as $key => $userid) {
                // Check status
                //   active = 1: account is still confirmed
-               //   active = '0': account is deleted or locked
-               $result = SQL_QUERY_ESC("SELECT
-       COUNT(`userid`) AS active
-FROM
-       `{?_MYSQL_PREFIX?}_user_data`
-WHERE
-       `userid`=%s AND `status`='CONFIRMED'
-LIMIT 1",
-                       array(bigintval($userid)), __FUNCTION__, __LINE__);
-               list($active) = SQL_FETCHROW($result);
-               SQL_FREERESULT($result);
+               //   active = 0: account is deleted or locked
+               $active = countSumTotalData($userid, 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED'");
 
                $prices['active'][$key] = $active;
 
                // Allow valid and active users with at least one ref to get points
-               if (($userid > 0) && ($prices['ref'][$key] > 0) && ($active == 1) && ($prices['cpoints'][$key] > 0)) {
+               if ((isValidUserId($userid)) && ($prices['ref'][$key] > 0) && ($active == 1) && ($prices['cpoints'][$key] > 0)) {
                        $total++;
                } // END - if
        } // END - foreach
@@ -448,9 +483,9 @@ LIMIT 1",
                array(bigintval($id)), __FUNCTION__, __LINE__);
 
        // Run array through (by userid is the most important 2nd-level-array)
-       foreach($prices['userid'] as $key => $userid) {
+       foreach ($prices['userid'] as $key => $userid) {
                // Allow valid and active users with at least one ref to get points
-               if (($userid > 0) && ($prices['ref'][$key] > 0) && ($prices['active'][$key] == 1) && ($prices['cpoints'][$key] > 0)) {
+               if ((isValidUserId($userid)) && ($prices['ref'][$key] > 0) && ($prices['active'][$key] == 1) && ($prices['cpoints'][$key] > 0)) {
                        // Transfer data to array for the mail template
                        $DATA['level']  = $prices['level'][$key];
                        $DATA['points'] = $prices['points'][$key];
@@ -492,11 +527,11 @@ LIMIT 1",
 
                                // Load template
                                $message = loadEmailTemplate($template, $DATA, $userid);
-                               sendEmail($userid, getMaskedMessage('RALLYE_MEMBER_EXPIRED_SUBJ', $DATA['level']), $message);
+                               sendEmail($userid, getMaskedMessage('RALLYE_MEMBER_EXPIRED_SUBJECT', $DATA['level']), $message);
                        } // END - if
 
                        // Count userid
-                       $cnt++;
+                       $count++;
                        $users['userid'][$userid] = $userid;
                        $users['poi'][$userid] = $DATA['infos'];
                } // END - if
@@ -507,13 +542,13 @@ LIMIT 1",
                $templ = 'admin_rallye_expired';
        } elseif (is_array($users['userid'])) {
                $templ = 'admin_rallye_expired_no';
-               $cnt = getReferalRallyeUserDataFromArray($users);
+               $count = getReferalRallyeUserDataFromArray($users);
        }
 
        // Send mail to admin
-       sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_EXPIRED_SUBJ', $title), $templ, $cnt);
+       sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_EXPIRED_SUBJECT', $title), $templ, $count);
 
-       // Add task
+       // Add task (we ignore the task id here)
        createNewTask('{--RALLYE_ADMIN_EXPIRED--}: ' . $title, '{--RALLYE_ADMIN_EXPIRED_TEXT--}', 'RALLYE_EXPIRED');
 }
 
@@ -526,8 +561,20 @@ function getReferalRallyeUserDataFromArray ($userIds) {
        $ret = '';
 
        // Load users
-       $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",
-               array($userid_string, count($userIds)), __FUNCTION__, __LINE__);
+       $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",
+               array(
+                       $userid_string,
+                       count($userIds)
+               ), __FUNCTION__, __LINE__);
        while ($content = SQL_FETCHARRAY($result)) {
                // Construct the message masked and add it
                $ret .= sprintf("%s %s %s (%s) - %s\n",
@@ -553,8 +600,15 @@ function getArrayFromReferalRallyePrices ($rallye) {
        );
 
        // Load prices
-       $result = SQL_QUERY_ESC("SELECT price_level, points, info FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s ORDER BY price_level",
-       array(bigintval($rallye)), __FUNCTION__, __LINE__);
+       $result = SQL_QUERY_ESC("SELECT
+       `price_level`, `points`, `info`
+FROM
+       `{?_MYSQL_PREFIX?}_rallye_prices`
+WHERE
+       `rallye_id`=%s
+ORDER BY
+       `price_level` ASC",
+               array(bigintval($rallye)), __FUNCTION__, __LINE__);
 
        // Transfer elements
        while ($content = SQL_FETCHARRAY($result)) {
@@ -577,7 +631,7 @@ function getArrayFromReferalRallyeUsers ($rallye) {
 
        // Init multi array
        $users = array(
-               'userid'     => array(),
+               'userid'  => array(),
                'ref'     => array(),
                'cpoints' => array(),
        );
@@ -587,11 +641,11 @@ function getArrayFromReferalRallyeUsers ($rallye) {
                array(bigintval($rallye)), __FUNCTION__, __LINE__);
        while ($content = SQL_FETCHARRAY($result_user)) {
                // Load current ref count
-               $cnt = getReferalRallyeRefsCount($content['userid'], $content['refs']);
+               $count = getReferalRallyeRefsCount($content['userid'], $content['refs']);
 
                // Points of ref's
                $result_ref = SQL_QUERY_ESC("SELECT
-       SUM(p.points) AS points
+       SUM(p.points) AS `points`
 FROM
        `{?_MYSQL_PREFIX?}_user_points` AS p
 LEFT JOIN
@@ -618,8 +672,8 @@ LIMIT 1",
                if (empty($refpoints)) $refpoints = '0';
 
                // Store calculated new refs to array
-               $users['userid'][]     = $content['userid'];
-               $users['ref'][]     = abs($cnt - $content['refs']);
+               $users['userid'][]  = $content['userid'];
+               $users['ref'][]     = abs($count - $content['refs']);
                $users['cpoints'][] = $refpoints - $content['curr_points'];
        } // END - while
 
@@ -627,7 +681,7 @@ LIMIT 1",
        SQL_FREERESULT($result_user);
 
        // Sort array for refs (descending)
-       array_pk_sort($users, array("ref", "cpoints"), 0, 1, true);
+       array_pk_sort($users, array('ref', 'cpoints'), 0, 1, true);
 
        // Load prices array (!)
        $prices = getArrayFromReferalRallyePrices($rallye);
@@ -637,9 +691,7 @@ LIMIT 1",
                // We only need to check one element in $users, see above while() block
                if (isset($users['userid'][$k])) {
                        $prices['userid'][$k]  = $users['userid'][$k];
-                       if (empty($prices['userid'][$k])) $prices['userid'][$k]  = '---';
-                       $prices['ref'][$k] = $users['ref'][$k];
-                       if (empty($prices['ref'][$k])) $prices['ref'][$k] = '---';
+                       $prices['ref'][$k]     = $users['ref'][$k];
                        $prices['cpoints'][$k] = $users['cpoints'][$k];
                } // END - if
        } // END - foreach
@@ -648,28 +700,23 @@ LIMIT 1",
        return $prices;
 }
 
-//
+// @TODO This function does not load min_users, min_prices, please encapsulate loading rallye data with e.g. getRallyeDataFromId()
 function addReferalRallyeWinners ($rallye, $default=0) {
        // First check how many prices are set
-       $result_prices = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_rallye_prices` WHERE `rallye_id`=%s ORDER BY `price_level` ASC",
-               array(bigintval($rallye)), __FUNCTION__, __LINE__);
-       $prices = SQL_NUMROWS($result_prices);
-       SQL_FREERESULT($result_prices);
+       $prices = countSumTotalData(bigintval($rallye), 'rallye_prices', 'id', 'rallye_id', true);
 
        // Load data
        $DATA = getArrayFromReferalRallyeUsers($rallye);
 
        // Generate table
-       $OUT = loadTemplate('guest_rallye_expired_header', true);
-       $SW = 2;
+       $OUT = '';
        for ($idx = '0'; $idx < $prices; $idx++) {
                // Check status
                //   active = 1: account is still confirmed
-               //   active = '0': account is deleted or locked
+               //   active = 0: account is deleted or locked
                $active = countSumTotalData($DATA['userid'][$idx], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED'");
 
-               if (empty($DATA['userid'][$idx])) $DATA['userid'][$idx] = '---';
-               if ((empty($DATA['ref'][$idx])) || ($DATA['ref'][$idx] == '0') || ($active == '0') || ("".round($DATA['cpoints'][$idx])."" == '0') || (empty($DATA['cpoints'][$idx]))) {
+               if ((empty($DATA['ref'][$idx])) || ($DATA['ref'][$idx] == '0') || ($active == '0') || ('' . round($DATA['cpoints'][$idx]) . '' == '0') || (empty($DATA['cpoints'][$idx]))) {
                        // Allow valid and active users with at least one ref to get points
                        $DATA['ref'][$idx]   = '---';
                        $DATA['userid'][$idx]   = '---';
@@ -683,46 +730,52 @@ function addReferalRallyeWinners ($rallye, $default=0) {
                        $DATA['infos'][$idx] = $DATA['points'][$idx] . ' {?POINTS?}';
                }
 
-               // Add row
-               $add = '';
-               $OUT .= "<tr>
-  <td class=\"switch_sw".$SW." bottom".$add."\">".($idx+1).".</td>
-  <td align=\"center\" class=\"switch_sw".$SW." bottom".$add."\">";
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '<strong>';
-               $OUT .= $DATA['userid'][$idx];
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '</strong>';
-               $OUT .= "</td>
-  <td align=\"center\" class=\"switch_sw".$SW." bottom".$add."\">";
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '<strong>';
-               $OUT .= $DATA['ref'][$idx];
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '</strong>';
-               $OUT .= "</td>
-  <td align=\"center\" class=\"switch_sw".$SW." bottom".$add."\">";
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '<strong>';
-               $OUT .= $DATA['infos'][$idx];
-               if (($DATA['userid'][$idx] == $default) && ($default > 0)) $OUT .= '</strong>';
-               $OUT .= "</td>
-</tr>\n";
-               $SW = 3 - $SW;
+               // Prepare marking of default (maybe current user's) id
+               $start = ''; $end = '';
+               if (($DATA['userid'][$idx] == $default) && ($default > 0)) {
+                       $start = '<strong>';
+                       $end   = '</strong>';
+               } // END - if
+
+               // Prepare content
+               $content = array(
+                       'idx'    => ($idx + 1),
+                       'userid' => $DATA['userid'][$idx],
+                       'ref'    => $DATA['ref'][$idx],
+                       'infos'  => $DATA['infos'][$idx],
+                       'start'  => $start,
+                       'end'    => $end
+               );
+
+               // Load row template
+               $OUT .= loadTemplate('guest_rallye_row', true, $content);
        } // END - for
 
-       // Add footer
-       $OUT .= loadTemplate('guest_rallye_expired_footer', true);
+       // Prepare content
+       $content = array(
+               'rows'       => $OUT,
+               'min_users'  => '???',
+               'min_prices' => '???'
+       );
 
-       // And finnally return the output
-       return $OUT;
+       // Load main template and finnally return the output
+       return loadTemplate('guest_rallye', true, $content);
 }
 
 //
 function purgeExpiredReferalRallyes () {
        // Check for expired rallyes
        $EXPIRE = 3; // @TODO The hard-coded value...
-       $result_rallye = SQL_QUERY_ESC("SELECT id, title, start_time, end_time
-FROM `{?_MYSQL_PREFIX?}_rallye_data`
-WHERE end_time <= (UNIX_TIMESTAMP() - {?ONE_DAY?} - %s) AND expired='Y'",
+       $result_rallye = SQL_QUERY_ESC("SELECT
+       `id`, `title`, `start_time`, `end_time`
+FROM
+       `{?_MYSQL_PREFIX?}_rallye_data`
+WHERE
+       `end_time` <= (UNIX_TIMESTAMP() - {?ONE_DAY?} - %s) AND
+       `expired`='Y'",
                array($EXPIRE), __FUNCTION__, __LINE__);
 
-       if (SQL_NUMROWS($result_rallye) > 0) {
+       if (!SQL_HASZERONUMS($result_rallye)) {
                // Init SQLs
                initSqls();
 
@@ -734,7 +787,7 @@ WHERE end_time <= (UNIX_TIMESTAMP() - {?ONE_DAY?} - %s) AND expired='Y'",
                        $content['now_time']    = generateDateTime(time(), 1);
 
                        // Send mail to admin
-                       sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_PURGED_SUBJ', $content['title']), 'admin_rallye_purged', $content);
+                       sendAdminNotification(getMaskedMessage('RALLYE_ADMIN_PURGED_SUBJECT', $content['title']), 'admin_rallye_purged', $content);
 
                        // Purge whole rallye
                        addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_data` WHERE `id`=%s LIMIT 1",
@@ -744,7 +797,7 @@ WHERE end_time <= (UNIX_TIMESTAMP() - {?ONE_DAY?} - %s) AND expired='Y'",
                        addSql(SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `rallye_id`=%s LIMIT 1",
                                array(bigintval($content['id'])), __FUNCTION__, __LINE__, false));
 
-                       // Add task
+                       // Add task (we ignore the task id here
                        createNewTask('{--RALLYE_ADMIN_PURGED--}: ' . $content['title'], '{--RALLYE_ADMIN_PURGED_TEXT--}', 'RALLYE_PURGED');
                } // END - while
 
@@ -774,46 +827,46 @@ function addReferalRallyeTemplateSelection ($name = 'template', $default = '') {
                $read = substr($read, 7, strpos($read, '.') - 7);
 
                // Accept only template names between 1 and 255 chars length
-               if ((strlen($read) < 256) && (!empty($read))) $ral[] = $read;
-       } // END - while
+               if ((strlen($read) < 256) && (!empty($read))) {
+                       // Valid entry found
+                       $ral[$read] = $read;
+               } else {
+                       // Log invalid
+                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("WARNING: Template %s not used.", $read));
+               }
+       } // END - foreach
 
        // Do we have found templates which we can link with the new rallye?
        if (!empty($ral[0])) {
                // Generate selection box for all found templates
-               // @TODO Rewrite this to our API function
-               $OUT  = "<select name=\"".$name."\" size=\"1\" class=\"admin_select\">
-  <option value=\"\">{--SELECT_NONE--}</option>\n";
-               foreach ($ral as $rallye) {
-                       $OUT .= "  <option value=\"".$rallye."\"";
-                       if ($default == $rallye) $OUT .= ' selected="selected"';
-                       $OUT .= ">".$rallye."</option>\n";
-               } // END - foreach
-               $OUT .= "</select>\n";
+               $OUT  = '<select class="form_select" name="' . $name . '" size="1">';
+               $OUT .= generateOptionList('/ARRAY/', array_keys($ral), array_values($ral), $default, '', 'none');
+               $OUT .= '</select>';
        } else {
                // No rallye templates found
-               $OUT = getMessage('RALLYE_NO_TEMPLATES_FOUND');
+               $OUT = '{--RALLYE_NO_TEMPLATES_FOUND--}';
        }
 
        // Return selection
        return $OUT;
 }
 
-//
-function getReferalRallyeRefsCount ($userid, $old = '0') {
+// @TODO Please document this function
+function getReferalRallyeRefsCount ($currUserid, $old = '0') {
        // Check current refs
-       if (getExtensionVersion('cache') >= '0.1.2') {
+       if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
                // Get refs from cache
-               $cnt = '0';
+               $count = '0';
                foreach ($GLOBALS['cache_array']['refsystem']['userid'] as $id => $userid) {
                        // Do we have a ref for this user?
-                       //* DEBUG: */ print("id={$id},userid={$userid},userid={$userid},old={$old},level={$GLOBALS['cache_array']['refsystem']['level'][$id]}<br />");
-                       if (($userid == $userid) && ($GLOBALS['cache_array']['refsystem']['level'][$id] == 1)) {
-                               //* DEBUG: */ print("userid matches!<br />");
+                       //* DEBUG: */ debugOutput('id='.$id.',userid='.$userid.',userid='.$userid.',old='.$old.',level='.$GLOBALS['cache_array']['refsystem']['level'][$id]);
+                       if (($currUserid == $userid) && ($GLOBALS['cache_array']['refsystem']['level'][$id] == 1)) {
+                               //* DEBUG: */ debugOutput('userid matches!');
                                foreach ($GLOBALS['cache_array']['refdepths']['level'] as $level) {
                                        if (($level == $GLOBALS['cache_array']['refsystem']['level'][$id]) && ($level == 1)) {
                                                // Level does exist so abort here
-                                               $cnt = $GLOBALS['cache_array']['refsystem']['counter'][$id];
-                                               //* DEBUG: */ print("*".$userid.'/'.$cnt."*<br />");
+                                               $count = $GLOBALS['cache_array']['refsystem']['counter'][$id];
+                                               //* DEBUG: */ debugOutput('*'.$userid.'/'.$count.'*');
                                                break;
                                        } elseif ($level > 1) {
                                                // Not interesting here...
@@ -822,48 +875,59 @@ function getReferalRallyeRefsCount ($userid, $old = '0') {
                                } // END - foreach
 
                                // Abort also here!
-                               if ($cnt > 0) break;
+                               if ($count > 0) break;
                        } // END - if
                } // END - foreach
 
-               //* DEBUG: */ print("<pre>");
-               //* DEBUG: */ print(print_r($GLOBALS['cache_array']['refsystem'], true));
-               //* DEBUG: */ print("</pre>");
+               //* DEBUG: */ debugOutput('<pre>'.print_r($GLOBALS['cache_array']['refsystem'], true).'</pre>');
                //* DEBUG: */ shutdown();
 
-               if ($cnt > 0) {
+               if ($count > 0) {
                        // Count cache hits
                        incrementStatsEntry('cache_hits');
 
                        // Remove old refs
-                       //* DEBUG: */ print('+'.$cnt.'/'.$old."+<br />");
-                       $cnt -= $old;
+                       //* DEBUG: */ debugOutput('+'.$count.'/'.$old.'+');
+                       $count -= $old;
                } // END - if
        } else {
                // Load current refs from database
-               $result_ref = SQL_QUERY_ESC("SELECT SUM(s.counter) AS cnt
-FROM `{?_MYSQL_PREFIX?}_refsystem` AS s
-LEFT JOIN `{?_MYSQL_PREFIX?}_refdepths` AS d
-ON s.level=d.level
-WHERE s.userid=%s AND s.level=1", array(bigintval($userid)), __FUNCTION__, __LINE__);
-               list($cnt) = SQL_FETCHROW($result_ref);
+               $result_ref = SQL_QUERY_ESC("SELECT
+       SUM(s.counter) AS cnt
+FROM
+       `{?_MYSQL_PREFIX?}_refsystem` AS s
+LEFT JOIN
+       `{?_MYSQL_PREFIX?}_refdepths` AS d
+ON
+       s.level=d.level
+WHERE
+       s.userid=%s AND
+       s.level=1",
+                       array(
+                               bigintval($userid)
+                       ), __FUNCTION__, __LINE__);
+
+               // Load count @TODO Can't we rewrite this to our API?
+               list($count) = SQL_FETCHROW($result_ref);
+
+               // Free result
                SQL_FREERESULT($result_ref);
-               if (empty($cnt)) {
-                       $cnt = '0';
+               if (empty($count)) {
+                       $count = '0';
                } else {
-                       $cnt -= $old;
+                       $count -= $old;
                }
        }
 
        // Return count
-       //* DEBUG: */ print("*".$userid.'/'.$old.'/'.$cnt."*<br />");
-       return $cnt;
+       //* DEBUG: */ debugOutput('*'.$userid.'/'.$old.'/'.$count.'*');
+       return $count;
 }
 
 // Determines the right language string for min_users
 function determineReferalRallyeMinimumUsers ($min_users) {
        // Rallye ends without user limitation is the default
-       $return = getMessage('RALLYE_END_NO_USER_LIMITATION');
+       $return = '{--RALLYE_END_NO_USER_LIMITATION--}';
 
        if ($min_users > 0) {
                // Rallye ends when X members are totally in your exchange
@@ -877,7 +941,7 @@ function determineReferalRallyeMinimumUsers ($min_users) {
 // Determines the right language string for min_prices
 function determineReferalRallyeMinimumPrices ($min_prices) {
        // Rallye ends without user limitation is the default
-       $return = getMessage('RALLYE_END_NO_PRICE_LIMITATION');
+       $return = '{--RALLYE_END_NO_PRICE_LIMITATION--}';
 
        if ($min_prices > 0) {
                // Rallye ends when X members are totally in your exchange
@@ -888,11 +952,5 @@ function determineReferalRallyeMinimumPrices ($min_prices) {
        return $return;
 }
 
-// Filter for extra-autpurge
-function FILTER_RALLYE_EXTRA_AUTOPURGE () {
-       // Check expired rallyes (hard-coded 3 days limit for displaying expired rallyes!)
-       purgeExpiredReferalRallyes();
-}
-
 // [EOF]
 ?>