]> git.mxchange.org Git - mailer.git/blobdiff - inc/mysql-manager.php
Fixes for extension problems while installing/removing (still double-registration...
[mailer.git] / inc / mysql-manager.php
index 46154a41084d7508073acf6f18619de9225ccf75..7137be73f1506e172de78d16de92b78503ed3168 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                  *
  ************************************************************************/
 
 // Some security stuff...
-if (ereg(basename(__FILE__), $_SERVER['PHP_SELF']))
-{
-       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
+if (!defined('__SECURITY')) {
+       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
        require($INC);
 }
 
-//
-function ADD_MODULE_TITLE($mod)
-{
-       global $cacheArray, $_CONFIG;
-       $name = ""; $result = false;
-       // Load title
-       if (!isBooleanConstantAndTrue('mxchange_installed')) {
-               if ((GET_EXT_VERSION("cache") >= "0.1.2") && (isset($cacheArray['modules']['module'])) && (is_array($cacheArray['modules']['module'])) && (isset($cacheArray['modules']['module'][$mod]))) {
+// "Getter" for module title
+function getModuleTitle ($mod) {
+       // Init variables
+       $name = '';
+       $result = false;
+
+       // Is the script installed?
+       if (isInstalled()) {
+               // Check if cache is valid
+               if ((GET_EXT_VERSION('cache') >= '0.1.2') && (isset($GLOBALS['cache_array']['modules']['module'])) && (in_array($mod, $GLOBALS['cache_array']['modules']['module']))) {
                        // Load from cache
-                       $name = $cacheArray['modules']['title'][$mod];
+                       $name = $GLOBALS['cache_array']['modules']['title'][$mod];
 
                        // Update cache hits
-                       $_CONFIG['cache_hits']++;
-               } else {
+                       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", array($mod), __FILE__, __LINE__);
+                       $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);
                }
-       }
+       } // END - if
 
        // Trim name
        $name = trim($name);
@@ -65,25 +72,51 @@ function ADD_MODULE_TITLE($mod)
        // Still no luck or empty title?
        if (empty($name)) {
                // No name found
-               $name = LANG_UNKNOWN_MODULE." (".$mod.")";
+               $name = sprintf("%s (%s)", getMessage('LANG_UNKNOWN_MODULE'), $mod);
                if (SQL_NUMROWS($result) == 0) {
                        // Add module to database
-                       $dummy = CHECK_MODULE($mod);
-               }
-       }
+                       $dummy = checkModulePermissions($mod);
+               } // END - if
+       } // END - if
+
+       // Return name
        return $name;
 }
-// Check validity of a given module name (no file extension)
-function CHECK_MODULE($mod) {
-       // We need them now here...
-       global $cacheArray, $_CONFIG, $cacheInstance;
 
+// "Getter" for module description
+function getModuleDescription ($mode, $wht, $column = 'what') {
+       // Fix empty 'what'
+       if (empty($wht)) {
+               $wht = 'welcome';
+               if (getConfig('index_home') != '') $wht = getConfig('index_home');
+       } // END - if
+
+       // Default is not found
+       $ret = '??? (' . $wht . ')';
+
+       // Look for title
+       $result = SQL_QUERY_ESC("SELECT title FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE %s='%s' LIMIT 1",
+       array($mode, $column, $wht), __FUNCTION__, __LINE__);
+
+       // Is there an entry?
+       if (SQL_NUMROWS($result) == 1) {
+               // Fetch the title
+               list($ret) = SQL_FETCHROW($result);
+       } // END - if
+
+       // Free result
+       SQL_FREERESULT($result);
+       return $ret;
+}
+
+// Check validity of a given module name (no file extension)
+function checkModulePermissions ($mod) {
        // Filter module name (names with low chars and underlines are fine!)
-       $mod = preg_replace("/[^a-z_]/", "", $mod);
+       $mod = preg_replace("/[^a-z_]/", '', $mod);
 
        // Check for prefix is a extension...
        $modSplit = explode("_", $mod);
-       $extension = ""; $mod_chk = $mod;
+       $extension = ''; $mod_chk = $mod;
        //* DEBUG: */ echo __LINE__."*".count($modSplit)."*/".$mod."*<br />";
        if (count($modSplit) == 2) {
                // Okay, there is a seperator (_) in the name so is the first part a module?
@@ -91,188 +124,262 @@ function CHECK_MODULE($mod) {
                if (EXT_IS_ACTIVE($modSplit[0])) {
                        // The prefix is an extension's name, so let's set it
                        $extension = $modSplit[0]; $mod = $modSplit[1];
-               }
-       }
+               } // END - if
+       } // END - if
 
        // Major error in module registry is the default
-       $ret = "major";
+       $ret = 'major';
 
-       // Check if script is installed if not return a "done" to prevent some errors
-       if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing')) || (!isBooleanConstantAndTrue('admin_registered'))) return "done";
+       // Check if script is installed if not return a 'done' to prevent some errors
+       if ((!isInstalled()) || (isInstalling()) || (!isAdminRegistered())) {
+               // Not installed or no admin registered or in installation phase
+               return 'done';
+       } // END - if
+
+       // Init variables
+       $locked = 'Y';
+       $hidden = 'N';
+       $admin  = 'N';
+       $mem    = 'N';
+       $found  = false;
 
        // Check if cache is latest version
-       $locked = 'Y'; $hidden = 'N'; $admin = 'N'; $mem = 'N'; $found = false;
-       if ((GET_EXT_VERSION("cache") >= "0.1.2") && (isset($cacheArray['modules']['module'])) && (is_array($cacheArray['modules']['module']))) {
+       if (GET_EXT_VERSION('cache') >= '0.1.2') {
+               // Is the cache there?
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Using cache.');
+               if (!isset($GLOBALS['cache_array']['modules'])) {
+                       // This happens when a new extension is registered while ext-cache is installed
+                       $ret = 'cache_miss';
+               } // END - if
+
                // Is the module cached?
-               if (isset($cacheArray['modules']['locked'][$mod_chk])) {
+               if (isset($GLOBALS['cache_array']['modules']['locked'][$mod_chk])) {
                        // Check cache
-                       $locked = $cacheArray['modules']['locked'][$mod_chk];
-                       $hidden = $cacheArray['modules']['hidden'][$mod_chk];
-                       $admin  = $cacheArray['modules']['admin_only'][$mod_chk];
-                       $mem    = $cacheArray['modules']['mem_only'][$mod_chk];
+                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Cache found.');
+                       $locked = $GLOBALS['cache_array']['modules']['locked'][$mod_chk];
+                       $hidden = $GLOBALS['cache_array']['modules']['hidden'][$mod_chk];
+                       $admin  = $GLOBALS['cache_array']['modules']['admin_only'][$mod_chk];
+                       $mem    = $GLOBALS['cache_array']['modules']['mem_only'][$mod_chk];
 
                        // Update cache hits
-                       $_CONFIG['cache_hits']++;
+                       incrementConfigEntry('cache_hits');
                        $found = true;
                } else {
                        // No, then we have to update it!
-                       $ret = "cache_miss";
+                       $ret = 'cache_miss';
                }
-       } else {
+       } 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", array($mod_chk), __FILE__, __LINE__);
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Using database.');
+               $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
+                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Entry found.');
                        list($locked, $hidden, $admin, $mem) = SQL_FETCHROW($result);
-                       SQL_FREERESULT($result);
                        $found = true;
+               } elseif (isDebugModeEnabled()) {
+                       // Debug message only in debug-mode...
+                       DEBUG_LOG(__FUNCTION__, __LINE__, 'Module ' . $mod_chk . ' not found!');
                }
-       }
 
-       // Check returned values against current access permissions
-       //
-       //  Admin access            ----- Guest access -----           --- Guest   or   member? ---
-       if ((IS_ADMIN()) || (($locked == 'N') && ($admin == 'N') && (($mem == 'N') || (IS_LOGGED_IN())))) {
-               // If you are admin you are welcome for everything!
-               $ret = "done";
-       } elseif ($locked == 'Y') {
-               // Module is locked
-               $ret = "locked";
-       } elseif (($mem == 'Y') && (!IS_LOGGED_IN())) {
-               // You have to login first!
-               $ret = "mem_only";
-       } elseif (($admin == 'Y') && (!IS_ADMIN())) {
-               // Only the Admin is allowed to enter this module!
-               $ret = "admin_only";
+               // Free result
+               SQL_FREERESULT($result);
        }
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'ret=' . $ret);
+
+       // Is the module found?
+       if ($found === true) {
+               // Check returned values against current access permissions
+               //
+               //  Admin access            ----- Guest access -----           --- Guest   or   member? ---
+               if ((IS_ADMIN()) || (($locked == 'N') && ($admin == 'N') && (($mem == 'N') || (IS_MEMBER())))) {
+                       // If you are admin you are welcome for everything!
+                       $ret = 'done';
+               } elseif ($locked == 'Y') {
+                       // Module is locked
+                       $ret = 'locked';
+               } elseif (($mem == 'Y') && (!IS_MEMBER())) {
+                       // You have to login first!
+                       $ret = 'mem_only';
+               } elseif (($admin == 'Y') && (!IS_ADMIN())) {
+                       // Only the Admin is allowed to enter this module!
+                       $ret = 'admin_only';
+               } else {
+                       // @TODO Nothing helped???
+                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("ret=%s,locked=%s,admin=%s,mem=%s",
+                       $ret,
+                       $locked,
+                       $admin,
+                       $mem
+                       ));
+               }
+       } // END - if
 
        // Still no luck or not found?
-       if (($ret == "major") || ($ret == "cache_miss") || (!$found)) {
-               //         ----- Legacy module -----                      ---- Module in base folder  ----           --- Module with extension's name ---
-               if ((file_exists(PATH."inc/modules/".$mod.".php")) || (file_exists(PATH.$mod.".php")) || (file_exists(PATH.$extension."/".$mod.".php"))) {
+       if (($ret == 'cache_miss') || ($found === false)) {
+               //              ----- Legacy module -----                                               ---- Module in base folder  ----                       --- Module with extension's name ---
+               if ((isFileReadable(sprintf("%sinc/modules/%s.php", constant('PATH'), $mod))) || (isFileReadable(sprintf("%s%s.php", constant('PATH'), $mod))) || (isFileReadable(sprintf("%s%s/%s.php", constant('PATH'), $extension, $mod)))) {
                        // Data is missing so we add it
-                       if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
+                       if (GET_EXT_VERSION('sql_patches') >= '0.3.6') {
                                // Since 0.3.6 we have a has_menu column, this took me a half hour
                                // to find a loop here... *sigh*
-                               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_mod_reg
-(module, locked, hidden, mem_only, admin_only, has_menu) VALUES
-('%s', 'Y', 'N', 'N', 'N', 'N')", array($mod_chk), __FILE__, __LINE__);
+                               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_mod_reg`
+(`module`, `locked`, `hidden`, `mem_only`, `admin_only`, `has_menu`) VALUES
+('%s','Y','N','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
                        } else {
                                // Wrong/missing sql_patches!
-                               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_mod_reg
-(module, locked, hidden, mem_only, admin_only) VALUES
-('%s', 'Y', 'N', 'N', 'N')", array($mod_chk), __FILE__, __LINE__);
+                               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_mod_reg`
+(`module`, `locked`, `hidden`, `mem_only`, `admin_only`) VALUES
+('%s','Y','N','N','N')", array($mod_chk), __FUNCTION__, __LINE__);
                        }
 
                        // Everthing is fine?
-                       if (SQL_AFFECTEDROWS() == 0) {
+                       if (SQL_AFFECTEDROWS() < 1) {
                                // Something bad happend!
-                               return "major";
-                       }
+                               return 'major';
+                       } // END - if
 
                        // Destroy cache here
-                       if (GET_EXT_VERSION("cache") >= "0.1.2") {
-                               if ($cacheInstance->cache_file("mod_reg", true)) $cacheInstance->cache_destroy();
-                               unset($cacheArray['modules']);
-                       }
+                       // @TODO Rewrite this to a filter
+                       rebuildCacheFiles('modreg', 'modreg');
 
                        // And reload data
-                       $ret = CHECK_MODULE($mod_chk);
+                       $ret = checkModulePermissions($mod_chk);
                } else {
                        // Module not found we don't add it to the database
-                       $ret = "404";
+                       $ret = '404';
                }
+       } elseif (!$found) {
+               // Problem with module detected
+               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Problem in module %s detected. ret=%s, locked=%s, hidden=%s, mem=%s, admin=%s",
+                       $mod,
+                       $ret,
+                       $locked,
+                       $hidden,
+                       $mem,
+                       $admin
+               ));
        }
 
        // Return the value
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'ret=' . $ret);
        return $ret;
 }
+
 // Add menu description pending on given file name (without path!)
