mailer project continued:
[mailer.git] / inc / mysql-manager.php
index 50b4e88d02489c41851c72c2c4c821c64336099c..c72706cbd7a135ae93c65367927a18aca8c93ab6 100644 (file)
@@ -16,7 +16,7 @@
  * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -42,16 +42,19 @@ if (!defined('__SECURITY')) {
 
 // "Getter" for module description
 // @TODO Can we cache this?
-function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
+function getTitleFromMenu ($mode, $what, $column = 'what', $ADD = '') {
+       // Debug message
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',what=' . $what . ',column=' . $column . ',add=' . $ADD);
+
        // Fix empty 'what'
        if (empty($what)) {
                $what = getIndexHome();
        } elseif ((isGetRequestElementSet('action')) && ($column == 'what')) {
                // Get it from action
                return getTitleFromMenu($mode, getAction(), 'action', $ADD);
-       } elseif ($what == 'overview') {
+       } elseif ($what == 'welcome') {
                // Overview page
-               return '{--WHAT_IS_OVERVIEW--}';
+               return '{--WHAT_IS_WELCOME--}';
        }
 
        // Default is not found
@@ -163,7 +166,7 @@ function addYouAreHereLink ($accessLevel, $FQFN, $return = false) {
 
                // Can we close the you-are-here navigation?
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . 'getWhat()=' . getWhat());
-               if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
+               if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'welcome')))) {
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
                        // Add closing div and br-tag
                        $GLOBALS['nav_depth'] = '0';
@@ -378,7 +381,7 @@ ORDER BY
        } // END - if
 }
 
