Compilation time added, some compileCode() calles removed, ADMIN_WHAT_404 added
[mailer.git] / inc / mysql-manager.php
index 2b88cfbc83d96a54f261cf86457dfdb3120fe7d8..343477e89101ab298cd11456a0754c92bd1132ec 100644 (file)
@@ -253,7 +253,7 @@ function checkModulePermissions ($mod = '') {
 
                        // Destroy cache here
                        // @TODO Rewrite this to a filter
-                       if (getOutputMode() == 0) rebuildCacheFile('modules', 'modules');
+                       if ((getOutputMode() == 0) || (getOutputMode() == -1)) rebuildCacheFile('modules', 'modules');
 
                        // And reload data
                        unset($GLOBALS['module_status'][$mod]);
@@ -580,10 +580,13 @@ function isMember () {
        if (isset($GLOBALS['is_member'])) {
                // Then return it
                return $GLOBALS['is_member'];
-       } // END - if
+       } elseif (getUserId() == 0) {
+               // No member
+               return false;
+       }
 
-       // Init global 'status'
-       $GLOBALS['status'] = false;
+       // Init global user data array
+       initUserData();
 
        // Fix "deleted" cookies first
        fixDeletedCookies(array('userid', 'u_hash'));
@@ -591,24 +594,16 @@ function isMember () {
        // Are cookies set?
        if ((isUserIdSet()) && (isSessionVariableSet('u_hash'))) {
                // Cookies are set with values, but are they valid?
-               $result = SQL_QUERY_ESC("SELECT `password`, `status`, `last_module`, `last_online` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                       array(getUserId()), __FUNCTION__, __LINE__);
-               if (SQL_NUMROWS($result) == 1) {
-                       // Load data from cookies
-                       list($password, $GLOBALS['status'], $mod, $onl) = SQL_FETCHROW($result);
-
+               if (fetchUserData(getUserId()) === true) {
                        // Validate password by created the difference of it and the secret key
-                       $valPass = generatePassString($password);
+                       $valPass = generatePassString(getUserData('password'));
 
                        // Transfer last module and online time
-                       if ((!empty($mod)) && (empty($GLOBALS['last_online']['module']))) {
-                               // @TODO Try to rewrite this to one or more functions
-                               $GLOBALS['last_online']['module'] = $mod;
-                               $GLOBALS['last_online']['online'] = $onl;
-                       } // END - if
+                       $GLOBALS['last_online']['module'] = getUserData('last_module');
+                       $GLOBALS['last_online']['online'] = getUserData('last_online');
 
                        // So did we now have valid data and an unlocked user?
-                       if (($GLOBALS['status'] == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
+                       if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
                                // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
                                $ret = true;
                        } else {
@@ -621,9 +616,6 @@ function isMember () {
                        //* DEBUG: */ print(__LINE__."***<br />");
                        destroyUserSession();
                }
-
-               // Free memory
-               SQL_FREERESULT($result);
        } else {
                // Cookie data is invalid!
                //* DEBUG: */ print(__LINE__."///<br />");
@@ -637,11 +629,82 @@ function isMember () {
        return $ret;
 }
 
+// Fetch user data for given user id
+function fetchUserData ($userid, $column='userid') {
+       // Don't look for invalid userids...
+       if ($userid < 1) {
+               // Invalid, so abort here
+               debug_report_bug('User id ' . $userid . ' is invalid.');
+       } elseif (isset($GLOBALS['user_data'][$userid])) {
+               // Use cache, so it is fine
+               return true;
+       }
+
+       // By default none was found
+       $found = false;
+
+       // Do we have userid/refid?
+       if (($column == 'userid') || ($column == 'refid')) {
+               // Then secure the id
+               $userid = bigintval($userid);
+       } // END - if
+
+       // Query for the user
+       $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
+               array($column, $userid), __FUNCTION__, __LINE__);
+
+       // Do we have a record?
+       if (SQL_NUMROWS($result) == 1) {
+               // Load data from cookies
+               $data = SQL_FETCHARRAY($result);
+
+               // Set the userid for later use
+               setCurrentUserId($data['userid']);
+               $GLOBALS['user_data'][getCurrentUserId()] = $data;
+
+               // Rewrite 'last_failure' if found
+               if (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure'])) {
+                       // Backup the raw one and zero it
+                       $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
+                       $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = 0;
+
+                       // Is it not zero?
+                       if ($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] != '0000-00-00 00:00:00') {
+                               // Seperate data/time
+                               $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure']);
+
+                               // Seperate data and time again
+                               $array['date'] = explode('-', $array[0]);
+                               $array['time'] = explode(':', $array[1]);
+
+                               // Now pass it to mktime()
+                               $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
+                                       $array['time'][0],
+                                       $array['time'][1],
+                                       $array['time'][2],
+                                       $array['date'][1],
+                                       $array['date'][2],
+                                       $array['date'][0]
+                               );
+                       } // END - if
+               } // END - if
+
+               // Found, but valid?
+               $found = isUserDataValid();
+       } // END - if
+
+       // Free memory
+       SQL_FREERESULT($result);
+
+       // Return result
+       return $found;
+}
+
 // This patched function will reduce many SELECT queries for the specified or current admin login
 function isAdmin ($admin = '') {
        // Init variables
        $ret = false; $passCookie = ''; $valPass = '';
-       //* DEBUG: */ print(__LINE__."ADMIN:".$admin."<br />");
+       //* DEBUG: */ print(__FUNCTION__.':'.$admin.'<br />');
 
        // If admin login is not given take current from cookies...
        if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
@@ -649,51 +712,57 @@ function isAdmin ($admin = '') {
                $admin = getSession('admin_login');
                $passCookie = getSession('admin_md5');
        } // END - if
-       //* DEBUG: */ print(__LINE__."ADMIN:".$admin.'/'.$passCookie."<br />");
+       //* DEBUG: */ print(__FUNCTION__.':'.$admin.'/'.$passCookie.'<br />');
 
-       // Search in array for entry
-       if (isset($GLOBALS['admin_hash'])) {
-               // Use cached string
-               $valPass = $GLOBALS['admin_hash'];
-       } elseif ((!empty($passCookie)) && (isAdminHashSet($admin) === true) && (!empty($admin))) {
-               // Login data is valid or not?
-               $valPass = generatePassString(getAdminHash($admin));
+       // Do we have cache?
+       if (!isset($GLOBALS['is_admin'][$admin])) {
+               // Init it with failed
+               $GLOBALS['is_admin'][$admin] = false;
+
+               // Search in array for entry
+               if (isset($GLOBALS['admin_hash'])) {
+                       // Use cached string
+                       $valPass = $GLOBALS['admin_hash'];
+               } elseif ((!empty($passCookie)) && (isAdminHashSet($admin) === true) && (!empty($admin))) {
+                       // Login data is valid or not?
+                       $valPass = generatePassString(getAdminHash($admin));
+
+                       // Cache it away
+                       $GLOBALS['admin_hash'] = $valPass;
+
+                       // Count cache hits
+                       incrementStatsEntry('cache_hits');
+               } elseif ((!empty($admin)) && ((!isExtensionActive('cache'))) || (isAdminHashSet($admin) === false)) {
+                       // Search for admin
+                       $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
+                               array($admin), __FUNCTION__, __LINE__);
 
-               // Cache it away
-               $GLOBALS['admin_hash'] = $valPass;
+                       // Is he admin?
+                       $passDB = '';
+                       if (SQL_NUMROWS($result) == 1) {
+                               // Admin login was found so let's load password from DB
+                               list($passDB) = SQL_FETCHROW($result);
 
-               // Count cache hits
-               incrementStatsEntry('cache_hits');
-       } elseif ((!empty($admin)) && ((!isExtensionActive('cache'))) || (isAdminHashSet($admin) === false)) {
-               // Search for admin
-               $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
-                       array($admin), __FUNCTION__, __LINE__);
+                               // Temporary cache it
+                               setAdminHash($admin, $passDB);
 
-               // Is he admin?
-               $passDB = '';
-               if (SQL_NUMROWS($result) == 1) {
-                       // Admin login was found so let's load password from DB
-                       list($passDB) = SQL_FETCHROW($result);
+                               // Generate password hash
+                               $valPass = generatePassString($passDB);
+                       } // END - if
 
-                       // Temporary cache it
-                       setAdminHash($admin, $passDB);
+                       // Free memory
+                       SQL_FREERESULT($result);
+               }
 
-                       // Generate password hash
-                       $valPass = generatePassString($passDB);
+               if (!empty($valPass)) {
+                       // Check if password is valid
+                       //* DEBUG: */ print(__FUNCTION__ . ':(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie).'<br />');
+                       $GLOBALS['is_admin'][$admin] = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
                } // END - if
-
-               // Free memory
-               SQL_FREERESULT($result);
-       }
-
-       if (!empty($valPass)) {
-               // Check if password is valid
-               //* DEBUG: */ print(__FUNCTION__ . ':' . $valPass . '/' . $passCookie . '<br />');
-               $ret = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == '*FAILED*') && (!isExtensionActive('cache'))));
        } // END - if
 
        // Return result of comparision
-       return $ret;
+       return $GLOBALS['is_admin'][$admin];
 }
 
 // Generates a list of "max receiveable emails per day"
@@ -800,6 +869,8 @@ function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
 
        // Run SQL command
        $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
+
+       // Should we look for affected rows (only update) or found rows?
        if ($updateEntry === true) {
                // Check updated/affected rows
                $ret = (SQL_AFFECTEDROWS() == 1);
@@ -818,24 +889,22 @@ function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
        return $ret;
 }
 
-//
+// Send out mails depending on the 'mod/modes' combination
+// @TODO Lame description for this function
 function sendModeMails ($mod, $modes) {
        // Load hash
-       $result_main = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
-               array(getUserId()), __FUNCTION__, __LINE__);
-       if (SQL_NUMROWS($result_main) == 1) {
-               // Load hash from database
-               list($hashDB) = SQL_FETCHROW($result_main);
-
+       if (fetchUserData(getUserId())) {
                // Extract salt from cookie
                $salt = substr(getSession('u_hash'), 0, -40);
 
                // Now let's compare passwords
-               $hash = generatePassString($hashDB);
+               $hash = generatePassString(getUserData('password'));
+
+               // Does the hash match or should we change it?
                if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
                        // Load user's data               0        1        2         3        4      5    6      7
                        $result = SQL_QUERY_ESC("SELECT gender, surname, family, street_nr, country, zip, city, email FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND password='%s' LIMIT 1",
-                               array(getUserId(), $hashDB), __FUNCTION__, __LINE__);
+                               array(getUserId(), getUserData('password')), __FUNCTION__, __LINE__);
                        if (SQL_NUMROWS($result) == 1) {
                                // Load the data
                                $content = SQL_FETCHARRAY($result, 0, false);
@@ -847,7 +916,7 @@ function sendModeMails ($mod, $modes) {
                                $content['gender'] = translateGender($content['gender']);
 
                                // Clear/init the content variable
-                               $content['info'] = '';
+                               $content['message'] = '';
 
                                switch ($mod) {
                                        case 'mydata':
@@ -864,10 +933,10 @@ function sendModeMails ($mod, $modes) {
 
                                                                default:
                                                                        logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
-                                                                       $content['message'] = getMessage('MEMBER_UNKNOWN_MODE').": ".$mode."\n\n";
+                                                                       $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
                                                                        break;
                                                        } // END - switch
-                                               } // END - if
+                                               } // END - foreach
 
                                                if (isExtensionActive('country')) {
                                                        // Replace code with description
@@ -965,7 +1034,7 @@ function getModeAction ($mode, $what) {
                // Get it directly from URL
                return getAction();
        }
-       //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$ret."<br />");
+       //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$ret.'<br />');
 
        // Does the module have a menu?
        if (ifModuleHasMenu($mode)) {
@@ -1072,7 +1141,7 @@ function getPaymentPoints ($pid, $lookFor = 'price') {
        return $ret;
 }
 
-// Remove a receiver's ID from $receivers and add a link for him to confirm
+// Remove a receiver's id from $receivers and add a link for him to confirm
 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $bonus = false) {
        // Default is not removed
        $ret = 'failed';
@@ -1084,7 +1153,7 @@ function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = '', $
 
                // Is there already a line for this user available?
                if ($stats_id > 0) {
-                       // Only when we got a real stats ID continue searching for the entry
+                       // Only when we got a real stats id continue searching for the entry
                        $type = 'NORMAL'; $rowName = 'stats_id';
                        if ($bonus) { $type = 'BONUS'; $rowName = 'bonus_id'; }
 
@@ -1155,6 +1224,7 @@ function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatemen
        }
 
        // Return value
+       //* DEBUG: */ print 'ret='.$ret.'<br />';
        return $ret;
 }
 // Getter fro ref level percents
@@ -1197,7 +1267,7 @@ function getReferalLevelPercents ($level) {
  * Dynamic referal system, can also send mails!
  *
  * subject     = Subject line, write in lower-case letters and underscore is allowed
- * userid         = Referal ID wich should receive...
+ * userid         = Referal id wich should receive...
  * points      = ... xxx points
  * sendNotify  = shall I send the referal an email or not?
  * rid         = inc/modules/guest/what-confirm.php need this
@@ -1250,14 +1320,10 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
        if ($locked === true) $data = 'locked_points';
 
        // Check user account
-       $result_user = SQL_QUERY_ESC("SELECT `refid`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
-               array(bigintval($userid)), __FUNCTION__, __LINE__);
-
-       //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},numRows=".SQL_NUMROWS($result_user).",points={$points}<br />");
-       if (SQL_NUMROWS($result_user) == 1) {
+       //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},points={$points}<br />");
+       if (fetchUserData($userid)) {
                // This is the user and his ref
-               list($ref, $email) = SQL_FETCHROW($result_user);
-               $GLOBALS['cache_array']['add_userid'][$ref] = $userid;
+               $GLOBALS['cache_array']['add_userid'][getUserData('refid')] = $userid;
 
                // Get percents
                $per = getReferalLevelPercents($GLOBALS['ref_level']);
@@ -1290,20 +1356,20 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
                        } // END - if
 
                        // Points updated, maybe I shall send him an email?
-                       if (($sendNotify === true) && ($ref > 0) && ($locked === false)) {
+                       if (($sendNotify === true) && (getUserData('refid') > 0) && ($locked === false)) {
                                // Prepare content
                                $content = array(
                                        'percents' => $per,
                                        'level'    => bigintval($GLOBALS['ref_level']),
                                        'points'   => $ref_points,
-                                       'refid'    => bigintval($ref)
+                                       'refid'    => getUserData('refid')
                                );
 
                                // Load email template
                                $message = loadEmailTemplate('confirm-referal', $content, bigintval($userid));
 
-                               sendEmail($email, THANX_REFERRAL_ONE, $message);
-                       } elseif (($sendNotify) && ($ref == 0) && ($locked === false) && ($add_mode == 'direct')) {
+                               sendEmail(getUserData('email'), THANX_REFERAL_ONE, $message);
+                       } elseif (($sendNotify) && (getUserData('refid') == 0) && ($locked === false) && ($add_mode == 'direct')) {
                                // Prepare content
                                $content = array(
                                        'text'   => getMessage('REASON_DIRECT_PAYMENT'),
@@ -1314,21 +1380,19 @@ function addPointsThroughReferalSystem ($subject, $userid, $points, $sendNotify
                                $message = loadEmailTemplate('add-points', $content, $userid);
 
                                // And sent it away
-                               sendEmail($email, getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
+                               sendEmail(getUserData('email'), getMessage('SUBJECT_DIRECT_PAYMENT'), $message);
                                if (!isGetRequestElementSet('mid')) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
                        }
 
                        // Maybe there's another ref?
-                       if (($ref > 0) && ($points > 0) && ($ref != $userid) && ($add_mode == 'ref')) {
+                       if ((getUserData('refid') > 0) && ($points > 0) && (getUserData('refid') != $userid) && ($add_mode == 'ref')) {
                                // Then let's credit him here...
-                               //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref},points={$points} - ADVANCE!<br />");
-                               addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), $ref, $points, $sendNotify, $ref, $locked);
+                               //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref=".getUserData('refid').",points={$points} - ADVANCE!<br />");
+                               addPointsThroughReferalSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, $sendNotify, getUserData('refid'), $locked);
                        } // END - if
                } // END - if
        } // END - if
 
-       // Free result
-       SQL_FREERESULT($result_user);
        //* DEBUG: */ print("</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />");
 }
 
@@ -1343,7 +1407,7 @@ function updateReferalCounter ($userid) {
                array(bigintval($userid), $GLOBALS['cache_array']['ref_level'][$userid]), __FUNCTION__, __LINE__);
 
        // When no entry was updated then we have to create it here
-       //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS()."<br />");
+       //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS().'<br />');
        if (SQL_AFFECTEDROWS() < 1) {
                // First count!
                SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
@@ -1351,23 +1415,24 @@ function updateReferalCounter ($userid) {
                //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid}<br />");
        } // END - if
 
-       // Check for his referal
-       $result = SQL_QUERY_ESC("SELECT `refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-               array(bigintval($userid)), __FUNCTION__, __LINE__);
+       // Init referal id
+       $ref = 0;
 
-       // Load refid
-       list($ref) = SQL_FETCHROW($result);
+       // Check for his referal
+       if (fetchUserData($userid)) {
+               // Get it
+               $ref = getUserData('refid');
+       } // END - if
 
-       // Free memory
-       SQL_FREERESULT($result);
        //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):userid={$userid},ref={$ref}<br />");
 
        // When he has a referal...
        if (($ref > 0) && ($ref != $userid)) {
                // Move to next referal level and count his counter one up!
                //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - ADVANCE!<br />");
-               $GLOBALS['cache_array']['ref_level'][$userid]++; updateReferalCounter($ref);
-       } elseif ((($ref == $userid) || ($ref == 0)) && (getExtensionVersion('cache') >= '0.1.2')) {
+               $GLOBALS['cache_array']['ref_level'][$userid]++;
+               updateReferalCounter($ref);
+       } elseif ((($ref == $userid) || ($ref == 0)) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
                // Remove cache here
                //* DEBUG: */ print(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - CACHE!<br />");
                rebuildCacheFile('refsystem', 'refsystem');
@@ -1398,7 +1463,7 @@ function sendAdminEmails ($subj, $message) {
        // Really simple... ;-)
 }
 
-// Get ID number from administrator's login name
+// Get id number from administrator's login name
 function getAdminId ($login) {
        // By default no admin is found
        $ret = '-1';
@@ -1641,11 +1706,17 @@ function FILTER_ACTIVATE_EXCHANGE () {
 // Deletes a user account with given reason
 function deleteUserAccount ($userid, $reason) {
        $points = 0;
-       $result = SQL_QUERY_ESC("SELECT (SUM(p.points) - d.used_points) AS points
-FROM `{?_MYSQL_PREFIX?}_user_points` AS p
-LEFT JOIN `{?_MYSQL_PREFIX?}_user_data` AS d
-ON p.userid=d.userid
-WHERE p.userid=%s", array(bigintval($userid)), __FUNCTION__, __LINE__);
+       $result = SQL_QUERY_ESC("SELECT
+       (SUM(p.points) - d.used_points) AS points
+FROM
+       `{?_MYSQL_PREFIX?}_user_points` AS p
+LEFT JOIN
+       `{?_MYSQL_PREFIX?}_user_data` AS d
+ON
+       p.userid=d.userid
+WHERE
+       p.userid=%s",
+               array(bigintval($userid)), __FUNCTION__, __LINE__);
        if (SQL_NUMROWS($result) == 1) {
                // Save his points to add them to the jackpot
                list($points) = SQL_FETCHROW($result);
@@ -1913,7 +1984,7 @@ VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
 // Generate a receiver list for given category and maximum receivers
 function generateReceiverList ($cat, $receiver, $mode = '') {
        // Init variables
-       $CAT_TABS     = "%s";
+       $CAT_TABS     = '';
        $CAT_WHERE    = '';
        $receiverList = '';
        $result       = false;
@@ -1932,7 +2003,7 @@ function generateReceiverList ($cat, $receiver, $mode = '') {
        if ($cat > 0) {
                // Select category
                $CAT_TABS  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.userid=c.userid";
-               $CAT_WHERE = " AND c.cat_id=%s";
+               $CAT_WHERE = sprintf(" AND c.cat_id=%s", $cat);
        } // END - if
 
        // Exclude users in holiday?
@@ -1945,14 +2016,12 @@ function generateReceiverList ($cat, $receiver, $mode = '') {
                // Only include HTML receivers
                $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED' AND d.`html`='Y'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
                        array(
-                               $cat,
                                $receiver
                        ), __FUNCTION__, __LINE__);
        } else {
                // Include all
                $result = SQL_QUERY_ESC("SELECT d.userid FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED'".$CAT_WHERE." ORDER BY d.{?order_select?} {?order_mode?} LIMIT %s",
                        array(
-                               $cat,
                                $receiver
                        ), __FUNCTION__, __LINE__);
        }