Fixes/rewrites for missing sql_patches and check on admin's default access mode ...
[mailer.git] / inc / mysql-manager.php
index f4f85cbc21b50ff8302ae2ea94d265d153e952fa..db3015241a05653e8326fa33ccd6c73562a577eb 100644 (file)
  * -------------------------------------------------------------------- *
  * Kurzbeschreibung  : Alle MySQL-Relevanten Funktionen                 *
  * -------------------------------------------------------------------- *
- *                                                                      *
+ * $Revision::                                                        $ *
+ * $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 - 2008 by Roland Haeder                           *
  * For more information visit: http://www.mxchange.org                  *
@@ -54,7 +59,7 @@ function ADD_MODULE_TITLE ($mod) {
                        incrementConfigEntry('cache_hits');
                } elseif (!EXT_IS_ACTIVE("cache")) {
                        // Load from database
-                       $result = SQL_QUERY_ESC("SELECT title FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE module='%s' LIMIT 1",
+                       $result = SQL_QUERY_ESC("SELECT title FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE `module`='%s' LIMIT 1",
                                array($mod), __FUNCTION__, __LINE__);
                        list($name) = SQL_FETCHROW($result);
                        SQL_FREERESULT($result);
@@ -114,6 +119,12 @@ function checkModulePermissions ($mod) {
 
        // Check if cache is latest version
        if (GET_EXT_VERSION("cache") >= "0.1.2") {
+               // Is the cache there?
+               if (!isset($GLOBALS['cache_array']['modules'])) {
+                       // This should normally not happen...
+                       debug_report_bug("Cache 'modules' is gone.");
+               } // END - if
+
                // Is the module cached?
                if (isset($GLOBALS['cache_array']['modules']['locked'][$mod_chk])) {
                        // Check cache
@@ -131,7 +142,7 @@ function checkModulePermissions ($mod) {
                }
        } elseif (!EXT_IS_ACTIVE("cache")) {
                // Check for module in database
-               $result = SQL_QUERY_ESC("SELECT locked, hidden, admin_only, mem_only FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE module='%s' LIMIT 1",
+               $result = SQL_QUERY_ESC("SELECT locked, hidden, admin_only, mem_only FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE `module`='%s' LIMIT 1",
                        array($mod_chk), __FUNCTION__, __LINE__);
                if (SQL_NUMROWS($result) == 1) {
                        // Read data
@@ -244,7 +255,7 @@ function ADD_DESCR ($ACC_LVL, $FQFN, $return = false, $output = true) {
                        $modCheck = $GLOBALS['module'];
                        break;
                }
-               $AND = " AND (what='' OR `what` IS NULL)";
+               $AND = " AND (`what`='' OR `what` IS NULL)";
        } elseif (substr($file, 0, 5) == "what-") {
                // This is an admin what file!
                $type = "what";
@@ -306,7 +317,7 @@ function ADD_DESCR ($ACC_LVL, $FQFN, $return = false, $output = true) {
                list($ret) = SQL_FETCHROW($result);
 
                // Shall we return it?
-               if ($return) {
+               if ($return === true) {
                        // Return title
                        return $ret;
                } elseif (((GET_EXT_VERSION("sql_patches") >= "0.2.3") && (getConfig('youre_here') == "Y")) || ((IS_ADMIN()) && ($modCheck == "admin"))) {
@@ -351,75 +362,84 @@ function ADD_MENU ($MODE, $act, $wht) {
 
        // is the menu action valid?
        if (!VALIDATE_MENU_ACTION($MODE, $act, $wht, true)) {
-               return getMessage('CODE_MENU_NOT_VALID');
+               return getCode('MENU_NOT_VALID');
        } // END - if
 
        // Non-admin shall not see all menus
        if (!IS_ADMIN()) {
                $AND = " AND `visible`='Y' AND `locked`='N'";
-       }
+       } // END - if
 
        // Load SQL data and add the menu to the output stream...
-       $result_main = SQL_QUERY_ESC("SELECT title, action FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE (what='' OR `what` IS NULL)".$AND." ORDER BY `sort`",
+       $result_main = SQL_QUERY_ESC("SELECT title, action FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE (`what`='' OR `what` IS NULL)".$AND." ORDER BY `sort`",
                array($MODE), __FUNCTION__, __LINE__);
        //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
        if (SQL_NUMROWS($result_main) > 0) {
                OUTPUT_HTML("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"".$MODE."_menu\">");
                // There are menus available, so we simply display them... :)
-               while (list($main_title, $main_action) = SQL_FETCHROW($result_main)) {
-                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
+               while ($content = SQL_FETCHARRAY($result_main)) {
+                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$content['action']."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
                        // Init variables
-                       $BLOCK_MODE = false; $act = $main_action;
-
-                       // Prepare content
-                       $content = array(
-                               'action' => $main_action,
-                               'title'  => $main_title
-                       );
+                       $GLOBALS['block_mode'] = false;
+                       $act = $content['action'];
 
                        // Load menu header template
                        LOAD_TEMPLATE($MODE."_menu_title", false, $content);
 
-                       $result_sub = SQL_QUERY_ESC("SELECT title, what FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$AND." ORDER BY `sort`",
-                        array($MODE, $main_action), __FUNCTION__, __LINE__);
+                       // Sub menu
+                       $result_sub = SQL_QUERY_ESC("SELECT title AS sub_title, what AS sub_what FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$AND." ORDER BY `sort`",
+                               array($MODE, $content['action']), __FUNCTION__, __LINE__);
+
+                       // Get number of rows
                        $ctl = SQL_NUMROWS($result_sub);
+
+                       // Do we have some entries?
                        if ($ctl > 0) {
-                               $cnt=0;
-                               while (list($sub_title, $sub_what) = SQL_FETCHROW($result_sub)) {
+                               // Init counter
+                               $cnt = 0;
+
+                               // Load all sub menus
+                               while ($content2 = SQL_FETCHARRAY($result_sub)) {
+                                       // Merge both arrays in one
+                                       $content = merge_array($content, $content2);
+
                                        // Init content
-                                       $content = "";
+                                       $OUT = "";
 
                                        // Full file name for checking menu
-                                       //* DEBUG: */ echo __LINE__.":!!!!".$sub_what."!!!<br />\n";
-                                       $FQFN = sprintf("%sinc/modules/%s/what-%s.php", constant('PATH'), $MODE, $sub_what);
-                                       if (FILE_READABLE($FQFN)) {
-                                               if ((!empty($wht)) && (($wht == $sub_what))) {
-                                                       $content = "<strong>";
+                                       //* DEBUG: */ echo __LINE__.":!!!!".$content['sub_what']."!!!<br />\n";
+                                       $INC = sprintf("inc/modules/%s/what-%s.php", $MODE, $content['sub_what']);
+                                       if (INCLUDE_READABLE($INC)) {
+                                               if ((!empty($wht)) && (($wht == $content['sub_what']))) {
+                                                       $OUT = "<strong>";
                                                }
 
                                                // Navigation link
-                                               $content .= "<a name=\"menu\" class=\"menu_blur\" href=\"{!URL!}/modules.php?module=".$GLOBALS['module']."&amp;what=".$sub_what.ADD_URL_DATA("")."\" target=\"_self\">";
+                                               $OUT .= "<a name=\"menu\" class=\"menu_blur\" href=\"{!URL!}/modules.php?module=".$GLOBALS['module']."&amp;what=".$content['sub_what'].ADD_URL_DATA("")."\" target=\"_self\">";
                                        } else {
-                                               $content .= "<em>";
+                                               $OUT .= "<em>";
                                        }
 
                                        // Menu title
-                                       $content .= getConfig('menu_blur_spacer') . $sub_title;
+                                       $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
 
-                                       if (FILE_READABLE($FQFN)) {
-                                               $content .= "</a>";
+                                       if (INCLUDE_READABLE($INC)) {
+                                               $OUT .= "</a>";
                                        } else {
-                                               $content .= "</em>";
+                                               $OUT .= "</em>";
                                        }
 
-                                       if ((!empty($wht)) && (($wht == $sub_what))) {
-                                               $content .= "</strong>";
-                                       }
-                                       $wht = $sub_what; $cnt++;
-                                       // Prepare array
+                                       if ((!empty($wht)) && (($wht == $content['sub_what']))) {
+                                               $OUT .= "</strong>";
+                                       } // END - if
+
+                                       // Remember 'what' for next round and count it up
+                                       $wht = $content['sub_what']; $cnt++;
+
+                                       // Rewrite array
                                        $content =  array(
-                                               'menu' => $content,
-                                               'what' => $sub_what
+                                               'menu' => $OUT,
+                                               'what' => $content['sub_what']
                                        );
 
                                        // Add regular menu row or bottom row?
@@ -431,31 +451,33 @@ function ADD_MENU ($MODE, $act, $wht) {
                                }
                        } else {
                                // This is a menu block... ;-)
-                               $BLOCK_MODE = true;
-                               $INC_BLOCK = sprintf("inc/modules/%s/action-%s.php", $MODE, $main_action);
+                               $GLOBALS['block_mode'] = true;
+                               $INC_BLOCK = sprintf("inc/modules/%s/action-%s.php", $MODE, $content['action']);
                                if (FILE_READABLE($INC_BLOCK)) {
                                        // Load include file
-                                       if ((!EXT_IS_ACTIVE($main_action)) || ($main_action == "online")) OUTPUT_HTML("<tr>
+                                       if ((!EXT_IS_ACTIVE($content['action'])) || ($content['action'] == "online")) OUTPUT_HTML("<tr>
 
   <td class=\"".$MODE."_menu_whats\">");
-                                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
+                                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$content['action']."/".$content['sub_what'].":".$GLOBALS['what']."*<br />\n";
                                        LOAD_INC($INC_BLOCK);
-                                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
-                                       if ((!EXT_IS_ACTIVE($main_action)) || ($main_action == "online")) OUTPUT_HTML("  </td>
+                                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$content['action']."/".$content['sub_what'].":".$GLOBALS['what']."*<br />\n";
+                                       if ((!EXT_IS_ACTIVE($content['action'])) || ($content['action'] == "online")) OUTPUT_HTML("  </td>
 </tr>");
                                }
-                               //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
+                               //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$content['action']."/".$content['sub_what'].":".$GLOBALS['what']."*<br />\n";
                        }
                        $main_cnt++;
-                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
-                       if (SQL_NUMROWS($result_main) > $main_cnt)      OUTPUT_HTML("<tr><td class=\"".$MODE."_menu_seperator\"></td></tr>");
+                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$content['action']."/".$content['sub_what'].":".$GLOBALS['what']."*<br />\n";
+                       if (SQL_NUMROWS($result_main) > $main_cnt) {
+                               OUTPUT_HTML("<tr><td class=\"".$MODE."_menu_seperator\"></td></tr>");
+                       } // END - if
                }
 
                // Free memory
                SQL_FREERESULT($result_main);
 
                // Close table
-               //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
+               //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$content['action']."/".$content['sub_what'].":".$GLOBALS['what']."*<br />\n";
                OUTPUT_HTML("</table>");
        }
 }
@@ -523,53 +545,49 @@ function IS_ADMIN ($admin="") {
 // Generates a list of "max receiveable emails per day"
 function ADD_MAX_RECEIVE_LIST ($MODE, $default = "", $return = false) {
        $OUT = "";
+       $result = false;
+
        switch ($MODE) {
-       case "guest":
-               // Guests (in the registration form) are not allowed to select 0 mails per day.
-               $result = SQL_QUERY("SELECT value, comment FROM `{!_MYSQL_PREFIX!}_max_receive` WHERE value > 0 ORDER BY value", __FUNCTION__, __LINE__);
-               if (SQL_NUMROWS($result) > 0) {
-                       $OUT = "";
-                       while (list($value, $comment) = SQL_FETCHROW($result)) {
-                               $OUT .= "      <option value=\"".$value."\"";
-                               if (REQUEST_POST('max_mails') == $value) $OUT .= " selected=\"selected\"";
-                               $OUT .= ">".$value." {--PER_DAY--}";
-                               if (!empty($comment)) $OUT .= " (".$comment.")";
-                               $OUT .= "</option>\n";
-                       }
-                       define('__MAX_RECEIVE_OPTIONS', $OUT);
+               case "guest":
+                       // Guests (in the registration form) are not allowed to select 0 mails per day.
+                       $result = SQL_QUERY("SELECT value, comment FROM `{!_MYSQL_PREFIX!}_max_receive` WHERE value > 0 ORDER BY value",
+                               __FUNCTION__, __LINE__);
+                       break;
 
-                       // Free memory
-                       SQL_FREERESULT($result);
-                       $OUT = LOAD_TEMPLATE("guest_receive_table", true);
-               } else {
-                       // Maybe the admin has to setup some maximum values?
-                       debug_report_bug("Nothing is being done here?");
-               }
-               break;
+               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",
+                               __FUNCTION__, __LINE__);
+                       break;
 
-       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", __FUNCTION__, __LINE__);
-               if (SQL_NUMROWS($result) > 0) {
-                       $OUT = "";
-                       while (list($value, $comment) = SQL_FETCHROW($result)) {
-                               $OUT .= "      <option value=\"".$value."\"";
-                               if ($default == $value) $OUT .= " selected=\"selected\"";
-                               $OUT .= ">".$value." {--PER_DAY--}";
-                               if (!empty($comment)) $OUT .= " (".$comment.")";
-                               $OUT .= "</option>\n";
-                       }
-                       define('__MAX_RECEIVE_OPTIONS', $OUT);
-                       SQL_FREERESULT($result);
-                       $OUT = LOAD_TEMPLATE("member_receive_table", true);
-               } else {
-                       // Maybe the admin has to setup some maximum values?
-                       $OUT = LOAD_TEMPLATE("admin_settings_saved", true, getMessage('NO_MAX_VALUES'));
+               default: // Invalid!
+                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $MODE));
+                       break;
+       }
+
+       // Some entries are found?
+       if (SQL_NUMROWS($result) > 0) {
+               $OUT = "";
+               while ($content = SQL_FETCHARRAY($result)) {
+                       $OUT .= "      <option value=\"".$content['value']."\"";
+                       if (REQUEST_POST('max_mails') == $content['value']) $OUT .= " selected=\"selected\"";
+                       $OUT .= ">".$content['value']." {--PER_DAY--}";
+                       if (!empty($content['comment'])) $OUT .= " (".$content['comment'].")";
+                       $OUT .= "</option>\n";
                }
-               break;
+               define('__MAX_RECEIVE_OPTIONS', $OUT);
+
+               // Load template
+               $OUT = LOAD_TEMPLATE($MODE."_receive_table", true);
+       } else {
+               // Maybe the admin has to setup some maximum values?
+               debug_report_bug("Nothing is being done here?");
        }
 
-       if ($return) {
+       // Free result
+       SQL_FREERESULT($result);
+
+       if ($return === true) {
                // Return generated HTML code
                return $OUT;
        } else {
@@ -611,10 +629,10 @@ function IS_MEMBER () {
        FIX_DELETED_COOKIES(array('userid', 'u_hash'));
 
        // Are cookies set?
-       if ((!empty($GLOBALS['userid'])) && (isSessionVariableSet('u_hash'))) {
+       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($GLOBALS['userid']), __FUNCTION__, __LINE__);
+                       array(getUserId()), __FUNCTION__, __LINE__);
                if (SQL_NUMROWS($result) == 1) {
                        // Load data from cookies
                        list($password, $status, $mod, $onl) = SQL_FETCHROW($result);
@@ -674,21 +692,21 @@ function VALIDATE_MENU_ACTION ($MODE, $act, $wht, $UPDATE=false) {
        $ret = false;
 
        // Look in all menus or only unlocked
-       $ADD = "";
-       if ((!IS_ADMIN()) && ($MODE != "admin")) $ADD = " AND `locked`='N'";
+       $add = "";
+       if ((!IS_ADMIN()) && ($MODE != "admin")) $add = " AND `locked`='N'";
 
        //* DEBUG: */ echo __LINE__.":".$MODE."/".$act."/".$wht."*<br />\n";
        if (($MODE != "admin") && ($UPDATE === true)) {
                // Update guest or member menu
-               $sql = SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$ADD." LIMIT 1",
+               $sql = SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s_menu` SET counter=counter+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
                        array($MODE, $act, $wht), __FUNCTION__, __LINE__, false);
        } elseif (($wht != "overview") && (!empty($wht))) {
                // 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",
+               $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($MODE, $act, $wht), __FUNCTION__, __LINE__, false);
        } else {
                // Admin login overview
-               $sql = SQL_QUERY_ESC("SELECT id, what FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE `action`='%s' AND (what='' OR `what` IS NULL)".$ADD." ORDER BY action DESC LIMIT 1",
+               $sql = SQL_QUERY_ESC("SELECT id, what FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE `action`='%s' AND (`what`='' OR `what` IS NULL)".$add." ORDER BY action DESC LIMIT 1",
                        array($MODE, $act), __FUNCTION__, __LINE__, false);
        }
 
@@ -743,7 +761,7 @@ function SEND_MODE_MAILS($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($GLOBALS['userid']), __FUNCTION__, __LINE__);
+               array(getUserId()), __FUNCTION__, __LINE__);
        if (SQL_NUMROWS($result_main) == 1) {
                // Load hash from database
                list($hashDB) = SQL_FETCHROW($result_main);
@@ -756,7 +774,7 @@ function SEND_MODE_MAILS($mod, $modes) {
                if (($hash == get_session('u_hash')) || (REQUEST_POST('pass1') == REQUEST_POST('pass2'))) {
                        // Load user's data
                        $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($GLOBALS['userid'], $hashDB), __FUNCTION__, __LINE__);
+                               array(getUserId(), $hashDB), __FUNCTION__, __LINE__);
                        if (SQL_NUMROWS($result) == 1) {
                                // Load the data
                                $DATA = SQL_FETCHROW($result);
@@ -800,7 +818,7 @@ function SEND_MODE_MAILS($mod, $modes) {
                                        } // END - if
 
                                        // Load template
-                                       $msg = LOAD_EMAIL_TEMPLATE("member_mydata_notify", $content, $GLOBALS['userid']);
+                                       $msg = LOAD_EMAIL_TEMPLATE("member_mydata_notify", $content, getUserId());
 
                                        if (getConfig('admin_notify') == "Y") {
                                                // The admin needs to be notified about a profile change
@@ -847,7 +865,7 @@ function SEND_MODE_MAILS($mod, $modes) {
        if (empty($content)) {
                if ((!empty($sub_adm)) && (!empty($msg_admin))) {
                        // Send admin mail
-                       SEND_ADMIN_NOTIFICATION($sub_adm, $msg_admin, $content, $GLOBALS['userid']);
+                       SEND_ADMIN_NOTIFICATION($sub_adm, $msg_admin, $content, getUserId());
                } elseif (getConfig('admin_notify') == "Y") {
                        // Cannot send mails to admin!
                        $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
@@ -865,7 +883,7 @@ function SEND_MODE_MAILS($mod, $modes) {
 function countModuleHit($mod) {
        if ($mod != "css") {
                // Do count all other modules but not accesses on CSS file css.php!
-               SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET clicks=clicks+1 WHERE module='%s' LIMIT 1",
+               SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET clicks=clicks+1 WHERE `module`='%s' LIMIT 1",
                        array($mod), __FUNCTION__, __LINE__);
        } // END - if
 }
@@ -925,7 +943,7 @@ function GET_ACTION ($MODE, &$wht) {
                if (isAdminRegistered()) {
                        // Redirect
                        // @TODO Why does this lead into an endless loop but we still need it???
-                       // Commented out LOAD_URL("admin.php");
+                       // @TODO Commented out LOAD_URL("admin.php");
                } // END - if
        }
 
@@ -999,31 +1017,33 @@ function GET_PAY_POINTS ($pid, $lookFor = "price") {
        return $ret;
 }
 
-// Remove a receiver's ID from $ARRAY and add a link for him to confirm
-function REMOVE_RECEIVER (&$ARRAY, $key, $uid, $pool_id, $stats_id="", $bonus=false) {
+// Remove a receiver's ID from $receivers and add a link for him to confirm
+function REMOVE_RECEIVER (&$receivers, $key, $uid, $pool_id, $stats_id="", $bonus=false) {
+       // Default is not removed
        $ret = "failed";
-       if ($uid > 0)
-       {
+
+       // Is the userid valid?
+       if ($uid > 0) {
                // Remove entry from array
-               unset($ARRAY[$key]);
+               unset($receivers[$key]);
 
                // Is there already a line for this user available?
-               if ($stats_id > 0)
-               {
+               if ($stats_id > 0) {
                        // 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"; }
+
+                       // 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",
-                        array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
-                       if (SQL_NUMROWS($result) == 0)
-                       {
-                               // No, so we add one!
+                               array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
+
+                       // Was it *not* found?
+                       if (SQL_NUMROWS($result) == 0) {
+                               // So we add one!
                                SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_links` (%s, userid, link_type) VALUES ('%s','%s','%s')",
-                                array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
+                                       array($rowName, $stats_id, bigintval($uid), $type), __FUNCTION__, __LINE__);
                                $ret = "done";
-                       }
-                        else
-                       {
+                       } else {
                                // Already found
                                $ret = "already";
                        }
@@ -1032,15 +1052,27 @@ function REMOVE_RECEIVER (&$ARRAY, $key, $uid, $pool_id, $stats_id="", $bonus=fa
                        SQL_FREERESULT($result);
                }
        }
+
        // Return status for sending routine
        return $ret;
 }
 
 // Calculate sum (default) or count records of given criteria
-function GET_TOTAL_DATA ($search, $tableName, $lookFor, $whereStatement="userid", $onlyRows=false, $add="") {
+function GET_TOTAL_DATA ($search, $tableName, $lookFor = "id", $whereStatement = "userid", $countRows = false, $add = "") {
        $ret = 0;
        //* DEBUG: */ echo $search."/".$tableName."/".$lookFor."/".$whereStatement."/".$add."<br />\n";
-       if (($onlyRows) || ($lookFor == "userid")) {
+       if ((empty($search)) && ($search != "0")) {
+               // Count or sum whole table?
+               if ($countRows === true) {
+                       // Count whole table
+                       $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{!_MYSQL_PREFIX!}_%s`".$add,
+                               array($lookFor, $tableName), __FUNCTION__, __LINE__);
+               } else {
+                       // Sum whole table
+                       $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{!_MYSQL_PREFIX!}_%s`".$add,
+                               array($lookFor, $tableName), __FUNCTION__, __LINE__);
+               }
+       } elseif (($countRows === true) || ($lookFor == "userid")) {
                // Count rows
                //* DEBUG: */ echo "COUNT!<br />\n";
                $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s'".$add,
@@ -1220,7 +1252,7 @@ function ADD_POINTS_REFSYSTEM ($subject, $uid, $points, $send_notify=false, $rid
 
                                // Prepare content
                                $content = array(
-                                       'text'   => REASON_DIRECT_PAYMENT,
+                                       'text'   => getMessage('REASON_DIRECT_PAYMENT'),
                                        'points' => TRANSLATE_COMMA($ref_points)
                                );
 
@@ -1228,7 +1260,7 @@ function ADD_POINTS_REFSYSTEM ($subject, $uid, $points, $send_notify=false, $rid
                                $msg = LOAD_EMAIL_TEMPLATE("add-points", $content, $uid);
 
                                // And sent it away
-                               SEND_EMAIL($email, SUBJECT_DIRECT_PAYMENT, $msg);
+                               SEND_EMAIL($email, getMessage('SUBJECT_DIRECT_PAYMENT'), $msg);
                                if (!REQUEST_ISSET_GET(('mid'))) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_POINTS_ADDED'));
                        }
 
@@ -1295,13 +1327,14 @@ function UPDATE_REF_COUNTER ($uid) {
        } // END - if
 }
 
-// OBSOLETE: Sends out mail to all administrators
+// Sends out mail to all administrators. This function is no longer obsolete
+// because we need it when there is no ext-admins installed
 function SEND_ADMIN_EMAILS ($subj, $msg) {
        // Load all admin email addresses
        $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id` ASC", __FUNCTION__, __LINE__);
-       while (list($email) = SQL_FETCHROW($result)) {
+       while ($content = SQL_FETCHARRAY($result)) {
                // Send the email out
-               SEND_EMAIL($email, $subj, $msg);
+               SEND_EMAIL($content['email'], $subj, $msg);
        } // END - if
 
        // Free result
@@ -1439,7 +1472,11 @@ function GET_ADMIN_DEFAULT_ACL ($aid) {
        // By default an invalid ACL value is returned
        $ret = "***";
 
-       if (isset($GLOBALS['cache_array']['admins']['def_acl'][$aid])) {
+       // Is sql_patches there and was it found in cache?
+       if (!EXT_IS_ACTIVE("sql_patches")) {
+               // Not found, which is bad, so we need to allow all
+               $ret =  "allow";
+       } elseif (isset($GLOBALS['cache_array']['admins']['def_acl'][$aid])) {
                // Use cache
                $ret = $GLOBALS['cache_array']['admins']['def_acl'][$aid];
 
@@ -1469,7 +1506,7 @@ function ADD_OPTION_LINES ($table, $id, $name, $default="", $special="", $where=
        $ret = "";
        if ($table == "/ARRAY/") {
                // Selection from array
-               if (is_array($id) && is_array($name) && sizeof($id) == sizeof($name)) {
+               if (is_array($id) && is_array($name) && count($id) == count($name)) {
                        // Both are arrays
                        foreach ($id as $idx => $value) {
                                $ret .= "<option value=\"".$value."\"";
@@ -1487,6 +1524,7 @@ function ADD_OPTION_LINES ($table, $id, $name, $default="", $special="", $where=
                        array($id, $ORDER, $table, $name), __FUNCTION__, __LINE__);
                if (SQL_NUMROWS($result) > 0) {
                        // Found data so add them as OPTION lines: $id is the value and $name is the "name" of the option
+                       // @TODO Try to rewrite this to $content = SQL_FETCHARRAY()
                        while (list($value, $title, $add) = SQL_FETCHROW($result)) {
                                if (empty($special)) $add = "";
                                $ret .= "<option value=\"".$value."\"";
@@ -1499,22 +1537,28 @@ function ADD_OPTION_LINES ($table, $id, $name, $default="", $special="", $where=
                        SQL_FREERESULT($result);
                } else {
                        // No data found
-                       $ret = "<option value=\"x\">".SELECT_NONE."</option>\n";
+                       $ret = "<option value=\"x\">{--SELECT_NONE--}</option>\n";
                }
        }
 
        // Return - hopefully - the requested data
        return $ret;
 }
-// Activate exchange (DEPERECATED???)
-function activateExchange() {
+// Activate exchange
+function activateExchange () {
+       // Is the extension 'user' there?
+       if (!EXT_IS_ACTIVE("user")) {
+               // Silently abort here
+               return false;
+       } // END - if
+
        // Check total amount of users
        $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true, " AND max_mails > 0");
 
        if ($totalUsers >= getConfig('activate_xchange')) {
                // Activate System
                SET_SQLS(array(
-                       "UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET `locked`='N', hidden='N', mem_only='Y' WHERE module='order' LIMIT 1",
+                       "UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET `locked`='N', hidden='N', mem_only='Y' WHERE `module`='order' LIMIT 1",
                        "UPDATE `{!_MYSQL_PREFIX!}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2",
                        "UPDATE `{!_MYSQL_PREFIX!}_config` SET activate_xchange='0' WHERE config=0 LIMIT 1"
                ));
@@ -1792,21 +1836,24 @@ function ADD_CATEGORY_OPTIONS ($mode) {
        $result = SQL_QUERY("SELECT id, cat FROM `{!_MYSQL_PREFIX!}_cats`".$whereStatement." ORDER BY `sort`", __FUNCTION__, __LINE__);
        if (SQL_NUMROWS($result) > 0) {
                // ... and begin loading stuff
-               while (list($id, $cat) = SQL_FETCHROW($result)) {
+               while ($content = SQL_FETCHARRAY($result)) {
                        // Transfer some data
-                       $CATS['id'][]   = $id;
-                       $CATS['name'][] = $cat;
+                       $CATS['id'][]   = $content['id'];
+                       $CATS['name'][] = $content['cat'];
 
                        // Check which users are in this category
                        $result_uids = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_cats` WHERE cat_id=%s",
-                        array(bigintval($id)), __FUNCTION__, __LINE__);
+                               array(bigintval($content['id'])), __FUNCTION__, __LINE__);
 
                        // Start adding all
                        $uid_cnt = 0;
+                       // @TODO Rewrite this to $content = SQL_FETCHARRAY()
                        while (list($ucat) = SQL_FETCHROW($result_uids)) {
                                $result_ver = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_data`
 WHERE userid=%s AND `status`='CONFIRMED' AND receive_mails > 0".PREPARE_SQL_HTML_HOLIDAY($mode)." LIMIT 1",
- array(bigintval($ucat)), __FUNCTION__, __LINE__);
+                                       array(bigintval($ucat)), __FUNCTION__, __LINE__);
+
+                               // Add user count
                                $uid_cnt += SQL_NUMROWS($result_ver);
 
                                // Free memory
@@ -1818,7 +1865,7 @@ WHERE userid=%s AND `status`='CONFIRMED' AND receive_mails > 0".PREPARE_SQL_HTML
 
                        // Add counter
                        $CATS['uids'][] = $uid_cnt;
-               }
+               } // END - while
 
                // Free memory
                SQL_FREERESULT($result);
@@ -1827,8 +1874,8 @@ WHERE userid=%s AND `status`='CONFIRMED' AND receive_mails > 0".PREPARE_SQL_HTML
                $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['uids'][$key]." ".USER_IN_CAT.")</option>\n";
-               }
+                       $OUT .= "      <option value=\"".$value."\">".$CATS['name'][$key]." (".$CATS['uids'][$key]." {--USER_IN_CAT--})</option>\n";
+               } // END - foreach
        } else {
                // No cateogries are defined yet
                $OUT = "<option class=\"member_failed\">{!MEMBER_NO_CATS!}</option>\n";
@@ -1907,6 +1954,7 @@ function GENERATE_RECEIVER_LIST ($cat, $receiver, $mode="") {
        $CAT_TABS     = "%s";
        $CAT_WHERE    = "";
        $receiverList = "";
+       $result       = false;
 
        // Secure data
        $cat      = bigintval($cat);
@@ -1934,19 +1982,19 @@ function GENERATE_RECEIVER_LIST ($cat, $receiver, $mode="") {
        if ((EXT_IS_ACTIVE("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.%s %s LIMIT %s",
-                array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__);
+                       array($cat, getConfig('order_select'), getConfig('order_mode'), $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.%s %s LIMIT %s",
-                array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__);
+                       array($cat, getConfig('order_select'), getConfig('order_mode'), $receiver), __FUNCTION__, __LINE__);
        }
 
        // Entries found?
        if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
                // Load all entries
-               while (list($REC) = SQL_FETCHROW($result)) {
+               while ($content = SQL_FETCHARRAY($result)) {
                        // Add receiver when not empty
-                       if (!empty($REC)) $receiverList .= $REC.";";
+                       if (!empty($content['userid'])) $receiverList .= $content['userid'].";";
                } // END - while
 
                // Free memory
@@ -1966,8 +2014,8 @@ function USER_STATS_GET_TIMESTAMP ($type, $data, $uid = 0) {
        $stamp = 0;
 
        // User id set?
-       if ((isset($GLOBALS['userid'])) && ($uid == 0)) {
-               $uid = $GLOBALS['userid'];
+       if ((isUserIdSet()) && ($uid == 0)) {
+               $uid = getUserId();
        } // END - if
 
        // Is the extension installed and updated?
@@ -2019,16 +2067,16 @@ function USER_STATS_INSERT_RECORD ($uid, $type, $data) {
 function GET_USER_REF_POINTS ($uid, $level) {
        //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
        // Default is no refs and no nickname
-       $ADD = "";
+       $add = "";
        $refs = array();
 
        // Do we have nickname extension installed?
        if (EXT_IS_ACTIVE("nickname")) {
-               $ADD = ", ud.nickname";
+               $add = ", ud.nickname";
        } // END - if
 
        // Get refs from database
-       $result = SQL_QUERY_ESC("SELECT ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$ADD."
+       $result = SQL_QUERY_ESC("SELECT ur.id, ur.refid, ud.status, ud.last_online, ud.mails_confirmed, ud.emails_received".$add."
 FROM `{!_MYSQL_PREFIX!}_user_refs` AS ur
 LEFT JOIN `{!_MYSQL_PREFIX!}_user_points` AS up
 ON ur.refid=up.userid AND ur.level=0
@@ -2093,6 +2141,7 @@ function REDUCED_RECIPIENT_RECEIVED_MAILS ($column, $id, $count) {
        // Are there entries?
        if (SQL_NUMROWS($result) > 0) {
                // Now load all userids for one big query!
+               // @TODO This can be somehow rewritten
                $UIDs = array();
                while (list($uid) = SQL_FETCHROW($result)) {
                        $UIDs[$uid] = $uid;
@@ -2122,6 +2171,11 @@ function SET_SQLS ($SQLs) {
        $GLOBALS['sqls'] = (array) $SQLs;
 }
 
+// Remover for SQLs array
+function UNSET_SQLS () {
+       unset($GLOBALS['sqls']);
+}
+
 // Getter for SQLs array
 function GET_SQLS () {
        return $GLOBALS['sqls'];
@@ -2129,6 +2183,7 @@ function GET_SQLS () {
 
 // Add an SQL to the list
 function ADD_SQL ($sql) {
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("sql=%s, count=%d", $sql, COUNT_SQLS()));
        $GLOBALS['sqls'][] = (string) $sql;
 }
 
@@ -2146,6 +2201,7 @@ function COUNT_SQLS () {
        if (IS_SQLS_INITIALIZED()) {
                // Then count it
                $count = count($GLOBALS['sqls']);
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("count=%d", $count));
        } // END - if
 
        // Return it
@@ -2156,8 +2212,7 @@ function COUNT_SQLS () {
 function IS_SQLS_VALID () {
        return (
                (IS_SQLS_INITIALIZED()) &&
-               (COUNT_SQLS() > 0) &&
-               (!empty($GLOBALS['sqls'][0]))
+               (COUNT_SQLS() > 0)
        );
 }