-// Checks wether the current user is a member
+// Checks whether the current user is a member
 function isMember () {
        // By default no member
        $ret = false;
@@ -423,7 +426,7 @@ function isMember () {
                // So did we now have valid data and an unlocked user?
                if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
                        // Transfer last module and online time
-                       $GLOBALS['last_online']['module'] = getUserData('last_module');
+                       $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
                        $GLOBALS['last_online']['online'] = getUserData('last_online');
 
                        // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
@@ -453,7 +456,7 @@ function fetchUserData ($value, $column = 'userid') {
                return false;
        } elseif (is_null($value)) {
                // This shall never happen, so please report it
-               debug_report_bug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
+               reportBug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
        }
 
        // If we should look for userid secure&set it here
@@ -467,7 +470,7 @@ function fetchUserData ($value, $column = 'userid') {
                // Don't look for invalid userids...
                if (!isValidUserId($value)) {
                        // Invalid, so abort here
-                       debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
+                       reportBug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
                } elseif (isUserDataValid()) {
                        // Use cache, so it is fine
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
@@ -482,14 +485,11 @@ function fetchUserData ($value, $column = 'userid') {
        // By default none was found
        $found = false;
 
-       // Extra statements
-       $ADD = '';
-       if (isExtensionInstalledAndNewer('user', '0.3.5')) {
-               $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
-       } // END - if
+       // Extra SQL statements
+       $ADD = runFilterChain('convert_user_data_columns', '');
 
        // Query for the user
-       $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
+       $result = SQL_QUERY_ESC("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
                array($column, $value), __FUNCTION__, __LINE__);
 
        // Do we have a record?
@@ -541,7 +541,12 @@ function fetchUserData ($value, $column = 'userid') {
        return $found;
 }
 
-// This patched function will reduce many SELECT queries for the specified or current admin login
+/*
+ * Checks whether the current session bears a valid admin id and password hash.
+ *
+ * This patched function will reduce many SELECT queries for the current admin
+ * login.
+ */
 function isAdmin () {
        // No admin in installation phase!
        if ((isInstallationPhase()) || (!isAdminRegistered())) {
@@ -551,7 +556,7 @@ function isAdmin () {
        // Init variables
        $ret = false;
        $adminId = '0';
-       $passCookie = '';
+       $passwordFromCookie = '';
        $valPass = '';
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
 
@@ -559,12 +564,16 @@ function isAdmin () {
        if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
                // Get admin login and password from session/cookies
                $adminId    = getCurrentAdminId();
-               $passCookie = getAdminMd5();
+               $passwordFromCookie = getAdminMd5();
        } // END - if
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mainId=' . $adminId . 'passCookie=' . $passCookie);
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . 'passwordFromCookie=' . $passwordFromCookie);
 
        // Abort if admin id is zero
        if ($adminId == '0') {
+               // A very noisy debug message ...
+               //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
+
+               // Abort here now
                return false;
        } // END - if
 
@@ -577,7 +586,7 @@ function isAdmin () {
                if (isset($GLOBALS['admin_hash'])) {
                        // Use cached string
                        $valPass = $GLOBALS['admin_hash'];
-               } elseif ((!empty($passCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
+               } elseif ((!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
                        // Login data is valid or not?
                        $valPass = encodeHashForCookie(getAdminHash($adminId));
 
@@ -596,8 +605,8 @@ function isAdmin () {
 
                if (!empty($valPass)) {
                        // Check if password is valid
-                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
-                       $GLOBALS[__FUNCTION__][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passwordFromCookie . ')='.intval($valPass == $passwordFromCookie));
+                       $GLOBALS[__FUNCTION__][$adminId] = ($GLOBALS['admin_hash'] == $passwordFromCookie);
                } // END - if
        } // END - if
 
@@ -617,6 +626,7 @@ function addMaxReceiveList ($mode, $default = '', $return = false) {
                        __FUNCTION__, __LINE__);
                        break;
 
+               case 'admin':
                case 'member':
                        // Members are allowed to set to zero mails per day (we will change this soon!)
                        $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
@@ -633,7 +643,11 @@ function addMaxReceiveList ($mode, $default = '', $return = false) {
                $OUT = '';
                while ($content = SQL_FETCHARRAY($result)) {
                        $OUT .= '      <option value="' . $content['value'] . '"';
-                       if (postRequestElement('max_mails') == $content['value']) $OUT .= ' selected="selected"';
+
+                       if (postRequestElement('max_mails') == $content['value']) {
+                               $OUT .= ' selected="selected"';
+                       } // END - if
+
                        $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
                        if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
                        $OUT .= '</option>';
@@ -643,7 +657,7 @@ function addMaxReceiveList ($mode, $default = '', $return = false) {
                $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
        } else {
                // Maybe the admin has to setup some maximum values?
-               debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
+               reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
        }
 
        // Free result
@@ -658,7 +672,7 @@ function addMaxReceiveList ($mode, $default = '', $return = false) {
        }
 }
 
-// Checks wether the given email address is used.
+// Checks whether the given email address is used.
 function isEmailTaken ($email) {
        // Default is no userid
        $useridSql = ' IS NOT NULL';
@@ -723,7 +737,7 @@ function isMenuActionValid ($mode, $action, $what, $updateEntry = false) {
                                $action,
                                $what
                        ), __FUNCTION__, __LINE__, false);
-       } elseif (($what != 'overview') && (!empty($what))) {
+       } elseif (($what != 'welcome') && (!empty($what))) {
                // Other actions
                $sql = SQL_QUERY_ESC("SELECT `id`,`what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what`='%s'".$add." ORDER BY `action` DESC LIMIT 1",
                        array(
@@ -770,16 +784,7 @@ function getActionFromModuleWhat ($module, $what) {
 
        if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
                // sql_patches is missing so choose depending on mode
-               if (isWhatSet()) {
-                       // Use setted what
-                       $what = getWhat();
-               } elseif ($module == 'admin') {
-                       // Admin area
-                       $what = 'overview';
-               } else {
-                       // Everywhere else
-                       $what = 'welcome';
-               }
+               $what = determineWhat($module);
        } elseif ((empty($what)) && ($module != 'admin')) {
                // Use configured 'home'
                $what = getIndexHome();
@@ -793,7 +798,7 @@ function getActionFromModuleWhat ($module, $what) {
                } elseif (isActionSet()) {
                        // Get it directly from URL
                        return getAction();
-               } elseif (($what == 'overview') || (!isWhatSet())) {
+               } elseif (($what == 'welcome') || (!isWhatSet())) {
                        // Default value for admin area
                        $data['action'] = 'login';
                }
@@ -865,13 +870,15 @@ function getCategory ($cid) {
 }
 
 // Get a string of "mail title" and price back
-function getPaymentTitlePrice ($pid, $full=false) {
+function getPaymentTitlePrice ($pid, $full = false) {
        // Default is not found
        $ret = '{--_PAYMENT_404--}';
 
        // Load payment data
        $result = SQL_QUERY_ESC("SELECT `mail_title`,`price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
-               array(bigintval($pid)), __FUNCTION__, __LINE__);
+               array(
+                       bigintval($pid)
+               ), __FUNCTION__, __LINE__);
 
        // Do we have an entry?
        if (SQL_NUMROWS($result) == 1) {
@@ -900,7 +907,10 @@ function getPaymentPoints ($pid, $lookFor = 'price') {
 
        // Search for it in database
        $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
-               array($lookFor, $pid), __FUNCTION__, __LINE__);
+               array(
+                       $lookFor,
+                       bigintval($pid)
+               ), __FUNCTION__, __LINE__);
 
        // Is the entry there?
        if (SQL_NUMROWS($result) == 1) {
@@ -938,7 +948,7 @@ function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isB
                        } // END - if
 
                        // Try to look the entry up
-                       $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND link_type='%s' LIMIT 1",
+                       $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
                                array(
                                        $rowName,
                                        bigintval($statsId),
@@ -949,7 +959,7 @@ function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isB
                        // Was it *not* found?
                        if (SQL_HASZERONUMS($result)) {
                                // So we add one!
-                               SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`,`userid`,`link_type`) VALUES ('%s','%s','%s')",
+                               SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`,`userid`,`link_type`) VALUES (%s,%s,'%s')",
                                        array(
                                                $rowName,
                                                bigintval($statsId),
@@ -1032,7 +1042,7 @@ function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatemen
        SQL_FREERESULT($result);
 
        // Fix empty values
-       if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
+       if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
                // Float number
                $data['res'] = '0.00000';
        } elseif (''.$data['res'].'' == '') {
@@ -1045,14 +1055,27 @@ function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatemen
        return $data['res'];
 }
 
-// Sends out mail to all administrators. This function is no longer obsolete
-// because we need it when there is no ext-admins installed
-function sendAdminEmails ($subj, $message) {
+/**
+ * Sends out mail to all administrators. This function is no longer obsolete
+ * because we need it when there is no ext-admins installed
+ */
+function sendAdminEmails ($subject, $message, $isBugReport = false) {
+       // Default is no special header
+       $mailHeader = '';
+
+       // Is it a bug report?
+       if ($isBugReport === true) {
+               // Then add a reply-to line back to the author (me)
+               $mailHeader = 'Reply-To: webmaster@mxchange.org' . chr(10);
+       } // END - if
+
        // Load all admin email addresses
        $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
+
+       // And send the notification to all of them
        while ($content = SQL_FETCHARRAY($result)) {
                // Send the email out
-               sendEmail($content['email'], $subj, $message);
+               sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
        } // END - if
 
        // Free result
@@ -1290,7 +1313,7 @@ function getAdminMenuMode ($adminId) {
 }
 
 // Generates an option list from various parameters
-function generateOptionList ($table, $id, $name, $default = '', $special = '', $whereStatement = '', $disabled = array(), $callback = '') {
+function generateOptions ($table, $id, $name, $default = '', $special = '', $whereStatement = '', $disabled = array(), $callback = '') {
        $ret = '';
        if ($table == '/ARRAY/') {
                // Selection from array
@@ -1317,7 +1340,7 @@ function generateOptionList ($table, $id, $name, $default = '', $special = '', $
                        } // END - foreach
                } else {
                        // Problem in request
-                       debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
+                       reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
                }
        } else {
                // Data from database
@@ -1459,14 +1482,10 @@ function getWhatFromModule ($modCheck) {
        // Default is empty
        $what = '';
 
+       // Check on given module
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
        switch ($modCheck) {
-               case 'admin':
-                       $what = 'overview';
-                       break;
-
-               case 'login':
-               case 'index':
+               case 'index': // Guest area
                        // Is ext-sql_patches installed and newer than 0.0.5?
                        if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
                                // Use it from config
@@ -1477,8 +1496,8 @@ function getWhatFromModule ($modCheck) {
                        }
                        break;
 
-               default:
-                       $what = '';
+               default: // Default for all other menus (getIndexHome() is for index module only)
+                       $what = 'welcome';
                        break;
        } // END - switch
 
@@ -1487,13 +1506,13 @@ function getWhatFromModule ($modCheck) {
 }
 
 // Returns HTML code with an option list of all categories
-function generateCategoryOptionsList ($mode) {
+function generateCategoryOptionsList ($mode, $userid = NULL) {
        // Prepare WHERE statement
        $whereStatement = " WHERE `visible`='Y'";
        if (isAdmin()) $whereStatement = '';
 
        // Initialize array...
-       $CATS = array(
+       $categories = array(
                'id'      => array(),
                'name'    => array(),
                'userids' => array()
@@ -1508,12 +1527,15 @@ function generateCategoryOptionsList ($mode) {
                // ... and begin loading stuff
                while ($content = SQL_FETCHARRAY($result)) {
                        // Transfer some data
-                       $CATS['id'][]   = $content['id'];
-                       $CATS['name'][] = $content['cat'];
+                       $categories['id'][]   = $content['id'];
+                       array_push($categories['name'], $content['cat']);
 
                        // Check which users are in this category
-                       $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
-                               array(bigintval($content['id'])), __FUNCTION__, __LINE__);
+                       $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
+                               array(
+                                       bigintval($content['id']),
+                                       convertNullToZero($userid)
+                               ), __FUNCTION__, __LINE__);
 
                        // Init count
                        $userid_cnt = '0';
@@ -1521,14 +1543,14 @@ function generateCategoryOptionsList ($mode) {
                        // Start adding all
                        while ($data = SQL_FETCHARRAY($result_userids)) {
                                // Add user count
-                               $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
+                               $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
                        } // END - while
 
                        // Free memory
                        SQL_FREERESULT($result_userids);
 
                        // Add counter
-                       $CATS['userids'][] = $userid_cnt;
+                       array_push($categories['userids'], $userid_cnt);
                } // END - while
 
                // Free memory
@@ -1536,9 +1558,8 @@ function generateCategoryOptionsList ($mode) {
 
                // Generate options
                $OUT = '';
-               foreach ($CATS['id'] as $key => $value) {
-                       if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
-                       $OUT .= '      <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
+               foreach ($categories['id'] as $key => $value) {
+                       $OUT .= '      <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
                } // END - foreach
        } else {
                // No cateogries are defined yet
@@ -1612,8 +1633,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 ($categoryId, $receiver, $mode = '') {
        // Init variables
-       $CAT_TABS     = '';
-       $CAT_WHERE    = '';
+       $extraColumns = '';
        $receiverList = '';
        $result       = false;
 
@@ -1627,32 +1647,32 @@ function generateReceiverList ($categoryId, $receiver, $mode = '') {
                $receiver = getTotalReceivers($mode);
        } // END - if
 
+       // Exclude (maybe exclude) testers
+       $addWhere = runFilterChain('user_exclusion_sql', ' ');
+
        // Category given?
        if ($categoryId > 0) {
                // Select category
-               $CAT_TABS  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
-               $CAT_WHERE = sprintf(" AND c.`cat_id`=%s", $categoryId);
+               $extraColumns  = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
+               $addWhere = sprintf(" AND c.`cat_id`=%s", $categoryId);
        } // END - if
 
        // Exclude users in holiday?
        if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
                // Add something for the holiday extension
-               $CAT_WHERE .= " AND d.`holiday_active`='N'";
+               $addWhere .= " AND d.`holiday_active`='N'";
        } // END - if
 
+       // Include only HTML recipients?
        if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
-               // 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(
-                               $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(
-                               $receiver
-                       ), __FUNCTION__, __LINE__);
-       }
+               $addWhere .= " AND d.`html`='Y'";
+       } // END - if
+
+       // Run query
+       $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$extraColumns." WHERE d.`status`='CONFIRMED' ".$addWhere." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
+               array(
+                       $receiver
+               ), __FUNCTION__, __LINE__);
 
        // Entries found?
        if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
@@ -1736,7 +1756,6 @@ function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId =
 }
 
 // Updates last module / online time
-// @TODO Fix inconsistency between last_module and getWhat()
 function updateLastActivity($userid) {
        // Is 'what' set?
        if (isWhatSet()) {
@@ -1744,34 +1763,85 @@ function updateLastActivity($userid) {
                SQL_QUERY_ESC("UPDATE
        `{?_MYSQL_PREFIX?}_user_data`
 SET
-       `last_module`='%s',
+       `%s`='%s',
        `last_online`=UNIX_TIMESTAMP(),
        `REMOTE_ADDR`='%s'
 WHERE
        `userid`=%s
 LIMIT 1",
                array(
+                       getUserLastWhatName(),
                        getWhat(),
                        detectRemoteAddr(),
                        bigintval($userid)
                ), __FUNCTION__, __LINE__);
        } else {
                // No what set, needs to be ignored (last_module is last_what)
-               // @TODO Rename last_module to last_what to make it more clear
                SQL_QUERY_ESC("UPDATE
        `{?_MYSQL_PREFIX?}_user_data`
 SET
+       `%s`=NULL,
        `last_online`=UNIX_TIMESTAMP(),
        `REMOTE_ADDR`='%s'
 WHERE
        `userid`=%s
 LIMIT 1",
                array(
+                       getUserLastWhatName(),
                        detectRemoteAddr(),
                        bigintval($userid)
                ), __FUNCTION__, __LINE__);
        }
 }
 
+/**
+ * Checks if given subject is found and if not, adds an SQL query to the
+ * extension registration queue.
+ */
+function registerExtensionPointsData ($subject, $columnName, $lockedMode, $paymentMethod) {
+       // Default is old extension version
+       $add = '';
+
+       // Is the extension equal or newer 0.8.9?
+       if (isExtensionInstalledAndNewer('sql_patches', '0.8.9')) {
+               // Then add provider
+               $add = " AND `account_provider`='EXTENSION'";
+       } // END - if
+
+       // Is the 'subject' there?
+       if (countSumTotalData($subject, 'points_data', 'id', 'subject', true, $add) == 0) {
+               // Not found so add an SQL query
+               addExtensionSql(sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`,`column_name`,`locked_mode`,`payment_method`) VALUES ('%s','%s','%s','%s')",
+                       $subject,
+                       $columnName,
+                       $lockedMode,
+                       $paymentMethod
+               ));
+       } // END - if
+}
+
+/**
+ * Checks if given subject is found and if so, adds an SQL query to the
+ * extension unregistration queue.
+ */
+function unregisterExtensionPointsData ($subject) {
+       // Default is old extension version
+       $add = '';
+
+       // Is the extension equal or newer 0.8.9?
+       if (isExtensionInstalledAndNewer('sql_patches', '0.8.9')) {
+               // Then add provider
+               $add = " AND `account_provider`='EXTENSION'";
+       } // END - if
+
+       // Is the 'subject' there?
+       if (countSumTotalData($subject, 'points_data', 'id', 'subject', true, $add) == 1) {
+               // Found one or more, so add an SQL query
+               addExtensionSql(sprintf("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_points_data` WHERE `subject`='%s'" . $add . " LIMIT 1",
+                       $subject
+               ));
+       } // END - if
+}
+
 // [EOF]
 ?>