-function ADD_DESCR($ACC_LVL, $file, $return = false, $output = true)
-{
-       global $DEPTH, $_CONFIG;
-       $LINK_ADD = ""; $OUT = ""; $AND = "";
+function ADD_DESCR ($accessLevel, $FQFN, $return = false, $output = true) {
+       // Use only filename of the FQFN...
+       $file = basename($FQFN);
+
+       // Init variables
+       $LINK_ADD = '';
+       $OUT = '';
+       $AND = '';
+
        // First we have to do some analysis...
-       if (ereg("action-", $file)) {
+       if (substr($file, 0, 7) == 'action-') {
                // This is an action file!
-               $type = "action";
+               $type = 'action';
                $search = substr($file, 7);
-               switch ($ACC_LVL)
-               {
-               case "admin":
-                       $MOD_CHECK = "admin";
-                       break;
+               switch ($accessLevel) {
+                       case 'admin':
+                               $modCheck = 'admin';
+                               break;
 
-               case "sponsor":
-               case "guest":
-               case "member":
-                       $MOD_CHECK = $GLOBALS['module'];
-                       break;
+                       case 'sponsor':
+                       case 'guest':
+                       case 'member':
+                               $modCheck = getModule();
+                               break;
                }
-               $AND = " AND what=''";
-       } elseif (ereg("what-", $file)) {
+               $AND = " AND (`what`='' OR `what` IS NULL)";
+       } elseif (substr($file, 0, 5) == 'what-') {
                // This is an admin what file!
-               $type = "what";
+               $type = 'what';
                $search = substr($file, 5);
-               $AND = "";
-               switch ($ACC_LVL)
-               {
-               case "admin":
-                       $MOD_CHECK = "admin";
-                       break;
+               $AND = '';
+               switch ($accessLevel) {
+                       case 'admin':
+                               $modCheck = 'admin';
+                               break;
 
-               case "guest":
-               case "member":
-                       $MOD_CHECK = $GLOBALS['module'];
-                       if (!IS_ADMIN()) {
-                               $AND = " AND visible='Y' AND locked='N'";
-                       }
-                       break;
+                       case 'guest':
+                       case 'member':
+                               $modCheck = getModule();
+                               if (!IS_ADMIN()) {
+                                       $AND = " AND `visible`='Y' AND `locked`='N'";
+                               }
+                               break;
                }
+
                $dummy = substr($search, 0, -4);
-               $AND .= " AND action='".GET_ACTION($ACC_LVL, $dummy)."'";
-       } elseif (($ACC_LVL == "sponsor") || ($ACC_LVL == "engine")) {
+               $AND .= " AND `action`='".getModeAction($accessLevel, $dummy)."'";
+       } elseif (($accessLevel == 'sponsor') || ($accessLevel == "engine")) {
                // Sponsor / engine menu
-               $type = "what";
-               $search = $file;
-               $MOD_CHECK = $GLOBALS['module'];
-               $AND = "";
+               $type     = 'what';
+               $search   = $file;
+               $modCheck = getModule();
+               $AND      = '';
        } else {
                // Other
-               $type = "menu";
-               $search = $file;
-               $MOD_CHECK = $GLOBALS['module'];
-               $AND = "";
+               $type     = 'menu';
+               $search   = $file;
+               $modCheck = getModule();
+               $AND      = '';
        }
-       if ((!isset($DEPTH)) && (!$return)) {
-               $DEPTH = "0";
-               $prefix = "<DIV class=\"you_are_here\">".YOU_ARE_HERE."&nbsp;<STRONG><A class=\"you_are_here\" href=\"".URL."/modules.php?module=".$GLOBALS['module'].$LINK_ADD."\">Home</A></STRONG>";
+
+       // Begin the navigation line
+       if ((!isset($GLOBALS['nav_depth'])) && (!$return)) {
+               $GLOBALS['nav_depth'] = 0;
+               $prefix = "<div class=\"you_are_here\">{--YOU_ARE_HERE--}&nbsp;<strong><a class=\"you_are_here\" href=\"{!URL!}/modules.php?module=".getModule().$LINK_ADD."\">Home</a></strong>";
        } else {
-               if (!$return) $DEPTH++;
-               $prefix = "";
+               if (!$return) $GLOBALS['nav_depth']++;
+               $prefix = '';
        }
-       $prefix .= "&nbsp;-&gt;&nbsp;";
-       if (ereg(".php", $search)) {
-               $search = substr($search, 0, strpos($search, ".php"));
-       }
-       $result = SQL_QUERY_ESC("SELECT title FROM "._MYSQL_PREFIX."_%s_menu WHERE %s='%s' ".$AND." LIMIT 1",
-        array($ACC_LVL, $type, $search), __FILE__, __LINE__);
+
+       $prefix .= '&nbsp;-&gt;&nbsp;';
+
+       // We need to remove .php and the end
+       if (substr($search, -4, 4) == '.php') {
+               // Remove the .php
+               $search = substr($search, 0, -4);
+       } // END - i
+
+       // Get the title from menu
+       $result = SQL_QUERY_ESC("SELECT title FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE %s='%s' ".$AND." LIMIT 1",
+       array($accessLevel, $type, $search), __FUNCTION__, __LINE__);
+
+       // Menu found?
        if (SQL_NUMROWS($result) == 1) {
+               // Load title
                list($ret) = SQL_FETCHROW($result);
-               SQL_FREERESULT($result);
-               if ($return) {
+
+               // Shall we return it?
+               if ($return === true) {
                        // Return title
                        return $ret;
-               } elseif (((GET_EXT_VERSION("sql_patches") >= "0.2.3") && ($_CONFIG['youre_here'] == 'Y')) || ((IS_ADMIN()) && ($MOD_CHECK == "admin"))) {
+               } elseif (((GET_EXT_VERSION('sql_patches') >= '0.2.3') && (getConfig('youre_here') == 'Y')) || ((IS_ADMIN()) && ($modCheck == 'admin'))) {
                        // Output HTML code
-                       $OUT = $prefix."<STRONG><A class=\"you_are_here\" href=\"".URL."/modules.php?module=".$MOD_CHECK."&amp;".$type."=".$search.$LINK_ADD."\">".$ret."</A></STRONG>\n";
-                       //* DEBUG: */ echo __LINE__."*".$type."/".$GLOBALS['what']."*<br />\n";
-                       if (($type == "what") || (($type == "action") && (!isset($_GET['what'])) && ($GLOBALS['what'] != "welcome"))) {
-                               //* DEBUG: */ echo __LINE__."+".$type."+<br />\n";
-                               $OUT .= "</DIV><br />\n";
-                       }
+                       $OUT = $prefix . "<strong><a class=\"you_are_here\" href=\"{!URL!}/modules.php?module=" . $modCheck . '&amp;' . $type . '=' . $search.$LINK_ADD . "\">" . $ret . "</a></strong>\n";
+
+                       // Can we close the you-are-here navigation?
+                       //* DEBUG: */ echo __LINE__."*".$type.'/'.getWhat()."*<br />\n";
+                       if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
+                               //* DEBUG: */ echo __LINE__.'+'.$type."+<br />\n";
+                               // Add closing div and br-tag
+                               $OUT .= "</div><br />\n";
+                               $GLOBALS['nav_depth'] = '0';
+
+                               // Run the filter chain
+                               $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'content' => ""));
+                               $OUT .= $ret['content'];
+                       } // END - if
                }
-       }
+       } // END - if
+
+       // Free result
+       SQL_FREERESULT($result);
 
        // Return or output HTML code?
        if ($output) {
@@ -283,135 +390,253 @@ function ADD_DESCR($ACC_LVL, $file, $return = false, $output = true)
                return $OUT;
        }
 }
+
 //
-function ADD_MENU($MODE, $act, $wht) {
-       global $_CONFIG;
-       if (!VALIDATE_MENU_ACTION($MODE, $act, $wht, true)) return CODE_MENU_NOT_VALID;
-       $main_cnt = 0; $AND = ""; $main_action = ""; $sub_what = "";
-       if (!IS_ADMIN())
-       {
-               $AND = "AND visible='Y' AND locked='N'";
-       }
+function ADD_MENU ($mode, $act, $wht) {
+       // Init some variables
+       $main_cnt = 0;
+       $AND = '';
+       $main_action = '';
+       $sub_what = '';
+
+       // is the menu action valid?
+       if (!isMenuActionValid($mode, $act, $wht, true)) {
+               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='' ".$AND." ORDER BY sort",
-        array($MODE), __FILE__, __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\">");
+       $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.':'.getWhat()."*<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.':'.getWhat()."*<br />\n";
+                       // Init variables
+                       enableBlockMode(false);
+                       $act = $content['action'];
+
                        // Load menu header template
-                       $BLOCK_MODE = false; $act = $main_action;
-                       LOAD_TEMPLATE($MODE."_menu_title", false, $main_title);
+                       LOAD_TEMPLATE($mode . '_menu_title', false, $content);
+
+                       // 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__);
 
-                       $result_sub = SQL_QUERY_ESC("SELECT title, what FROM "._MYSQL_PREFIX."_%s_menu WHERE action='%s' AND what != '' ".$AND." ORDER BY sort",
-                        array($MODE, $main_action), __FILE__, __LINE__);
+                       // Get number of rows
                        $ctl = SQL_NUMROWS($result_sub);
-                       if ($ctl > 0)
-                       {
-                               $cnt=0;
-                               while (list($sub_title, $sub_what) = SQL_FETCHROW($result_sub))
-                               {
-                                       $content = "";
+
+                       // Do we have some entries?
+                       if ($ctl > 0) {
+                               // 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
+                                       $OUT = '';
 
                                        // Full file name for checking menu
-                                       //* DEBUG: */ echo __LINE__.":!!!!".$sub_what."!!!<br />\n";
-                                       $test_inc = sprintf("%sinc/modules/%s/what-%s.php", PATH, $MODE, $sub_what);
-                                       $test = (file_exists($test_inc) && is_readable($test_inc));
-                                       if ($test) {
-                                               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 (isIncludeReadable($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=".getModule()."&amp;what=".$content['sub_what']."\" target=\"_self\">";
                                        } else {
-                                               $content .= "<I>";
+                                               $OUT .= "<em>";
                                        }
 
                                        // Menu title
-                                       $content .= $_CONFIG['middot'].$sub_title;
+                                       $OUT .= getConfig('menu_blur_spacer') . $content['sub_title'];
 
-                                       if ($test) {
-                                               $content .= "</A>";
+                                       if (isIncludeReadable($INC)) {
+                                               $OUT .= "</a>";
                                        } else {
-                                               $content .= "</I>";
+                                               $OUT .= "</em>";
                                        }
 
-                                       if ((!empty($wht)) && (($wht == $sub_what))) {
-                                               $content .= "</STRONG>";
-                                       }
-                                       $wht = $sub_what; $cnt++;
+                                       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' => $OUT,
+                                               'what' => $content['sub_what']
+                                       );
+
+                                       // Add regular menu row or bottom row?
                                        if ($cnt < $ctl) {
-                                               LOAD_TEMPLATE($MODE."_menu_row", false, $content);
+                                               LOAD_TEMPLATE($mode."_menu_row", false, $content);
                                        } else {
-                                               LOAD_TEMPLATE($MODE."_menu_bottom", false, $content);
+                                               LOAD_TEMPLATE($mode."_menu_bottom", false, $content);
                                        }
                                }
                        } else {
                                // This is a menu block... ;-)
-                               $BLOCK_MODE = true;
-                               $INC_BLOCK = sprintf(PATH."inc/modules/%s/action-%s.php", $MODE, $main_action);
-                               if ((file_exists($INC_BLOCK)) && (is_readable($INC_BLOCK))) {
+                               enableBlockMode();
+
+                               // Load menu block
+                               $INC_BLOCK = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
+                               if (isFileReadable($INC_BLOCK)) {
                                        // Load include file
-                                       if ((!EXT_IS_ACTIVE($main_action)) || ($main_action == "online")) OUTPUT_HTML("<TR>
-  <TD class=\"".$MODE."_menu_whats\">");
-                                       //* DEBUG: */ echo __LINE__."/".$main_cnt."/".$main_action."/".$sub_what.":".$GLOBALS['what']."*<br />\n";
-                                       include ($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>
-</TR>");
+                                       if ((!EXT_IS_ACTIVE($content['action'])) || ($content['action'] == 'online')) OUTPUT_HTML("<tr>
+
+  <td class=\"".$mode."_menu_whats\">");
+                                       //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />\n";
+                                       loadInclude($INC_BLOCK);
+                                       //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<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'].':'.getWhat()."*<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'].':'.getWhat()."*<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";
-               OUTPUT_HTML("</TABLE>");
+               //* DEBUG: */ echo __LINE__.'/'.$main_cnt.'/'.$content['action'].'/'.$content['sub_what'].':'.getWhat()."*<br />\n";
+               OUTPUT_HTML("</table>");
+       }
+}
+
+// Checks wether the current user is a member
+function IS_MEMBER () {
+       // By default no member
+       $ret = false;
+
+       // Fix missing 'last' array, damn stupid code :(((
+       // @TODO Try to rewrite this to one or more functions
+       if ((!isset($GLOBALS['last'])) || (!is_array($GLOBALS['last']))) $GLOBALS['last'] = array();
+
+       // is the cache entry there?
+       if (isset($GLOBALS['is_member'])) {
+               // Then return it
+               return $GLOBALS['is_member'];
+       } // END - if
+
+       // Init global 'status'
+       $GLOBALS['status'] = false;
+
+       // Fix "deleted" cookies first
+       fixDeletedCookies(array('userid', 'u_hash'));
+
+       // 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);
+
+                       // Validate password by created the difference of it and the secret key
+                       $valPass = generatePassString($password);
+
+                       // Transfer last module and online time
+                       if ((!empty($mod)) && (empty($GLOBALS['last']['module']))) {
+                               // @TODO Try to rewrite this to one or more functions
+                               $GLOBALS['last']['module'] = $mod;
+                               $GLOBALS['last']['online'] = $onl;
+                       } // END - if
+
+                       // So did we now have valid data and an unlocked user?
+                       if (($GLOBALS['status'] == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
+                               // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
+                               $ret = true;
+                       } else {
+                               // Maybe got locked etc.
+                               //* DEBUG: */ echo __LINE__."!!!<br />";
+                               destroyUserSession();
+                       }
+               } else {
+                       // Cookie data is invalid!
+                       //* DEBUG: */ echo __LINE__."***<br />";
+                       destroyUserSession();
+               }
+
+               // Free memory
+               SQL_FREERESULT($result);
+       } else {
+               // Cookie data is invalid!
+               //* DEBUG: */ echo __LINE__."///<br />";
+               destroyUserSession();
        }
+
+       // Cache status
+       $GLOBALS['is_member'] = $ret;
+
+       // Return status
+       return $ret;
 }
+
 // This patched function will reduce many SELECT queries for the specified or current admin login
-function IS_ADMIN($admin="")
-{
-       global $cacheArray, $_CONFIG;
-       $ret = false; $passCookie = ""; $valPass = "";
+function IS_ADMIN ($admin = '') {
+       // Init variables
+       $ret = false; $passCookie = ''; $valPass = '';
        //* DEBUG: */ echo __LINE__."ADMIN:".$admin."<br />";
 
        // If admin login is not given take current from cookies...
        if ((empty($admin)) && (isSessionVariableSet('admin_login')) && (isSessionVariableSet('admin_md5'))) {
-               $admin = SQL_ESCAPE(get_session('admin_login')); $passCookie = get_session('admin_md5');
+               // Get admin login and password from session/cookies
+               $admin = getSession('admin_login');
+               $passCookie = getSession('admin_md5');
        }
-       //* DEBUG: */ echo __LINE__."ADMIN:".$admin."/".$passCookie."<br />";
+       //* DEBUG: */ echo __LINE__."ADMIN:".$admin.'/'.$passCookie."<br />";
 
        // Search in array for entry
-       if ((!empty($passCookie)) && (isset($cacheArray['admins']['password'][$admin])) && (!empty($admin))) {
-               // Count cache hits
-               $_CONFIG['cache_hits']++;
-
+       if (isset($GLOBALS['cache_array']['admin_hash'])) {
+               // Use cached string
+               $valPass = $GLOBALS['cache_array']['admin_hash'];
+       } elseif ((!empty($passCookie)) && (isset($GLOBALS['cache_array']['admins']['password'][$admin])) && (!empty($admin))) {
                // Login data is valid or not?
-               $valPass = generatePassString($cacheArray['admins']['password'][$admin]);
-       } elseif (!empty($admin)) {
+               $valPass = generatePassString($GLOBALS['cache_array']['admins']['password'][$admin]);
+
+               // Cache it away
+               $GLOBALS['cache_array']['admin_hash'] = $valPass;
+
+               // Count cache hits
+               incrementConfigEntry('cache_hits');
+       } elseif ((!empty($admin)) && ((!EXT_IS_ACTIVE('cache'))) || (!isset($GLOBALS['cache_array']['admins']['password'][$admin]))) {
                // Search for admin
-               $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
-                array($admin), __FILE__, __LINE__);
+               $result = SQL_QUERY_ESC("SELECT HIGH_PRIORITY password FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
+               array($admin), __FUNCTION__, __LINE__);
 
                // Is he admin?
-               $passDB = "";
+               $passDB = '';
                if (SQL_NUMROWS($result) == 1) {
                        // Admin login was found so let's load password from DB
                        list($passDB) = SQL_FETCHROW($result);
+
+                       // Temporary cache it
+                       $GLOBALS['cache_array']['admins']['password'][$admin] = $passDB;
+
+                       // Generate password hash
                        $valPass = generatePassString($passDB);
-               }
+               } // END - if
 
                // Free memory
                SQL_FREERESULT($result);
@@ -419,312 +644,158 @@ function IS_ADMIN($admin="")
 
        if (!empty($valPass)) {
                // Check if password is valid
-               //* DEBUG: */ echo __LINE__."*".$valPass."/".$passCookie)."*<br>";
-               $ret = (($valPass == $passCookie) || (($valPass == "*FAILED*") && (!EXT_IS_ACTIVE("cache"))));
-       }
+               //* DEBUG: */ print __FUNCTION__."*".$valPass.'/'.$passCookie."*<br />\n";
+               $ret = (($valPass == $passCookie) || ((strlen($valPass) == 32) && ($valPass == md5($passCookie))) || (($valPass == "*FAILED*") && (!EXT_IS_ACTIVE('cache'))));
+       } // END - if
 
        // Return result of comparision
-       //* DEBUG: */ if (!$ret) echo __LINE__."OK!<br>";
+       //* DEBUG: */ if (!$ret) echo __LINE__."OK!<br />";
        return $ret;
 }
-//
-function ADD_MAX_RECEIVE_LIST($MODE, $default="", $return=false)
-{
-       global $_POST;
-       $OUT = "";
-       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", __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) > 0)
-               {
-                       $OUT = "";
-                       while (list($value, $comment) = SQL_FETCHROW($result))
-                       {
-                               $OUT .= "      <OPTION value=\"".$value."\"";
-                               if ($_POST['max_mails'] == $value) $OUT .= " selected=\"selected\"";
-                               $OUT .= ">".$value." ".PER_DAY;
-                               if (!empty($comment)) $OUT .= " (".$comment.")";
-                               $OUT .= "</OPTION>\n";
-                       }
-                       define('__MAX_RECEIVE_OPTIONS', $OUT);
 
-                       // Free memory
-                       SQL_FREERESULT($result);
-                       $OUT = LOAD_TEMPLATE("guest_receive_table", true);
-               }
-                else
-               {
-                       // Maybe the admin has to setup some maximum values?
-               }
-               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", __FILE__, __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, NO_MAX_VALUES);
+// Generates a list of "max receiveable emails per day"
+function addMaxReceiveList ($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__);
+                       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;
+
+               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
-       {
+       } else {
                // Output directly (default)
                OUTPUT_HTML($OUT);
        }
 }
-//
-function SEARCH_EMAIL_USERTAB($email)
-{
-       $ret = false;
-       $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_user_data WHERE email LIKE '{PER}%s{PER}' LIMIT 1", array($email), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 1) $ret = true;
-       SQL_FREERESULT($result);
-       return $ret;
-}
-//
-function WHAT_IS_VALID($act, $wht, $type="guest")
-{
-       if (IS_ADMIN())
-       {
-               // Everything is valid to the admin :-)
-               return true;
-       }
-        else
-       {
-               $ret = false;
-               $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_%s_menu WHERE action='%s' AND what='%s' AND locked='N' LIMIT 1", array($type, $act, $wht), __FILE__, __LINE__);
-               // Is "what" valid?
-               if (SQL_NUMROWS($result) == 1) $ret = true;
-               SQL_FREERESULT($result);
-               return $ret;
-       }
-}
-//
-function IS_LOGGED_IN()
-{
-       global $status, $LAST;
-       if (!is_array($LAST)) $LAST = array();
-       $ret = false;
-
-       // Fix "deleted" cookies first
-       FIX_DELETED_COOKIES(array('userid', 'u_hash', 'lifetime'));
 
-       // Are cookies set?
-       if ((!empty($GLOBALS['userid'])) && (isSessionVariableSet('u_hash')) && (isSessionVariableSet('lifetime')) && (defined('COOKIE_PATH')))
-       {
-               // 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=%d LIMIT 1",
-                array($GLOBALS['userid']), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
-                       // Load data from cookies
-                       list($password, $status, $mod, $onl) = SQL_FETCHROW($result);
-
-                       // Validate password by created the difference of it and the secret key
-                       $valPass = generatePassString($password);
-
-                       // Transfer last module and online time
-                       if ((!empty($mod)) && (empty($LAST['module']))) { $LAST['module'] = $mod; $LAST['online'] = $onl; }
-
-                       // So did we now have valid data and an unlocked user?
-                       //* DEBUG: */ echo $valPass."<br>".get_session('u_hash')."<br>";
-                       if (($status == "CONFIRMED") && ($valPass == get_session('u_hash'))) {
-                               // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
-                               $ret = true;
-                       } else {
-                               // Maybe got locked etc.
-                               //* DEBUG: */ echo __LINE__."!!!<br>";
-                               set_session("userid", "");
-                               set_session("u_hash", "");
-                               set_session("lifetime", "");
-
-                               // Remove array elements to prevent errors
-                               unset($GLOBALS['userid']);
-                       }
-               } else {
-                       // Cookie data is invalid!
-                       //* DEBUG: */ echo __LINE__."***<br>";
-                       set_session("userid", "");
-                       set_session("u_hash", "");
-                       set_session("lifetime", "");
+// Checks wether the given email address is used.
+function isEmailTaken ($email) {
+       // Query the database
+       $result = SQL_QUERY_ESC("SELECT userid FROM `{!_MYSQL_PREFIX!}_user_data` WHERE email LIKE '{PER}%s{PER}' LIMIT 1",
+       array($email), __FUNCTION__, __LINE__);
 
-                       // Remove array elements to prevent errors
-                       unset($GLOBALS['userid']);
-               }
+       // Is the email there?
+       $ret = (SQL_NUMROWS($result) == 1);
 
-               // Free memory
-               SQL_FREERESULT($result);
-       }
-        else
-       {
-               // Cookie data is invalid!
-               //* DEBUG: */ echo __LINE__."///<br>";
-               set_session("userid", "");
-               set_session("u_hash", "");
-               set_session("lifetime", "");
+       // Free the result
+       SQL_FREERESULT($result);
 
-               // Remove array elements to prevent errors
-               unset($GLOBALS['userid']);
-       }
+       // Return result
        return $ret;
 }
-//
-function UPDATE_LOGIN_DATA ($UPDATE=true) {
-       global $LAST;
-       if (!is_array($LAST)) $LAST = array();
-
-       // Are the required cookies set?
-       if ((!isset($GLOBALS['userid'])) || (!isSessionVariableSet('u_hash')) || (!isSessionVariableSet('lifetime'))) {
-               // Nope, then return here to caller function
-               return false;
-       } else {
-               // Secure user ID
-               $GLOBALS['userid'] = bigintval(get_session('userid'));
-       }
 
-       // Extract last online time (life) and how long is auto-login valid (time)
-       $newl = time() + bigintval(get_session('lifetime'));
+// Validate the given menu action
+function isMenuActionValid ($mode, $act, $wht, $UPDATE=false) {
+       // Is the cache entry there and we shall not update?
+       if ((isset($GLOBALS['cache_array']['action_valid'][$mode][$act][$wht])) && ($UPDATE === false)) {
+               // Count cache hit
+               incrementConfigEntry('cache_hits');
 
-       // Recheck if logged in
-       if (!IS_LOGGED_IN()) return false;
-
-       // Load last module and last online time
-       $result = SQL_QUERY_ESC("SELECT last_module, last_online FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1", array($GLOBALS['userid']), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 1) {
-               // Load last module and online time
-               list($mod, $onl) = SQL_FETCHROW($result);
-               SQL_FREERESULT($result);
+               // Then use this cache
+               return $GLOBALS['cache_array']['action_valid'][$mode][$act][$wht];
+       } // END - if
 
-               // Maybe first login time?
-               if (empty($mod)) $mod = "login";
+       // By default nothing is valid
+       $ret = false;
 
-               if (set_session("userid", $GLOBALS['userid'], $newl, COOKIE_PATH) && set_session("u_hash", SQL_ESCAPE(get_session('u_hash')), $newl, COOKIE_PATH) && set_session("lifetime", bigintval(get_session('lifetime')), $newl, COOKIE_PATH)) {
-                       // This will be displayed on welcome page! :-)
-                       if (empty($LAST['module'])) {
-                               $LAST['module'] = $mod; $LAST['online'] = $onl;
-                       }
-                       if (empty($GLOBALS['what'])) {
-                               $GLOBALS['what'] = "welcome";
-                       }
+       // Look in all menus or only unlocked
+       $add = '';
+       if ((!IS_ADMIN()) && ($mode != 'admin')) $add = " AND `locked`='N'";
 
-                       // Update last module / online time
-                       $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_data SET last_module='%s', last_online=UNIX_TIMESTAMP() WHERE userid=%d LIMIT 1",
-                        array($GLOBALS['what'], $GLOBALS['userid']), __FILE__, __LINE__);
-               }
-       }  else {
-               // Destroy session, we cannot update!
-               set_session("userid", "");
-               set_session("u_hash", "");
-               set_session("lifetime", "");
-       }
-}
-//
-function VALIDATE_MENU_ACTION ($MODE, $act, $wht, $UPDATE=false)
-{
-       global $link;
-       $ret = false;
-       $ADD = "";
-       if ((!IS_ADMIN()) && ($MODE != "admin")) $ADD = " AND locked='N'";
-       //* DEBUG: */ echo __LINE__.":".$MODE."/".$act."/".$wht."*<br />\n";
-       if (($MODE != "admin") && ($UPDATE))
-       {
+       //* 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",
-                array($MODE, $act, $wht), __FILE__, __LINE__, false);
-       }
-        elseif ($wht != "overview")
-       {
+               $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'".$ADD." ORDER BY action DESC LIMIT 1",
-                array($MODE, $act), __FILE__, __LINE__, false);
-       }
-        else
-       {
+               $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=''".$ADD." ORDER BY action DESC LIMIT 1",
-                array($MODE, $act), __FILE__, __LINE__, false);
+               $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);
        }
 
        // Run SQL command
-       $result = SQL_QUERY($SQL, __FILE__, __LINE__);
-       if ($UPDATE)
-       {
-               if (SQL_AFFECTEDROWS($link, __FILE__, __LINE__) == 1) $ret = true;
-               //* DEBUG: */ debug_print_backtrace();
-       }
-        else
-       {
-               if (SQL_NUMROWS($result) == 1) {
-                       list($id, $wht2) = SQL_FETCHROW($result);
-                       //* DEBUG: */ echo __LINE__."+".$SQL."+<br />\n";
-                       //* DEBUG: */ echo __LINE__."*".$id."/".$wht."/".$wht2."*<br />\n";
-                       $ret = true;
-               }
+       $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
+       if ($UPDATE === true) {
+               // Check updated/affected rows
+               $ret = (SQL_AFFECTEDROWS() == 1);
+       } else {
+               // Check found rows
+               $ret = (SQL_NUMROWS($result) == 1);
        }
 
        // Free memory
        SQL_FREERESULT($result);
-       //* DEBUG: */ var_dump($ret);
-       return $ret;
-}
-//
-function GET_MOD_DESCR($MODE, $wht)
-{
-       if (empty($wht)) $wht = "welcome";
-       $ret = "??? (".$wht.")";
-       $result = SQL_QUERY_ESC("SELECT title FROM "._MYSQL_PREFIX."_%s_menu WHERE what='%s' LIMIT 1", array($MODE, $wht), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 1)
-       {
-               list($ret) = SQL_FETCHROW($result);
-               SQL_FREERESULT($result);
-       }
+
+       // Set cache entry
+       $GLOBALS['cache_array']['action_valid'][$mode][$act][$wht] = $ret;
+
+       // Return result
        return $ret;
 }
+
 //
-function SEND_MODE_MAILS($mod, $modes)
-{
-       global $_CONFIG, $DATA;
+function sendModeMails ($mod, $modes) {
+       global $DATA;
 
        // Load hash
-       $result_main = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d AND status='CONFIRMED' LIMIT 1",
-        array($GLOBALS['userid']), __FILE__, __LINE__);
+       $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);
 
                // Extract salt from cookie
-               $salt = substr(get_session('u_hash'), 0, -40);
+               $salt = substr(getSession('u_hash'), 0, -40);
 
                // Now let's compare passwords
                $hash = generatePassString($hashDB);
-               if (($hash == get_session('u_hash')) || ($_POST['pass1'] == $_POST['pass2'])) {
+               if (($hash == getSession('u_hash')) || (REQUEST_POST('pass1') == REQUEST_POST('pass2'))) {
                        // Load user's data
-                       $result = SQL_QUERY_ESC("SELECT sex, surname, family, street_nr, country, zip, city, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d AND password='%s' LIMIT 1",
-                        array($GLOBALS['userid'], $hashDB), __FILE__, __LINE__);
+                       $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__);
                        if (SQL_NUMROWS($result) == 1) {
                                // Load the data
                                $DATA = SQL_FETCHROW($result);
@@ -732,865 +803,1476 @@ function SEND_MODE_MAILS($mod, $modes)
                                // Free result
                                SQL_FREERESULT($result);
 
-                               // Translate salutation
-                               $DATA[0] = TRANSLATE_SEX($DATA[0]);
+                               // Translate gender
+                               $DATA[0] = translateGender($DATA[0]);
 
                                // Clear/init the content variable
-                               $content = "";
-                               $DATA['info'] = "";
+                               $content = '';
+                               $DATA['info'] = '';
 
                                switch ($mod)
                                {
-                               case "mydata":
-                                       foreach ($modes as $mode) {
-                                               switch ($mode)
-                                               {
-                                               case "normal": break; // Do not add any special lines
-
-                                               case "email": // Email was changed!
-                                                       $content = MEMBER_CHANGED_EMAIL.": ".$_POST['old_addy']."\n";
-                                                       break;
-
-                                               case "pass": // Password was changed
-                                                       $content = MEMBER_CHANGED_PASS."\n";
-                                                       break;
-
-                                               default:
-                                                       $content = MEMBER_UNKNOWN_MODE.": ".$mode."\n\n";
-                                                       break;
+                                       case 'mydata':
+                                               foreach ($modes as $mode) {
+                                                       switch ($mode)
+                                                       {
+                                                               case 'normal': break; // Do not add any special lines
+
+                                                               case 'email': // Email was changed!
+                                                                       $content = getMessage('MEMBER_CHANGED_EMAIL').": ".REQUEST_POST('old_addy')."\n";
+                                                                       break;
+
+                                                               case 'pass': // Password was changed
+                                                                       $content = getMessage('MEMBER_CHANGED_PASS')."\n";
+                                                                       break;
+
+                                                               default:
+                                                                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
+                                                                       $content = getMessage('MEMBER_UNKNOWN_MODE').": ".$mode."\n\n";
+                                                                       break;
+                                                       } // END - switch
+                                               } // END - if
+
+                                               if (EXT_IS_ACTIVE('country')) {
+                                                       // Replace code with description
+                                                       $DATA[4] = COUNTRY_GENERATE_INFO(REQUEST_POST('country_code'));
+                                               } // END - if
+
+                                               // Merge content with data from POST
+                                               $content = merge_array($content, REQUEST_POST_ARRAY());
+
+                                               // Load template
+                                               $msg = LOAD_EMAIL_TEMPLATE('member_mydata_notify', $content, getUserId());
+
+                                               if (getConfig('admin_notify') == 'Y') {
+                                                       // The admin needs to be notified about a profile change
+                                                       $msg_admin = 'admin_mydata_notify';
+                                                       $sub_adm   = getMessage('ADMIN_CHANGED_DATA');
+                                               } else {
+                                                       // No mail to admin
+                                                       $msg_admin = '';
+                                                       $sub_adm   = '';
                                                }
-                                       } // END - if
-
-                                       if (EXT_IS_ACTIVE("country")) {
-                                               // Replace code with description
-                                               $DATA[4] = COUNTRY_GENERATE_INFO($_POST['country_code']);
-                                       }
-
-                                       // Load template
-                                       $msg = LOAD_EMAIL_TEMPLATE("member_mydata_notify", $content, $GLOBALS['userid']);
-
-                                       if ($_CONFIG['admin_notify'] == 'Y') {
-                                               // The admin needs to be notified about a profile change
-                                               $msg_admin = "admin_mydata_notify";
-                                               $sub_adm = ADMIN_CHANGED_DATA;
-                                       } else {
-                                               // No mail to admin
-                                               $msg_admin = "";
-                                               $sub_adm = "";
-                                       }
 
-                                       // Set subject lines
-                                       $sub_mem = MEMBER_CHANGED_DATA;
+                                               // Set subject lines
+                                               $sub_mem = getMessage('MEMBER_CHANGED_DATA');
 
-                                       // Output success message
-                                       $content = "<STRONG><SPAN class=\"member_done\">".MYDATA_MAIL_SENT."</SPAN></STRONG>";
-                                       break;
+                                               // Output success message
+                                               $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
+                                               break;
 
-                               default:
-                                       $content = "<STRONG><SPAN class=\"member_failed\">".UNKNOWN_MODULE."</SPAN></STRONG>";
-                                       break;
-                               }
+                                       default: // Unsupported module!
+                                               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
+                                               $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
+                                               break;
+                               } // END - switch
                        } else {
                                // Could not load profile data
-                               $content = "<STRONG><SPAN class=\"member_failed\">".MEMBER_CANNOT_LOAD_PROFILE."</SPAN></STRONG>";
+                               $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
                        }
                } else {
                        // Passwords mismatch
-                       $content = "<STRONG><SPAN class=\"member_failed\">".MEMBER_PASSWORD_ERROR."</SPAN></STRONG>";
+                       $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
                }
        } else {
                // Could not load profile
-               $content = "<STRONG><SPAN class=\"member_failed\">".MEMBER_CANNOT_LOAD_PROFILE."</SPAN></STRONG>";
+               $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
        }
 
        // Send email to user if required
        if ((!empty($sub_mem)) && (!empty($msg))) {
                // Send member mail
-               SEND_EMAIL($DATA[7], $sub_mem, $msg);
-       }
+               sendEmail($DATA[7], $sub_mem, $msg);
+       } // END - if
 
        // Send only if no other error has occured
        if (empty($content)) {
                if ((!empty($sub_adm)) && (!empty($msg_admin))) {
                        // Send admin mail
-                       if (GET_EXT_VERSION("admins") >= "0.4.1") {
-                               SEND_ADMIN_EMAILS_PRO($sub_adm, $msg_admin, $content, $GLOBALS['userid']);
-                       } else {
-                               SEND_ADMIN_EMAILS($sub_adm, LOAD_EMAIL_TEMPLATE($msg_admin, $content, $GLOBALS['userid']));
-                       }
-               } elseif ($_CONFIG['admin_notify'] == 'Y') {
+                       sendAdminNotification($sub_adm, $msg_admin, $content, getUserId());
+               } elseif (getConfig('admin_notify') == 'Y') {
                        // Cannot send mails to admin!
-                       $content = CANNOT_SEND_ADMIN_MAILS;
+                       $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
                } else {
                        // No mail to admin
-                       $content = "<STRONG><SPAN class=\"member_done\">".MYDATA_MAIL_SENT."</SPAN></STRONG>";
+                       $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
                }
-       }
+       } // END - if
 
        // Load template
-       LOAD_TEMPLATE("admin_settings_saved", false, $content);
+       LOAD_TEMPLATE('admin_settings_saved', false, $content);
 }
+
 // Update module counter
-function COUNT_MODULE($mod)
-{
-       if ($mod != "css")
-       {
+function countModuleHit($mod) {
+       if ($mod != "css") {
                // Do count all other modules but not accesses on CSS file css.php!
-               $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_mod_reg SET clicks=clicks+1 WHERE module='%s' LIMIT 1",
-                array($mod), __FILE__, __LINE__);
-       }
+               SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_mod_reg` SET clicks=clicks+1 WHERE `module`='%s' LIMIT 1",
+               array($mod), __FUNCTION__, __LINE__);
+       } // END - if
 }
+
 // Get action value from mode (admin/guest/member) and what-value
-function GET_ACTION ($MODE, &$wht)
-{
-       global $ret; $ret = "";
-       //* DEBUG: */ echo __LINE__."=".$MODE."/".$wht."/".$GLOBALS['action']."=<br>";
-       if ((empty($wht)) && ($MODE != "admin"))
-       {
-               $wht = "welcome";
-       }
-       if ($MODE == "admin")
-       {
+function getModeAction ($mode, $wht) {
+       // Init status
+       $ret = '';
+
+       //* DEBUG: */ echo __LINE__.'='.$mode.'/'.$wht.'/'.getAction()."=<br />";
+       if ((empty($wht)) && ($mode != 'admin')) {
+               $wht = 'welcome';
+               if (getConfig('index_home') != '') $wht = getConfig('index_home');
+       } // END - if
+
+       if ($mode == 'admin') {
                // Action value for admin area
-               if (!empty($GLOBALS['action']))
-               {
+               if (REQUEST_ISSET_GET('action')) {
+                       // Use from request!
+                       return REQUEST_GET('action');
+               } elseif (isActionSet()) {
                        // Get it directly from URL
-                       return $GLOBALS['action'];
-               }
-                elseif (($wht == "overview") || (empty($GLOBALS['what'])))
-               {
+                       return getAction();
+               } elseif (($wht == 'overview') || (!isWhatSet())) {
                        // Default value for admin area
-                       $ret = "login";
+                       $ret = 'login';
                }
+       } elseif (isActionSet()) {
+               // Get it directly from URL
+               return getAction();
        }
-        elseif (!empty($GLOBALS['action']))
-       {
-               // Fix welcome value
-               if (empty($wht)) $wht = "welcome";
-               return $GLOBALS['action'];
-       }
-        else
-       {
-               // Everything else will be touched after checking the module has a menu assigned
-       }
-       //* DEBUG: */ echo __LINE__."*".$ret."*<br />\n";
+       //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret=".$ret."<br />\n";
 
-       if (MODULE_HAS_MENU($MODE))
-       {
+       // Does the module have a menu?
+       if (MODULE_HAS_MENU($mode)) {
                // Rewriting modules to menu
-               switch ($MODE)
-               {
-                       case "index": $MODE = "guest";  break;
-                       case "login": $MODE = "member"; break;
-                               break;
-               }
+               switch ($mode) {
+                       case 'index': $mode = 'guest';  break;
+                       case 'login': $mode = 'member'; break;
+               } // END - switch
 
-               // Guest and member menu is "main" as the default
-               if (empty($ret)) $ret = "main";
+               // Guest and member menu is 'main' as the default
+               if (empty($ret)) $ret = 'main';
 
                // Load from database
-               $result = SQL_QUERY_ESC("SELECT action FROM "._MYSQL_PREFIX."_%s_menu WHERE what='%s' LIMIT 1",
-                array($MODE, $wht), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
+               $result = SQL_QUERY_ESC("SELECT action FROM `{!_MYSQL_PREFIX!}_%s_menu` WHERE `what`='%s' LIMIT 1",
+               array($mode, $wht), __FUNCTION__, __LINE__);
+               if (SQL_NUMROWS($result) == 1) {
                        // Load action value and pray that this one is the right you want... ;-)
                        list($ret) = SQL_FETCHROW($result);
-               }
+               } // END - if
 
                // Free memory
                SQL_FREERESULT($result);
+       } elseif ((GET_EXT_VERSION('sql_patches') == '') && ($mode != 'admin')) {
+               // No sql_patches installed, but maybe we need to register an admin?
+               if (isAdminRegistered()) {
+                       // Redirect
+                       // @TODO Why does this lead into an endless loop but we still need it???
+                       // @TODO Commented out redirectToUrl('admin.php');
+               } // END - if
        }
 
        // Return action value
        return $ret;
 }
-//
-function GET_CATEGORY ($cid)
-{
-       $ret = _CATEGORY_404;
-       $result = SQL_QUERY_ESC("SELECT cat FROM "._MYSQL_PREFIX."_cats WHERE id=%d LIMIT 1", array($cid), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 1)
-       {
-               // Category found... :-)
-               list($ret) = SQL_FETCHROW($result);
+
+// Get category name back
+function getCategory ($cid) {
+       // Default is not found
+       $ret = getMessage('_CATEGORY_404');
+
+       // Is the category id set?
+       if ($cid == '0') {
+               // No category
+               $ret = getMessage('_CATEGORY_NONE');
+       } elseif ($cid > 0) {
+               // Lookup the category in database
+               $result = SQL_QUERY_ESC("SELECT cat FROM `{!_MYSQL_PREFIX!}_cats` WHERE `id`=%s LIMIT 1",
+               array(bigintval($cid)), __FUNCTION__, __LINE__);
+               if (SQL_NUMROWS($result) == 1) {
+                       // Category found... :-)
+                       list($ret) = SQL_FETCHROW($result);
+               } // END - if
+
+               // Free result
                SQL_FREERESULT($result);
-       }
+       } // END - if
+
+       // Return result
        return $ret;
 }
-//
-function GET_PAYMENT ($pid, $full=false)
-{
-       $ret = _PAYMENT_404;
-       $result = SQL_QUERY_ESC("SELECT mail_title, price FROM "._MYSQL_PREFIX."_payments WHERE id=%d LIMIT 1", array($pid), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 1)
-       {
+
+// Get a string of "mail title" and price back
+function getPaymentTitlePrice ($pid, $full=false) {
+       // Default is not found
+       $ret = getMessage('_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__);
+       if (SQL_NUMROWS($result) == 1) {
                // Payment type found... :-)
-               if (!$full)
-               {
+               if (!$full) {
                        // Return only title
                        list($ret) = SQL_FETCHROW($result);
-                       SQL_FREERESULT($result);
-               }
-                else
-               {
+               } else {
                        // Return title and price
                        list($t, $p) = SQL_FETCHROW($result);
-                       $ret = $t." / ".TRANSLATE_COMMA($p)." ".POINTS;
+                       $ret = $t.' / '.translateComma($p).' {!POINTS!}';
                }
        }
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return result
        return $ret;
 }
-//
-function GET_PAY_POINTS($pid, $lookFor="price")
-{
-       $ret = "-1";
-       $result = SQL_QUERY_ESC("SELECT %s FROM "._MYSQL_PREFIX."_payments WHERE id=%d LIMIT 1",
-               array($lookFor, $pid), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 1)
-       {
+
+// Get (basicly) the price of given payment id
+function getPaymentPoints ($pid, $lookFor = 'price') {
+       // Default value...
+       $ret = '-1';
+
+       // 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__);
+
+       // Is the entry there?
+       if (SQL_NUMROWS($result) == 1) {
                // Payment type found... :-)
                list($ret) = SQL_FETCHROW($result);
-               SQL_FREERESULT($result);
-       }
+       } // END - if
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return value
        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)
-{
-       $ret = "failed";
-       if ($uid > 0)
-       {
+
+// Remove a receiver's ID from $receivers and add a link for him to confirm
+function removeReceiver (&$receivers, $key, $uid, $pool_id, $stats_id='', $bonus=false) {
+       // Default is not removed
+       $ret = 'failed';
+
+       // 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"; }
-                       $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_user_links WHERE %s='%s' AND userid=%d AND link_type='%s' LIMIT 1",
-                        array($rowName, $stats_id, bigintval($uid), $type), __FILE__, __LINE__);
-                       if (SQL_NUMROWS($result) == 0)
-                       {
-                               // No, so we add one!
-                               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_user_links (%s, userid, link_type) VALUES ('%s', '%s', '%s')",
-                                array($rowName, $stats_id, bigintval($uid), $type), __FILE__, __LINE__);
-                               $ret = "done";
-                       }
-                        else
-                       {
+                       $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__);
+
+                       // 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__);
+                               $ret = 'done';
+                       } else {
                                // Already found
-                               $ret = "already";
+                               $ret = 'already';
                        }
 
                        // Free memory
                        SQL_FREERESULT($result);
                }
        }
+
        // Return status for sending routine
        return $ret;
 }
-//
-function GET_TOTAL_DATA($search, $tableName, $lookFor, $whereStatement="userid", $onlyRows=false)
-{
-       $ret = "0";
-       if ($onlyRows) {
+
+// Calculate sum (default) or count records of given criteria
+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 ((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
-               $result = SQL_QUERY_ESC("SELECT COUNT(%s) FROM "._MYSQL_PREFIX."_%s WHERE %s='%s'",
-                array($lookFor, $tableName, $whereStatement, $search), __FILE__, __LINE__);
+               //* DEBUG: */ echo "COUNT!<br />\n";
+               $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s'".$add,
+               array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
        } else {
                // Add all rows
-               $result = SQL_QUERY_ESC("SELECT SUM(%s) FROM "._MYSQL_PREFIX."_%s WHERE %s='%s'",
-                array($lookFor, $tableName, $whereStatement, $search), __FILE__, __LINE__);
+               //* DEBUG: */ echo "SUM!<br />\n";
+               $result = SQL_QUERY_ESC("SELECT SUM(`%s`) FROM `{!_MYSQL_PREFIX!}_%s` WHERE `%s`='%s'".$add,
+               array($lookFor, $tableName, $whereStatement, $search), __FUNCTION__, __LINE__);
        }
 
        // Load row
        list($ret) = SQL_FETCHROW($result);
-       //* DEBUG: */ echo __LINE__."*".$DATA."/".$search."/".$tableName."/".$ret."*<br />\n";
+
+       // Free result
        SQL_FREERESULT($result);
-       if (empty($ret)) {
-               if (($lookFor == "counter") || ($lookFor == "id")) {
-                       $ret = "0";
-               } else {
-                       $ret = "0.00000";
-               }
+
+       // Fix empty values
+       if ((empty($ret)) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
+               // Float number
+               $ret = '0.00000';
+       } elseif (''.$ret.'' == '') {
+               // Fix empty result
+               $ret = '0';
        }
+
+       // Return value
        return $ret;
 }
+// Getter fro ref level percents
+function getReferalLevelPercents ($level) {
+       // Default is zero
+       $per = 0;
+
+       // Do we have cache?
+       if ((isset($GLOBALS['cache_array']['ref_depths']['level'])) && (EXT_IS_ACTIVE('cache'))) {
+               // First look for level
+               $key = array_search($level, $GLOBALS['cache_array']['ref_depths']['level']);
+               if ($key !== false) {
+                       // Entry found!
+                       $per = $GLOBALS['cache_array']['ref_depths']['percents'][$key];
+
+                       // Count cache hit
+                       incrementConfigEntry('cache_hits');
+               }
+       } elseif (!EXT_IS_ACTIVE('cache')) {
+               // Get referal data
+               $result_lvl = SQL_QUERY_ESC("SELECT percents FROM `{!_MYSQL_PREFIX!}_refdepths` WHERE level='%s' LIMIT 1",
+               array(bigintval($level)), __FUNCTION__, __LINE__);
+
+               // Entry found?
+               if (SQL_NUMROWS($result_lvl) == 1) {
+                       // Get percents
+                       list($per) = SQL_FETCHROW($result_lvl);
+               } // END - if
+
+               // Free result
+               SQL_FREERESULT($result_lvl);
+       }
+
+       // Return percent
+       return $per;
+}
+
 /**
  *
- * Dynamic referral system, can also send mails!
+ * Dynamic referal system, can also send mails!
  *
- * uid         = Referral ID wich should receive...
+ * subject     = Subject line, write in lower-case letters and underscore is allowed
+ * uid         = Referal ID wich should receive...
  * points      = ... xxx points
- * send_notify = shall I send the referral an email or not?
- * refid       = inc/modules/guest/what-confirm.php need this
+ * send_notify = shall I send the referal an email or not?
+ * rid         = inc/modules/guest/what-confirm.php need this (DEPRECATED???)
  * locked      = Shall I pay it to normal (false) or locked (true) points ammount?
- * add_mode    = Add points only to $uid or also refs? (WARNING! Changing "ref" to "direct"
- *               will cause no referral will get points ever!!!)
+ * add_mode    = Add points only to $uid or also refs? (WARNING! Changing 'ref' to 'direct'
+ *               for default value will cause no referal will get points ever!!!)
  */
-function ADD_POINTS_REFSYSTEM($uid, $points, $send_notify=false, $rid="0", $locked=false, $add_mode="ref")
-{
-       global $DEPTH, $_CONFIG, $DATA, $link;
+function ADD_POINTS_REFSYSTEM ($subject, $uid, $points, $send_notify = false, $rid = '0', $locked = false, $add_mode = 'ref') {
+       //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
+       global $DATA;
+
+       // Convert mode to lower-case
+       $add_mode = strtolower($add_mode);
 
        // When $uid = 0 add points to jackpot
-       if ($uid == "0")
-       {
+       if ($uid == '0') {
                // Add points to jackpot
                ADD_JACKPOT($points);
                return;
+       } // END - if
+
+       // Add booking record if extension is installed
+       if (EXT_IS_ACTIVE('booking')) {
+               // Add record
+               ADD_BOOKING_RECORD($subject, $uid, $points, 'add');
+       } // END - if
+
+       // Count up referal depth
+       if (!isset($GLOBALS['ref_level'])) {
+               // Initialialize referal system
+               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal system initialized!<br />\n";
+               $GLOBALS['ref_level'] = 0;
+       } else {
+               // Increase referal level
+               $GLOBALS['ref_level']++;
+               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Referal level increased. DEPTH={$GLOBALS['ref_level']}<br />\n";
        }
 
-       // Count up referral depth
-       if (empty($DEPTH))
-       {
-               // Initialialize referral system
-               $DEPTH = "0";
-       }
-        else
-       {
-               // Increase referral level
-               $DEPTH++;
-       }
+       // Default is 'normal' points
+       $data = 'points';
 
        // Which points, locked or normal?
-       $data = "points"; if ($locked) $data = "locked_points";
+       if ($locked) $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($uid)), __FUNCTION__, __LINE__);
 
-       $result_user = SQL_QUERY_ESC("SELECT refid, email FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d AND status='CONFIRMED' LIMIT 1",
-        array(bigintval($uid)), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result_user) == 1)
-       {
+       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},numRows=".SQL_NUMROWS($result_user).",points={$points}<br />\n";
+       if (SQL_NUMROWS($result_user) == 1) {
                // This is the user and his ref
-               list ($ref, $email) = SQL_FETCHROW($result_user);
-               SQL_FREERESULT($result_user);
-               $result = SQL_QUERY_ESC("SELECT percents FROM "._MYSQL_PREFIX."_refdepths WHERE level='%s' LIMIT 1",
-                array(bigintval($DEPTH)), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
-                       list($per) = SQL_FETCHROW($result);
-                       SQL_FREERESULT($result);
-                       $P = $points * $per / 100;
+               list($ref, $email) = SQL_FETCHROW($result_user);
+               $GLOBALS['cache_array']['add_uid'][$ref] = $uid;
+
+               // Get percents
+               $per = getReferalLevelPercents($GLOBALS['ref_level']);
+               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},points={$points},depth={$GLOBALS['ref_level']},per={$per},mode={$add_mode}<br />\n";
+
+               // Some percents found?
+               if ($per > 0) {
+                       // Calculate new points
+                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},points={$points},per={$per},depth={$GLOBALS['ref_level']}<br />\n";
+                       $ref_points = $points * $per / 100;
+
+                       // Pay refback here if level > 0 and in ref-mode
+                       if ((EXT_IS_ACTIVE('refback')) && ($GLOBALS['ref_level'] > 0) && ($per < 100) && ($add_mode == "ref") && (isset($GLOBALS['cache_array']['add_uid'][$uid]))) {
+                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},data={$GLOBALS['cache_array']['add_uid'][$uid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - BEFORE!<br />\n";
+                               $ref_points = ADD_REFBACK_POINTS($GLOBALS['cache_array']['add_uid'][$uid], $uid, $points, $ref_points);
+                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},data={$GLOBALS['cache_array']['add_uid'][$uid]},ref_points={$ref_points},depth={$GLOBALS['ref_level']} - AFTER!<br />\n";
+                       } // END - if
 
                        // Update points...
-                       $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_user_points SET %s=%s+%s WHERE userid=%d AND ref_depth=%d LIMIT 1",
-                        array($data, $data, $P, bigintval($uid), bigintval($DEPTH)), __FILE__, __LINE__);
-                       if (SQL_AFFECTEDROWS($link, __FILE__, __LINE__) == 0)
-                       {
+                       SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_points` SET %s=%s+%s WHERE userid=%s AND ref_depth='%s' LIMIT 1",
+                       array($data, $data, $ref_points, bigintval($uid), bigintval($GLOBALS['ref_level'])), __FUNCTION__, __LINE__);
+                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},uid={$uid},depth={$GLOBALS['ref_level']},mode={$add_mode} - UPDATE! (".SQL_AFFECTEDROWS().")<br />\n";
+
+                       // No entry updated?
+                       if (SQL_AFFECTEDROWS() < 1) {
                                // First ref in this level! :-)
-                               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_user_points (userid, ref_depth, %s) VALUES (%d, %d, %s)",
-                                array($data, bigintval($uid), bigintval($DEPTH), $P), __FILE__, __LINE__);
-                       }
+                               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_points` (userid,ref_depth,%s) VALUES (%s,'%s',%s)",
+                               array($data, bigintval($uid), bigintval($GLOBALS['ref_level']), $ref_points), __FUNCTION__, __LINE__);
+                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):data={$data},ref_points={$ref_points},uid={$uid},depth={$GLOBALS['ref_level']},mode={$add_mode} - INSERTED! (".SQL_AFFECTEDROWS().")<br />\n";
+                       } // END - if
 
                        // Update mediadata as well
-                       if (GET_EXT_VERSION("mediadata") >= "0.0.4")
-                       {
+                       if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
                                // Update database
-                               MEDIA_UPDATE_ENTRY(array("total_points"), "add", $P);
-                       }
+                               MEDIA_UPDATE_ENTRY(array('total_points'), 'add', $ref_points);
+                       } // END - if
 
                        // Points updated, maybe I shall send him an email?
-                       if (($send_notify) && ($ref > 0) && (!$locked))
-                       {
-                               //              0                1      2              3
-                               $DATA = array($per, bigintval($DEPTH), $P, bigintval($ref));
-                               $msg = LOAD_EMAIL_TEMPLATE("confirm-referral", "", bigintval($uid));
-
-                               SEND_EMAIL($email, THANX_REFERRAL_ONE, $msg);
+                       if (($send_notify) && ($ref > 0) && (!$locked)) {
+                               // Prepare content
+                               $content = array(
+                                       'percent' => $per,
+                                       'level'   => bigintval($GLOBALS['ref_level']),
+                                       'points'  => $ref_points,
+                                       'refid'   => bigintval($ref)
+                               );
+
+                               // Load email template
+                               $msg = LOAD_EMAIL_TEMPLATE('confirm-referal', $content, bigintval($uid));
+
+                               sendEmail($email, THANX_REFERRAL_ONE, $msg);
+                       } elseif (($send_notify) && ($ref == 0) && (!$locked) && ($add_mode == 'direct') && (!defined('__POINTS_VALUE'))) {
+                               // Direct payment shall be notified about
+                               define('__POINTS_VALUE', $ref_points);
+
+                               // Prepare content
+                               $content = array(
+                                       'text'   => getMessage('REASON_DIRECT_PAYMENT'),
+                                       'points' => translateComma($ref_points)
+                               );
+
+                               // Load message
+                               $msg = LOAD_EMAIL_TEMPLATE('add-points', $content, $uid);
+
+                               // And sent it away
+                               sendEmail($email, getMessage('SUBJECT_DIRECT_PAYMENT'), $msg);
+                               if (!REQUEST_ISSET_GET(('mid'))) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_POINTS_ADDED'));
                        }
 
                        // Maybe there's another ref?
-                       if (($ref > 0) && ($points > 0) && ($ref != $uid) && ($add_mode == "ref"))
-                       {
+                       if (($ref > 0) && ($points > 0) && ($ref != $uid) && ($add_mode == 'ref')) {
                                // Then let's credit him here...
-                               ADD_POINTS_REFSYSTEM($ref, $points, $send_notify, $ref, $locked);
-                       }
-               }
-       }
+                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref},points={$points} - ADVANCE!<br />\n";
+                               ADD_POINTS_REFSYSTEM(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), $ref, $points, $send_notify, $ref, $locked);
+                       } // END - if
+               } // END - if
+       } // END - if
+
+       // Free result
+       SQL_FREERESULT($result_user);
+       //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
+}
+
+// Wrapper function for ADD_POINTS_REFSYSTEM()
+function ADD_POINTS_REFSYSTEM_DIRECT ($subject, $uid, $points) {
+       return ADD_POINTS_REFSYSTEM($subject, $uid, $points, false, 0, false, 'direct');
 }
-//
-function UPDATE_REF_COUNTER($uid)
-{
-       global $REF_LVL, $link, $cacheInstance;
-       // Make it sure referral level zero (member him-/herself) is at least selected
-       if (empty($REF_LVL)) $REF_LVL = "0";
+
+// Updates the referal counter
+function updateReferalCounter ($uid) {
+       // Make it sure referal level zero (member him-/herself) is at least selected
+       if (empty($GLOBALS['cache_array']['ref_level'][$uid])) $GLOBALS['cache_array']['ref_level'][$uid] = 1;
+       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},level={$GLOBALS['cache_array']['ref_level'][$uid]}<br />\n";
 
        // Update counter
-       $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_refsystem SET counter=counter+1 WHERE userid=%d AND level='%s' LIMIT 1",
-        array(bigintval($uid), $REF_LVL), __FILE__, __LINE__);
+       SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_refsystem` SET counter=counter+1 WHERE userid=%s AND level='%s' LIMIT 1",
+       array(bigintval($uid), $GLOBALS['cache_array']['ref_level'][$uid]), __FUNCTION__, __LINE__);
 
        // When no entry was updated then we have to create it here
-       if (SQL_AFFECTEDROWS($link) == 0)
-       {
+       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):updated=".SQL_AFFECTEDROWS()."<br />\n";
+       if (SQL_AFFECTEDROWS() < 1) {
                // First count!
-               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_refsystem (userid, level, counter) VALUES ('%s', '%s', '1')",
-                array(bigintval($uid), $REF_LVL), __FILE__, __LINE__);
-       }
+               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_refsystem` (userid, level, counter) VALUES (%s,%s,1)",
+               array(bigintval($uid), $GLOBALS['cache_array']['ref_level'][$uid]), __FUNCTION__, __LINE__);
+               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid}<br />\n";
+       } // END - if
+
+       // Check for his referal
+       $result = SQL_QUERY_ESC("SELECT refid FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
+       array(bigintval($uid)), __FUNCTION__, __LINE__);
 
-       // Check for his referral
-       $result = SQL_QUERY_ESC("SELECT refid FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1",
-        array(bigintval($uid)), __FILE__, __LINE__);
+       // Load refid
        list($ref) = SQL_FETCHROW($result);
 
        // Free memory
        SQL_FREERESULT($result);
-
-       // When he has a referral...
-       if (($ref > 0) && ($ref != $uid))
-       {
-               // Move to next referral level and count his counter one up!
-               $REF_LVL++; UPDATE_REF_COUNTER($ref);
-       }
-        elseif ((($ref == $uid) || ($ref == 0)) && (GET_EXT_VERSION("cache") >= "0.1.2"))
-       {
+       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):uid={$uid},ref={$ref}<br />\n";
+
+       // When he has a referal...
+       if (($ref > 0) && ($ref != $uid)) {
+               // Move to next referal level and count his counter one up!
+               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - ADVANCE!<br />\n";
+               $GLOBALS['cache_array']['ref_level'][$uid]++; updateReferalCounter($ref);
+       } elseif ((($ref == $uid) || ($ref == 0)) && (GET_EXT_VERSION('cache') >= '0.1.2')) {
                // Remove cache here
-               if ($cacheInstance->cache_file("refsystem", true)) $cacheInstance->cache_destroy();
-       }
-}
-//
-function UPDATE_ONLINE_LIST($SID, $mod, $act, $wht)
-{
-       global $link, $_CONFIG;
-       // Do not update online list when extension is deactivated
-       if (!EXT_IS_ACTIVE("online", true)) return;
-
-       // Initialize variables
-       $uid = "0"; $rid = "0"; $MEM = 'N'; $ADMIN = 'N';
-       if (!empty($GLOBALS['userid']))
-       {
-               // Update member status only when userid is valid
-               if (($GLOBALS['userid'] > 0) && (IS_LOGGED_IN()))
-               {
-                       // Is valid user
-                       $uid = $GLOBALS['userid'];
-                       $MEM = 'Y';
-               }
-       }
-       if (IS_ADMIN())
-       {
-               // Is administrator
-               $ADMIN = 'Y';
-       }
-       if (isSessionVariableSet('refid')) {
-               // Check cookie
-               if (get_session('refid') > 0) $rid = $GLOBALS['refid'];
+               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ref={$ref} - CACHE!<br />\n";
+               rebuildCacheFiles('refsystem', 'refsystem');
        }
 
-       // Now Read data
-       $result = SQL_QUERY_ESC("SELECT timestamp FROM "._MYSQL_PREFIX."_online
-WHERE sid='%s' LIMIT 1",
- array($SID), __FILE__, __LINE__);
-
-       if (SQL_NUMROWS($result) == 1)
-       {
-               SQL_FREERESULT($result);
-               $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_online SET
-module='%s',
-action='%s',
-what='%s',
-userid=%d,
-refid=%d,
-is_member='%s',
-is_admin='%s',
-timestamp=UNIX_TIMESTAMP()
-WHERE sid='%s' LIMIT 1",
- array(
-       $mod,
-       $act,
-       $wht,
-       bigintval($uid),
-       bigintval($rid),
-       $MEM,
-       $ADMIN,
-       $SID
-), __FILE__, __LINE__);
-       }
-        else
-       {
-               // No entry does exists so we simply add it!
-               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_online (module, action, what, userid, refid, is_member, is_admin, timestamp, sid, ip) VALUES ('%s', '%s', '%s', %d, %d, '%s', '%s', UNIX_TIMESTAMP(), '%s', '%s')",
-                array($mod, $act, $wht, bigintval($uid), bigintval($rid), $MEM, $ADMIN, $SID, getenv('REMOTE_ADDR')), __FILE__, __LINE__);
-       }
+       // "Walk" back here
+       $GLOBALS['cache_array']['ref_level'][$uid]--;
 
-       // Purge old entries
-       $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_online WHERE timestamp <= (UNIX_TIMESTAMP() - %d)",
-        array($_CONFIG['online_timeout']), __FILE__, __LINE__);
+       // Handle refback here if extension is installed
+       if (EXT_IS_ACTIVE('refback')) {
+               updateRefbackTable($uid);
+       } // END - if
 }
-// OBSULETE: Sends out mail to all administrators
-function SEND_ADMIN_EMAILS($subj, $msg)
-{
-       $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
-       while (list($email) = SQL_FETCHROW($result))
-       {
-               SEND_EMAIL($email, $subj, $msg);
-       }
-       // Really simple... ;-)
+
+// 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 ($content = SQL_FETCHARRAY($result)) {
+               // Send the email out
+               sendEmail($content['email'], $subj, $msg);
+       } // END - if
+
+       // Free result
        SQL_FREERESULT($result);
+
+       // Really simple... ;-)
 }
+
 // Get ID number from administrator's login name
-function GET_ADMIN_ID($login)
-{
-       global $cacheArray;
-       $ret = "-1";
-       if (!empty($cacheArray['admins']['aid'][$login]))
-       {
-               // Check cache
-               $ret = $cacheArray['admins']['aid'][$login];
-               if (empty($ret)) $ret = "-1";
-       }
-        else
-       {
+function GET_ADMIN_ID ($login) {
+       // By default no admin is found
+       $ret = '-1';
+
+       // Check cache
+       if (isset($GLOBALS['cache_array']['admins']['aid'][$login])) {
+               // Use it if found to save SQL queries
+               $ret = $GLOBALS['cache_array']['admins']['aid'][$login];
+
+               // Update cache hits
+               incrementConfigEntry('cache_hits');
+       } elseif (!EXT_IS_ACTIVE('cache')) {
                // Load from database
-               $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
-                array($login), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
+               $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
+               array($login), __FUNCTION__, __LINE__);
+               if (SQL_NUMROWS($result) == 1) {
                        list($ret) = SQL_FETCHROW($result);
-                       SQL_FREERESULT($result);
-               }
+               } // END - if
+
+               // Free result
+               SQL_FREERESULT($result);
        }
        return $ret;
 }
-//
+
+// "Getter" for current admin id
+function getCurrentAdminId () {
+       // Get the admin login from session
+       $adminLogin = getSession('admin_login');
+
+       // "Solve" it into an id
+       $adminId = GET_ADMIN_ID($adminLogin);
+
+       // Secure and return it
+       return bigintval($adminId);
+}
+
 // Get password hash from administrator's login name
-function GET_ADMIN_HASH($login)
-{
-       global $cacheArray;
-       $ret = "-1";
-       if (!empty($cacheArray['admins']['password'][$login]))
-       {
+function GET_ADMIN_HASH ($aid) {
+       // By default an invalid hash is returned
+       $ret = '-1';
+
+       if (isset($GLOBALS['cache_array']['admins']['password'][$aid])) {
                // Check cache
-               $ret = $cacheArray['admins']['password'][$login];
-               if (empty($ret)) $ret = "-1";
-       }
-        else
-       {
+               $ret = $GLOBALS['cache_array']['admins']['password'][$aid];
+
+               // Update cache hits
+               incrementConfigEntry('cache_hits');
+       } elseif (!EXT_IS_ACTIVE('cache')) {
                // Load from database
-               $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
-                array($login), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
+               $result = SQL_QUERY_ESC("SELECT password FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
+               array($aid), __FUNCTION__, __LINE__);
+               if (SQL_NUMROWS($result) == 1) {
+                       // Fetch data
                        list($ret) = SQL_FETCHROW($result);
-                       SQL_FREERESULT($result);
-               }
+
+                       // Set cache
+                       $GLOBALS['cache_array']['admins']['password'][$aid] = $ret;
+               } // END - if
+
+               // Free result
+               SQL_FREERESULT($result);
        }
        return $ret;
 }
-//
-function GET_ADMIN_LOGIN($aid)
-{
-       global $cacheArray;
-       $ret = "***";
-       if (!empty($cacheArray['admins']['login']['aid']))
-       {
-               // Check cache
-               if (!empty($cacheArray['admins']['login'][$aid]))       $ret = $cacheArray['admins']['login'][$aid];
-               if (empty($ret)) $ret = "***";
-       }
-        else
-       {
+
+// "Getter" for admin login
+function getAdminLogin ($aid) {
+       // By default a non-existent login is returned (other functions react on this!)
+       $ret = '***';
+
+       if (isset($GLOBALS['cache_array']['admins']['login'][$aid])) {
+               // Get cache
+               $ret = $GLOBALS['cache_array']['admins']['login'][$aid];
+
+               // Update cache hits
+               incrementConfigEntry('cache_hits');
+       } elseif (!EXT_IS_ACTIVE('cache')) {
                // Load from database
-               $result = SQL_QUERY_ESC("SELECT login FROM "._MYSQL_PREFIX."_admins WHERE id=%d LIMIT 1",
-                array(bigintval($aid)), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
+               $result = SQL_QUERY_ESC("SELECT login FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
+               array(bigintval($aid)), __FUNCTION__, __LINE__);
+               if (SQL_NUMROWS($result) == 1) {
                        // Fetch data
                        list($ret) = SQL_FETCHROW($result);
-               }
+
+                       // Set cache
+                       $GLOBALS['cache_array']['admins']['login'][$aid] = $ret;
+               } // END - if
 
                // Free memory
                SQL_FREERESULT($result);
        }
        return $ret;
 }
-//
-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))
-               {
-                       // Both are arrays
-                       foreach ($id as $idx=>$value)
-                       {
-                               $ret .= "<OPTION value=\"".$value."\"";
-                               if ($default == $value) $ret .= " selected checked";
-                               $ret .= ">".$name[$idx]."</OPTION>\n";
-                       }
+
+// Get email address of admin id
+function getAdminEmail ($aid) {
+       // By default an invalid emails is returned
+       $ret = '***';
+
+       if (isset($GLOBALS['cache_array']['admins']['email'][$aid])) {
+               // Get cache
+               $ret = $GLOBALS['cache_array']['admins']['email'][$aid];
+
+               // Update cache hits
+               incrementConfigEntry('cache_hits');
+       } elseif (!EXT_IS_ACTIVE('cache')) {
+               // Load from database
+               $result_aid = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
+               array(bigintval($aid)), __FUNCTION__, __LINE__);
+               if (SQL_NUMROWS($result_aid) == 1) {
+                       // Get data
+                       list($ret) = SQL_FETCHROW($result_aid);
+
+                       // Set cache
+                       $GLOBALS['cache_array']['admins']['email'][$aid] = $ret;
+               } // END - if
+
+               // Free result
+               SQL_FREERESULT($result_aid);
+       }
+
+       // Return email
+       return $ret;
+}
+
+// Get default ACL  of admin id
+function getAdminDefaultAcl ($aid) {
+       // By default an invalid ACL value is returned
+       $ret = '***';
+
+       // 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];
+
+               // Update cache hits
+               incrementConfigEntry('cache_hits');
+       } elseif (!EXT_IS_ACTIVE('cache')) {
+               // Load from database
+               $result_aid = SQL_QUERY_ESC("SELECT default_acl FROM `{!_MYSQL_PREFIX!}_admins` WHERE `id`=%s LIMIT 1",
+               array(bigintval($aid)), __FUNCTION__, __LINE__);
+               if (SQL_NUMROWS($result_aid) == 1) {
+                       // Fetch data
+                       list($ret) = SQL_FETCHROW($result_aid);
+
+                       // Set cache
+                       $GLOBALS['cache_array']['admins']['def_acl'][$aid] = $ret;
                }
+
+               // Free result
+               SQL_FREERESULT($result_aid);
        }
-        else
-       {
+
+       // Return email
+       return $ret;
+}
+
+// Generates an option list from various parameters
+function generateOptionList ($table, $id, $name, $default='', $special='', $where='') {
+       $ret = '';
+       if ($table == '/ARRAY/') {
+               // Selection from array
+               if (is_array($id) && is_array($name) && count($id) == count($name)) {
+                       // Both are arrays
+                       foreach ($id as $idx => $value) {
+                               $ret .= '<option value="' . $value . '"';
+                               if ($default == $value) $ret .= ' selected="selected"';
+                               $ret .= '>' . $name[$idx] . '</option>';
+                       } // END - foreach
+               } // END - if
+       } else {
                // Data from database
-               $SPEC = ", ".$id;
-               if (!empty($special)) $SPEC = ", ".$special;
+               $SPEC = ', '.$id;
+               if (!empty($special)) $SPEC = ', ' . $special;
                $ORDER = $name.$SPEC;
-               if ($table == "country") $ORDER = $special;
-               $result = SQL_QUERY_ESC("SELECT %s, %s".$SPEC." FROM "._MYSQL_PREFIX."_%s ".$where." ORDER BY %s",
-                array($id, $ORDER, $table, $name), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) > 0)
-               {
+               if ($table == 'country') $ORDER = $special;
+               $result = SQL_QUERY_ESC("SELECT %s, %s".$SPEC." FROM `{!_MYSQL_PREFIX!}_%s` ".$where." ORDER BY %s",
+               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
-                       while (list($value, $title, $add) = SQL_FETCHROW($result))
-                       {
-                               if (empty($special)) $add = "";
-                               $ret .= "<OPTION value=\"".$value."\"";
-                               if ($default == $value) $ret .= " selected checked";
-                               if (!empty($add)) $add = " (".$add.")";
-                               $ret .= ">".$title.$add."</OPTION>\n";
-                       }
+                       // @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 . '"';
+                               if ($default == $value) $ret .= ' selected="selected"';
+                               if (!empty($add)) $add = ' ('.$add.')';
+                               $ret .= '>' . $title . $add . '</option>';
+                       } // END - while
 
                        // Free memory
                        SQL_FREERESULT($result);
-               }
-                else
-               {
+               } else {
                        // No data found
-                       $ret = "<OPTION value=\"x\">".SELECT_NONE."</OPTION>\n";
+                       $ret = '<option value="x">{--SELECT_NONE--}</option>';
                }
        }
+
        // Return - hopefully - the requested data
        return $ret;
 }
-// Aiut
-function activateExchange() {
-       global $_CONFIG;
-       $result = SQL_QUERY("SELECT userid FROM "._MYSQL_PREFIX."_user_data WHERE status='CONFIRMED' AND max_mails > 0", __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) >= $_CONFIG['activate_xchange'])
-       {
-               // Free memory
-               SQL_FREERESULT($result);
+// Activate exchange
+function activateExchange () {
+       // Is the extension 'user' there?
+       if (!EXT_IS_ACTIVE('user')) {
+               // Silently abort here
+               return false;
+       } // END - if
 
-               // Activate System
-               $SQLs = array(
-                       "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"
-               );
-
-               // Run SQLs
-               foreach ($SQLs as $sql)
-               {
-                       $result = SQL_QUERY($sql, __FILE__, __LINE__);
-               }
+       // Check total amount of users
+       $totalUsers = GET_TOTAL_DATA('CONFIRMED', 'user_data', 'userid', 'status', true, ' AND max_mails > 0');
 
-               // Destroy cache
-       }
+       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!}_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"
+                       ));
+
+                       // Run SQLs
+                       runFilterChain('run_sqls');
+
+                       // Rebuild caches
+                       // @TODO Rewrite this to a filter
+                       rebuildCacheFiles('config', 'config');
+                       rebuildCacheFiles('modreg', 'modreg');
+       } // END - if
 }
-//
-function DELETE_USER_ACCOUNT($uid, $reason)
-{
+
+// Deletes a user account with given reason
+function deleteUserAccount ($uid, $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
+FROM `{!_MYSQL_PREFIX!}_user_points` AS p
+LEFT JOIN `{!_MYSQL_PREFIX!}_user_data` AS d
 ON p.userid=d.userid
-WHERE p.userid=%d", array(bigintval($uid)), __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 1)
-       {
+WHERE p.userid=%s", array(bigintval($uid)), __FUNCTION__, __LINE__);
+       if (SQL_NUMROWS($result) == 1) {
                // Save his points to add them to the jackpot
                list($points) = SQL_FETCHROW($result);
-               SQL_FREERESULT($result);
 
                // Delete points entries as well
-               $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_points WHERE userid=%d", array(bigintval($uid)), __FILE__, __LINE__);
+               SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_points` WHERE userid=%s", array(bigintval($uid)), __FUNCTION__, __LINE__);
 
                // Update mediadata as well
-               if (GET_EXT_VERSION("mediadata") >= "0.0.4")
-               {
+               if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
                        // Update database
-                       MEDIA_UPDATE_ENTRY(array("total_points"), "sub", $points);
-               }
+                       MEDIA_UPDATE_ENTRY(array('total_points'), 'sub', $points);
+               } // END - if
 
                // Now, when we have all his points adds them do the jackpot!
                ADD_JACKPOT($points);
-       }
+       } // END - if
+
+       // Free the result
+       SQL_FREERESULT($result);
 
        // Delete category selections as well...
-       $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_cats WHERE userid=%d",
-        array(bigintval($uid)), __FILE__, __LINE__);
+       SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_cats` WHERE userid=%s",
+       array(bigintval($uid)), __FUNCTION__, __LINE__);
 
        // Remove from rallye if found
-       if (EXT_IS_ACTIVE("rallye"))
-       {
-               $result = SQL_QUERY("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_rallye_users WHERE userid=%d",
-                array(bigintval($uid)), __FILE__, __LINE__);
-       }
+       if (EXT_IS_ACTIVE('rallye')) {
+               SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_rallye_users` WHERE userid=%s",
+               array(bigintval($uid)), __FUNCTION__, __LINE__);
+       } // END - if
 
        // Now a mail to the user and that's all...
-       $msg = LOAD_EMAIL_TEMPLATE("del-user", $reason, $uid);
-       SEND_EMAIL($uid, ADMIN_DEL_ACCOUNT, $msg);
+       $msg = LOAD_EMAIL_TEMPLATE('del-user', array('text' => $reason), $uid);
+       sendEmail($uid, getMessage('ADMIN_DEL_ACCOUNT'), $msg);
 
        // Ok, delete the account!
-       $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_user_data WHERE userid=%d LIMIT 1", array(bigintval($uid)), __FILE__, __LINE__);
+       SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($uid)), __FUNCTION__, __LINE__);
 }
-//
-function META_DESCRIPTION($mod, $wht)
-{
-       global $_CONFIG, $DEPTH;
-       if (($mod != "admin") && ($mod != "login"))
-       {
-               // Exclude admin and member's area
-               $DESCR = MAIN_TITLE." ".trim($_CONFIG['title_middle'])." ".ADD_DESCR("guest", "what-".$wht, true);
-               unset($DEPTH);
-               OUTPUT_HTML("<META name=\"description\" content=\"".$DESCR."\">");
-       }
+
+// Generates meta description for given module and 'what' value
+function generateMetaDescriptionCode ($mod, $wht) {
+       // Exclude admin and member's area
+       if (($mod != 'admin') && ($mod != 'login')) {
+               // Construct dynamic description
+               $DESCR = '{!MAIN_TITLE!} '.trim(getConfig('title_middle')) . ' ' . ADD_DESCR('guest', 'what-'.$wht, true);
+
+               // Output it directly
+               OUTPUT_HTML('<meta name="description" content="' . $DESCR . '" />');
+       } // END - if
+
+       // Remove depth
+       unset($GLOBALS['ref_level']);
 }
-//
-function ADD_JACKPOT($points)
-{
-       $result = SQL_QUERY("SELECT points FROM "._MYSQL_PREFIX."_jackpot WHERE ok='ok' LIMIT 1", __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 0)
-       {
+
+// Adds points to the jackpot
+function ADD_JACKPOT ($points) {
+       $result = SQL_QUERY("SELECT points FROM `{!_MYSQL_PREFIX!}_jackpot` WHERE ok='ok' LIMIT 1", __FUNCTION__, __LINE__);
+       if (SQL_NUMROWS($result) == 0) {
                // Create line
-               $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_jackpot (ok, points) VALUES ('ok', '%s')", array($points), __FILE__, __LINE__);
-       }
-        else
-       {
+               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_jackpot` (ok, points) VALUES ('ok','%s')", array($points), __FUNCTION__, __LINE__);
+       } else {
                // Free memory
                SQL_FREERESULT($result);
 
                // Update points
-               $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_jackpot SET points=points+%s WHERE ok='ok' LIMIT 1",
-                array($points), __FILE__, __LINE__);
+               SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_jackpot` SET points=points+%s WHERE ok='ok' LIMIT 1",
+               array($points), __FUNCTION__, __LINE__);
        }
 }
-//
-function SUB_JACKPOT($points)
-{
+
+// Subtracts points from the jackpot
+function SUB_JACKPOT ($points) {
        // First failed
-       $ret = "-1";
+       $ret = '-1';
 
        // Get current points
-       $result = SQL_QUERY("SELECT points FROM "._MYSQL_PREFIX."_jackpot WHERE ok='ok' LIMIT 1", __FILE__, __LINE__);
-       if (SQL_NUMROWS($result) == 0)
-       {
+       $result = SQL_QUERY("SELECT points FROM `{!_MYSQL_PREFIX!}_jackpot` WHERE ok='ok' LIMIT 1", __FUNCTION__, __LINE__);
+       if (SQL_NUMROWS($result) == 0) {
                // Create line
-               $result = SQL_QUERY("INSERT INTO "._MYSQL_PREFIX."_jackpot (ok, points) VALUES ('ok', 0.00000)", __FILE__, __LINE__);
-       }
-        else
-       {
-               // Free memory
-               SQL_FREERESULT($result);
-
+               SQL_QUERY("INSERT INTO `{!_MYSQL_PREFIX!}_jackpot` (ok, points) VALUES ('ok', 0.00000)", __FUNCTION__, __LINE__);
+       } else {
                // Read points
                list($jackpot) = SQL_FETCHROW($result);
-               if ($jackpot >= $points)
-               {
+               if ($jackpot >= $points) {
                        // Update points when there are enougth points in jackpot
-                       $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_jackpot SET points=points-%s WHERE ok='ok' LIMIT 1",
-                               array($points), __FILE__, __LINE__);
+                       SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_jackpot` SET points=points-%s WHERE ok='ok' LIMIT 1",
+                       array($points), __FUNCTION__, __LINE__);
                        $ret = $jackpot - $points;
-               }
+               } // END - if
        }
+
+       // Free memory
+       SQL_FREERESULT($result);
 }
-//
-function IS_DEMO() {
-       return ((EXT_IS_ACTIVE("demo")) && (get_session('admin_login') == "demo"));
+
+// Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
+function IS_DEMO () {
+       return ((EXT_IS_ACTIVE('demo')) && (getSession('admin_login') == 'demo'));
 }
-//
-function LOAD_CONFIG($no="0")
-{
-       global $cacheArray;
-       $CFG_DUMMY = array();
-
-       // Check for cache extension, cache-array and if the requested configuration is in cache
-       if ((is_array($cacheArray)) && (isset($cacheArray['config'][$no])) && (is_array($cacheArray['config'][$no]))) {
-               // Load config from cache
-               //* DEBUG: */ echo gettype($cacheArray['config'][$no])."<br />\n";
-               foreach ($cacheArray['config'][$no] as $key=>$value) {
-                       $CFG_DUMMY[$key] = $value;
-               }
 
-               // Count cache hits
-               $CFG_DUMMY['cache_hits']++;
+// Gets the matching what name from module
+function getWhatFromModule ($modCheck) {
+       // Is the request element set?
+       if (REQUEST_ISSET_GET('what')) {
+               // Then return this!
+               return REQUEST_GET('what');
+       } // END - if
+
+       // Default is empty
+       $wht = '';
+
+       //* DEBUG: */ echo __LINE__.'!'.$modCheck."!<br />\n";
+       switch ($modCheck) {
+               case 'admin':
+                       $wht = 'overview';
+                       break;
+
+               case 'login':
+               case 'index':
+                       $wht = 'welcome';
+                       if (($modCheck == 'index') && (getConfig('index_home') != '')) $wht = getConfig('index_home');
+                       break;
+
+               default:
+                       $wht = '';
+                       break;
+       } // END - switch
+
+       // Return what value
+       return $wht;
+}
+
+// Subtract points from database and mediadata cache
+function SUB_POINTS ($subject, $uid, $points) {
+       // Add points to used points
+       SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `used_points`=`used_points`+%s WHERE userid=%s LIMIT 1",
+               array($points, bigintval($uid)), __FUNCTION__, __LINE__);
+
+       // Insert booking record
+       // @TODO Rewrite this to a filter
+       if (EXT_IS_ACTIVE('booking')) {
+               // Add record
+               ADD_BOOKING_RECORD($subject, $uid, $points, 'sub');
+       } // END - if
+
+       // Update mediadata as well
+       if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
+               // Update database
+               MEDIA_UPDATE_ENTRY(array('total_points'), 'sub', $points);
+       } // END - if
+}
+
+// Update config entries
+function updateConfiguration ($entries, $values, $updateMode='') {
+       // Do not update config in CSS mode
+       if ((getOutputMode() == '1') || (getOutputMode() == -1)) {
+               return;
+       } // END - if
+
+       // Do we have multiple entries?
+       if (is_array($entries)) {
+               // Walk through all
+               $all = '';
+               foreach ($entries as $idx => $entry) {
+                       // Update mode set?
+                       if (!empty($updateMode)) {
+                               // Update entry
+                               // @TODO Find a way for updating $_CONFIG here
+                               $all .= sprintf("%s=%s%s%s,", $entry, $entry, $updateMode, (float)$values[$idx]);
+                       } else {
+                               // Check if string or number
+                               if (($values[$idx] + 0) === $values[$idx]) {
+                                       // Number detected
+                                       $all .= sprintf("%s=%s,", $entry, (float)$values[$idx]);
+                               } elseif ($values[$idx] == 'UNIX_TIMESTAMP()') {
+                                       // Function UNIX_TIMESTAMP() detected
+                                       $all .= sprintf("%s=%s,", $entry, $values[$idx]);
+                               } else {
+                                       // String detected
+                                       $all .= sprintf("%s='%s',", $entry, SQL_ESCAPE($values[$idx]));
+                               }
+                       }
+
+                       // Set it in config as well
+                       setConfigEntry($entry, $values[$idx]);
+               } // END - foreach
+
+               // Remove last comma
+               $entries = substr($all, 0, -1);
+       } elseif (!empty($updateMode)) {
+               // Update mode set
+               // @TODO Find a way for updating $_CONFIG here
+               $entries .= sprintf("=%s%s%s", $entries, $updateMode, (float)$values);
        } else {
-               // Load config from DB
-               $result_config = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_config WHERE config=%d LIMIT 1",
-                       array(bigintval($no)), __FILE__, __LINE__);
+               // Set it in config first
+               setConfigEntry($entries, $values);
 
-               // Get config from database
-               $CFG_DUMMY = SQL_FETCHARRAY($result_config);
+               // Regular entry to update
+               $entries .= sprintf("='%s'", SQL_ESCAPE($values));
+       }
 
-               // Free result
-               SQL_FREERESULT($result_config);
+       // Run database update
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "entries={$entries}");
+       SQL_QUERY("UPDATE `{!_MYSQL_PREFIX!}_config` SET ".$entries." WHERE config=0 LIMIT 1", __FUNCTION__, __LINE__);
+
+       // Get affected rows
+       $affectedRows = SQL_AFFECTEDROWS();
+       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):entries={$entries},affectedRows={$affectedRows}<br />\n";
+
+       // Rebuild cache
+       rebuildCacheFiles('config', 'config');
+}
+
+// Prepares an SQL statement part for HTML mail and/or holiday depency
+// @TODO Can this be rewritten to a filter?
+function PREPARE_SQL_HTML_HOLIDAY ($mode) {
+       // Exclude no users by default
+       $MORE = '';
+
+       // HTML mail?
+       if ($mode == 'html') $MORE = " AND `html`='Y'";
+       if (GET_EXT_VERSION('holiday') >= '0.1.3') {
+               // Add something for the holiday extension
+               $MORE .= " AND `holiday_active`='N'";
+       } // END - if
+
+       // Return result
+       return $MORE;
+}
+
+// "Getter" for total available receivers
+function getTotalReceivers ($mode='normal') {
+       // Query database
+       $result_all = SQL_QUERY("SELECT userid
+FROM `{!_MYSQL_PREFIX!}_user_data`
+WHERE `status`='CONFIRMED' AND receive_mails > 0 ".PREPARE_SQL_HTML_HOLIDAY($mode),
+       __FUNCTION__, __LINE__);
+
+       // Get num rows
+       $numRows = SQL_NUMROWS($result_all);
 
-               // Remember this config in the array
-               $cacheArray['config'][$no] = $CFG_DUMMY;
+       // Free result
+       SQL_FREERESULT($result_all);
+
+       // Return value
+       return $numRows;
+}
+
+// Returns HTML code with an "<option> list" of all categories
+function generateCategoryOptionsList ($mode) {
+       // Prepare WHERE statement
+       $whereStatement = " WHERE `visible`='Y'";
+       if (IS_ADMIN()) $whereStatement = '';
+
+       // Initialize array...
+       $CATS = array(
+               'id'   => array(),
+               'name' => array(),
+               'uids' => array()
+       );
+
+       // Get categories
+       $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 ($content = SQL_FETCHARRAY($result)) {
+                       // Transfer some data
+                       $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($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__);
+
+                               // Add user count
+                               $uid_cnt += SQL_NUMROWS($result_ver);
+
+                               // Free memory
+                               SQL_FREERESULT($result_ver);
+                       } // END - while
+
+                       // Free memory
+                       SQL_FREERESULT($result_uids);
+
+                       // Add counter
+                       $CATS['uids'][] = $uid_cnt;
+               } // END - while
+
+               // Free memory
+               SQL_FREERESULT($result);
+
+               // 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['uids'][$key] . ' {--USER_IN_CAT--})</option>';
+               } // END - foreach
+       } else {
+               // No cateogries are defined yet
+               $OUT = '<option class="member_failed">{!MEMBER_NO_CATS!}</option>';
        }
 
-       // Return config array
-       return $CFG_DUMMY;
+       // Return HTML code
+       return $OUT;
 }
-// Gets the matching what name from module
-function GET_WHAT($MOD_CHECK)
-{
-       $wht = "";
-       //* DEBUG: */ echo __LINE__."!".$MOD_CHECK."!<br />\n";
-       switch ($MOD_CHECK)
-       {
-       case "admin":
-               $wht = "overview";
-               break;
-
-       case "login":
-       case "index":
-               $wht = "welcome";
-               break;
-
-       default:
-               $wht = "";
-               break;
+
+// Add bonus mail to queue
+function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $cat, $mode='normal', $receiver=0) {
+       // Is admin or bonus extension there?
+       if (!IS_ADMIN()) {
+               // Abort here
+               return false;
+       } elseif (!EXT_IS_ACTIVE('bonus')) {
+               // Abort here
+               return false;
        }
 
-       // Return what value
-       return $wht;
+       // Calculcate target sent
+       $target = countSelection(explode(';', $receiverList));
+
+       // Receiver is zero?
+       if ($receiver == 0) {
+               // Then auto-fix it
+               $receiver = $target;
+       } // END - if
+
+       // HTML extension active?
+       if (EXT_IS_ACTIVE('html_mail')) {
+               // No HTML by default
+               $HTML = 'N';
+
+               // HTML mode?
+               if ($mode == 'html') $HTML = 'Y';
+
+               // Add HTML mail
+               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_bonus`
+(subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent, html_msg)
+VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s','%s')",
+               array(
+               $subject,
+               $text,
+               $receiverList,
+               $points,
+               $seconds,
+               $url,
+               $cat,
+               $target,
+               bigintval($receiver),
+               $HTML
+               ), __FUNCTION__, __LINE__);
+       } else {
+               // Add regular mail
+               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_bonus`
+(subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, mails_sent)
+VALUES ('%s','%s','%s','%s','%s','NEW', UNIX_TIMESTAMP(),'%s','%s','%s','%s')",
+               array(
+               $subject,
+               $text,
+               $receiverList,
+               $points,
+               $seconds,
+               $url,
+               $cat,
+               $target,
+               bigintval($receiver),
+               ), __FUNCTION__, __LINE__);
+       }
 }
-//
-function MODULE_HAS_MENU($mod)
-{
-       global $cacheArray, $_CONFIG;
 
-       // All is false by default
-       $ret = false;
-       if (GET_EXT_VERSION("cache") >= "0.1.2")
-       {
-               if (isset($cacheArray['modules']['has_menu'][$mod]))
-               {
-                       // Check module cache and count hit
-                       if ($cacheArray['modules']['has_menu'][$mod] == 'Y') $ret = true;
-                       $_CONFIG['cache_hits']++;
-               }
-                elseif (isset($cacheArray['extensions']['ext_menu'][$mod]))
-               {
-                       // Check cache and count hit
-                       if ($cacheArray['extensions']['ext_menu'][$mod] == 'Y') $ret = true;
-                       $_CONFIG['cache_hits']++;
-               }
+// Generate a receiver list for given category and maximum receivers
+function generateReceiverList ($cat, $receiver, $mode = '') {
+       // Init variables
+       $CAT_TABS     = "%s";
+       $CAT_WHERE    = '';
+       $receiverList = '';
+       $result       = false;
+
+       // Secure data
+       $cat      = bigintval($cat);
+       $receiver = bigintval($receiver);
+
+       // Is the receiver zero and mode set?
+       if (($receiver == 0) && (!empty($mode))) {
+               // Auto-fix receiver maximum
+               $receiver = getTotalReceivers($mode);
+       } // END - if
+
+       // Category given?
+       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";
+       } // END - if
+
+       // Exclude users in holiday?
+       if (GET_EXT_VERSION('holiday') >= '0.1.3') {
+               // Add something for the holiday extension
+               $CAT_WHERE .= " AND d.`holiday_active`='N'";
+       } // END - if
+
+       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__);
+       } 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__);
        }
-       if ((GET_EXT_VERSION("sql_patches") >= "0.3.6") && ($ret === false))
-       {
-               // Check database for entry
-               $result = SQL_QUERY_ESC("SELECT has_menu FROM "._MYSQL_PREFIX."_mod_reg WHERE module='%s' LIMIT 1",
-                array($mod), __FILE__, __LINE__);
-               if (SQL_NUMROWS($result) == 1)
-               {
-                       list($has_menu) = SQL_FETCHROW($result);
-                       if ($has_menu == 'Y') $ret = true;
-               }
+
+       // Entries found?
+       if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
+               // Load all entries
+               while ($content = SQL_FETCHARRAY($result)) {
+                       // Add receiver when not empty
+                       if (!empty($content['userid'])) $receiverList .= $content['userid'] . ';';
+               } // END - while
 
                // Free memory
                SQL_FREERESULT($result);
-       } elseif (GET_EXT_VERSION("sql_patches") == "") {
-               // No sql_patches installed, so maybe in admin area?
-               if ((IS_ADMIN()) && ($mod == "admin")) return true; // Then there is a menu!
+
+               // Remove trailing semicolon
+               $receiverList = substr($receiverList, 0, -1);
+       } // END - if
+
+       // Return list
+       return $receiverList;
+}
+
+// Get timestamp for given stats type and data
+function getTimestampFromUserStats ($type, $data, $uid = 0) {
+       // Default timestamp is zero
+       $stamp = 0;
+
+       // User id set?
+       if ((isUserIdSet()) && ($uid == 0)) {
+               $uid = getUserId();
+       } // END - if
+
+       // Is the extension installed and updated?
+       if ((!EXT_IS_ACTIVE('sql_patches')) || (EXT_VERSION_IS_OLDER('sql_patches', '0.5.6'))) {
+               // Return zero here
+               return $stamp;
+       } // END - if
+
+       // Try to find the entry
+       $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`inserted`) AS `stamp`
+FROM `{!_MYSQL_PREFIX!}_user_stats_data`
+WHERE userid=%s AND stats_type='%s' AND stats_data='%s'
+LIMIT 1",
+       array(bigintval($uid), $type, $data), __FUNCTION__, __LINE__);
+
+       // Is the entry there?
+       if (SQL_NUMROWS($result) == 1) {
+               // Get this stamp
+               list($stamp) = SQL_FETCHROW($result);
+       } // END - if
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return stamp
+       return $stamp;
+}
+
+// Inserts user stats
+function insertUserStatsRecord ($uid, $type, $data) {
+       // Is the extension installed and updated?
+       if ((!EXT_IS_ACTIVE('sql_patches')) || (EXT_VERSION_IS_OLDER('sql_patches', '0.5.6'))) {
+               // Return zero here
+               return false;
+       } // END - if
+
+       // Does it exist?
+       if ((!getTimestampFromUserStats($type, $data, $uid)) && (!is_array($data))) {
+               // Then insert it!
+               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
+               array(bigintval($uid), $type, $data), __FUNCTION__, __LINE__);
+       } elseif (is_array($data)) {
+               // Invalid data!
+               DEBUG_LOG(__FUNCTION__, __LINE__, " uid={$uid},type={$type},data={".gettype($data).": Invalid statistics data type!");
        }
+}
 
-       // Return status
-       return $ret;
+// "Getter" for array for user refs and points in given level
+function getUserReferalPoints ($uid, $level) {
+       //* DEBUG: */ print "----------------------- <font color=\"#00aa00\">".__FUNCTION__." - ENTRY</font> ------------------------<ul><li>\n";
+       // Default is no refs and no nickname
+       $add = '';
+       $refs = array();
+
+       // Do we have nickname extension installed?
+       if (EXT_IS_ACTIVE('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."
+FROM `{!_MYSQL_PREFIX!}_user_refs` AS ur
+LEFT JOIN `{!_MYSQL_PREFIX!}_user_points` AS up
+ON ur.refid=up.userid AND ur.level=0
+LEFT JOIN `{!_MYSQL_PREFIX!}_user_data` AS ud
+ON ur.refid=ud.userid
+WHERE ur.userid=%s AND ur.level=%s
+ORDER BY ur.refid ASC",
+       array(bigintval($uid), bigintval($level)), __FUNCTION__, __LINE__);
+
+       // Are there some entries?
+       if (SQL_NUMROWS($result) > 0) {
+               // Fetch all entries
+               while ($row = SQL_FETCHARRAY($result)) {
+                       // Get total points of this user
+                       $row['points'] = GET_TOTAL_DATA($row['refid'], 'user_points', 'points') - GET_TOTAL_DATA($row['refid'], 'user_data', 'used_points');
+
+                       // Get unconfirmed mails
+                       $row['unconfirmed']  = GET_TOTAL_DATA($row['refid'], 'user_links', 'id', 'userid', true);
+
+                       // Init clickrate with zero
+                       $row['clickrate'] = 0;
+
+                       // Is at least one mail received?
+                       if ($row['emails_received'] > 0) {
+                               // Calculate clickrate
+                               $row['clickrate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
+                       } // END - if
+
+                       // Activity is 'active' by default because if autopurge is not installed
+                       $row['activity'] = getMessage('MEMBER_ACTIVITY_ACTIVE');
+
+                       // Is autopurge installed and the user inactive?
+                       if ((EXT_IS_ACTIVE('autopurge')) && ((time() - getConfig('ap_inactive_since')) >= $row['last_online']))  {
+                               // Inactive user!
+                               $row['activity'] = getMessage('MEMBER_ACTIVITY_INACTIVE');
+                       } // END - if
+
+                       // Remove some entries
+                       unset($row['mails_confirmed']);
+                       unset($row['emails_received']);
+                       unset($row['last_online']);
+
+                       // Add row
+                       $refs[$row['id']] = $row;
+               } // END - while
+       } // END - if
+
+       // Free result
+       SQL_FREERESULT($result);
+
+       // Return result
+       //* DEBUG: */ print "</li></ul>----------------------- <font color=\"#aa0000\">".__FUNCTION__." - EXIT</font> ------------------------<br />\n";
+       return $refs;
 }
 
-//
+// Recuce the amount of received emails for the receipients for given email
+function reduceRecipientReceivedMails ($column, $id, $count) {
+       // Search for mail in database
+       $result = SQL_QUERY_ESC("SELECT `userid` FROM `{!_MYSQL_PREFIX!}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
+       array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
+
+       // 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;
+               } // END - while
+
+               // Now update all user accounts
+               SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
+               array(implode(',', $UIDs), count($UIDs)), __FUNCTION__, __LINE__);
+       } // END - if
+
+       // Free result
+       SQL_FREERESULT($result);
+}
+
+// Init SQLs array
+function INIT_SQLS () {
+       SET_SQLS(array());
+}
+
+// Checks wether the sqls array is initialized
+function IS_SQLS_INITIALIZED () {
+       return ((isset($GLOBALS['sqls'])) && (is_array($GLOBALS['sqls'])));
+}
+
+// Setter for SQLs array
+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'];
+}
+
+// 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;
+}
+
+// Setter for SQLs key
+function SET_SQL_KEY ($key, $value) {
+       $GLOBALS['sqls'][$key] = (string) $value;
+}
+
+// Merge SQLs together
+function MERGE_SQLS ($SQLs) {
+       SET_SQLS(merge_array(GET_SQLS(), $SQLs));
+}
+
+// Counter for SQLs array
+function COUNT_SQLS () {
+       // Default is false
+       $count = false;
+
+       // Is the array there?
+       if (IS_SQLS_INITIALIZED()) {
+               // Then count it
+               $count = count($GLOBALS['sqls']);
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("count=%d", $count));
+       } // END - if
+
+       // Return it
+       return $count;
+}
+
+// Checks wether the SQLs array is filled
+function IS_SQLS_VALID () {
+       return (
+       (IS_SQLS_INITIALIZED()) &&
+       (COUNT_SQLS() > 0)
+       );
+}
+
+// [EOF]
 ?>