Cases (switch command) on numbers fixed, German language strings fixed
[mailer.git] / inc / functions.php
index 8ac91e556901e68696ead6e560043abac61bc4ca..dce5f6d7af0763d8fd08e702e2199e24ca399f0e 100644 (file)
@@ -17,7 +17,7 @@
  * 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                           *
+ * Copyright (c) 2003 - 2009 by Roland Haeder                           *
  * For more information visit: http://www.mxchange.org                  *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
  * MA  02110-1301  USA                                                  *
  ************************************************************************/
+
 // Some security stuff...
 if (!defined('__SECURITY')) {
-       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
-       require($INC);
-}
+       die();
+} // END - if
 
 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
-function OUTPUT_HTML ($HTML, $newLine = true) {
-       // Some global variables
-       global $OUTPUT;
+function outputHtml ($htmlCode, $newLine = true) {
+       // Init output
+       if (!isset($GLOBALS['output'])) $GLOBALS['output'] = '';
+
+       // Transfer username
+       $username = getMessage('USERNAME_UNKNOWN');
+       if (isset($GLOBALS['username'])) $username = getUsername();
 
        // Do we have HTML-Code here?
-       if (!empty($HTML)) {
+       if (!empty($htmlCode)) {
                // Yes, so we handle it as you have configured
-               switch (getConfig('OUTPUT_MODE'))
-               {
+               switch (getConfig('OUTPUT_MODE')) {
                        case 'render':
                                // That's why you don't need any \n at the end of your HTML code... :-)
-                               if (constant('_OB_CACHING') == 'on') {
+                               if (getPhpCaching() == 'on') {
                                        // Output into PHP's internal buffer
-                                       outputRawCode($HTML);
+                                       outputRawCode($htmlCode);
 
                                        // That's why you don't need any \n at the end of your HTML code... :-)
-                                       if ($newLine) echo "\n";
+                                       if ($newLine === true) print("\n");
                                } else {
                                        // Render mode for old or lame servers...
-                                       $OUTPUT .= $HTML;
+                                       $GLOBALS['output'] .= $htmlCode;
 
                                        // That's why you don't need any \n at the end of your HTML code... :-)
-                                       if ($newLine) $OUTPUT .= "\n";
+                                       if ($newLine === true) $GLOBALS['output'] .= "\n";
                                }
                                break;
 
                        case 'direct':
                                // If we are switching from render to direct output rendered code
-                               if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != 'on')) { outputRawCode($OUTPUT); $OUTPUT = ''; }
+                               if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
 
                                // The same as above... ^
-                               outputRawCode($HTML);
-                               if ($newLine) echo "\n";
+                               outputRawCode($htmlCode);
+                               if ($newLine) print("\n");
                                break;
 
                        default:
                                // Huh, something goes wrong or maybe you have edited config.php ???
-                               app_die(__FUNCTION__, __LINE__, "<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
+                               app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
                                break;
-               }
-       } elseif ((constant('_OB_CACHING') == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
+               } // END - switch
+       } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
                // Headers already sent?
                if (headers_sent()) {
                        // Log this error
-                       DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
+                       logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
 
                        // Trigger an user error
-                       debug_report_bug("Headers are already sent!");
+                       debug_report_bug('Headers are already sent!');
                } // END - if
 
                // Output cached HTML code
-               $OUTPUT = ob_get_contents();
+               $GLOBALS['output'] = ob_get_contents();
 
                // Clear output buffer for later output if output is found
-               if (!empty($OUTPUT)) {
+               if (!empty($GLOBALS['output'])) {
                        clearOutputBuffer();
                } // END - if
 
@@ -112,56 +115,63 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
                sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
                sendHeader('Pragma: no-cache'); // HTTP/1.0
                sendHeader('Connection: Close');
+               sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
+               sendHeader('Content-language: ' . getLanguage());
 
                // Extension 'rewrite' installed?
-               if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
-                       $OUTPUT = rewriteLinksInCode($OUTPUT);
+               if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
+                       $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
-               // Compile and run finished rendered HTML code
-               while (strpos($OUTPUT, '{!') > 0) {
-                       // Replace _MYSQL_PREFIX
-                       $OUTPUT = str_replace("{!_MYSQL_PREFIX!}", getConfig('_MYSQL_PREFIX'), $OUTPUT);
+               // Init counter
+               $cnt = '0';
 
+               // Compile and run finished rendered HTML code
+               while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
                        // Prepare the content and eval() it...
+                       $content = array();
                        $newContent = '';
-                       $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
+
+                       // Compile it
+                       $eval = "\$newContent = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";";
                        eval($eval);
 
                        // Was that eval okay?
                        if (empty($newContent)) {
                                // Something went wrong!
-                               app_die(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
+                               debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>');
                        } // END - if
-                       $OUTPUT = $newContent;
+                       $GLOBALS['output'] = $newContent;
+
+                       // Count round
+                       $cnt++;
                } // END - while
 
                // Output code here, DO NOT REMOVE! ;-)
-               outputRawCode($OUTPUT);
-       } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
+               outputRawCode($GLOBALS['output']);
+       } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
                // Rewrite links when rewrite extension is active
-               if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
-                       $OUTPUT = rewriteLinksInCode($OUTPUT);
+               if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
+                       $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
                // Compile and run finished rendered HTML code
-               while (strpos($OUTPUT, '{!') > 0) {
-                       $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
-                       eval($eval);
+               while (strpos($GLOBALS['output'], '{!') > 0) {
+                       eval("\$GLOBALS['output'] = \"".compileCode(smartAddSlashes($GLOBALS['output']))."\";");
                } // END - while
 
                // Output code here, DO NOT REMOVE! ;-)
-               outputRawCode($OUTPUT);
+               outputRawCode($GLOBALS['output']);
        }
 }
 
 // Output the raw HTML code
-function outputRawCode ($HTML) {
+function outputRawCode ($htmlCode) {
        // Output stripped HTML code to avoid broken JavaScript code, etc.
-       echo stripslashes(stripslashes($HTML));
+       print(stripslashes(stripslashes($htmlCode)));
 
-       // Flush the output if only constant('_OB_CACHING') is not 'on'
-       if (constant('_OB_CACHING') != 'on') {
+       // Flush the output if only getPhpCaching() is not 'on'
+       if (getPhpCaching() != 'on') {
                // Flush it
                flush();
        } // END - if
@@ -191,13 +201,14 @@ function addFatalMessage ($F, $L, $message, $extra='') {
        $GLOBALS['fatal_messages'][] = $message;
 
        // Log fatal messages away
-       DEBUG_LOG($F, $L, " message={$message}");
+       debug_report_bug($message);
+       logDebugMessage($F, $L, " message={$message}");
 }
 
 // Getter for total fatal message count
 function getTotalFatalErrors () {
        // Init coun
-       $count = 0;
+       $count = '0';
 
        // Do we have at least the first entry?
        if (!empty($GLOBALS['fatal_messages'][0])) {
@@ -210,266 +221,396 @@ function getTotalFatalErrors () {
 }
 
 // Load a template file and return it's content (only it's name; do not use ' or ")
-function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
+function loadTemplate ($template, $return=false, $content=array()) {
        // @TODO Remove this sanity-check if all is fine
        if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
 
-       // Add more variables which you want to use in your template files
-       global $DATA, $username;
+       // @TODO Try to rewrite all $DATA to $content
+       global $DATA;
+
+       // Do we have cache?
+       if (isTemplateCached($template)) {
+               // Evaluate the cache
+               eval(readTemplateCache($template));
+       } elseif (!isset($GLOBALS['template_eval'][$template])) {
+               // Add more variables which you want to use in your template files
+               $username = getUsername();
 
-       // Get whole config array
-       $_CONFIG = getConfigArray();
+               // Make all template names lowercase
+               $template = strtolower($template);
 
-       // Make all template names lowercase
+               // Count the template load
+               incrementConfigEntry('num_templates');
+
+               // Init some data
+               $ret = '';
+               if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
+
+               // Base directory
+               $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
+               $mode = '';
+
+               // Check for admin/guest/member templates
+               if (substr($template, 0, 6) == 'admin_') {
+                       // Admin template found
+                       $mode = 'admin/';
+               } elseif (substr($template, 0, 6) == 'guest_') {
+                       // Guest template found
+                       $mode = 'guest/';
+               } elseif (substr($template, 0, 7) == 'member_') {
+                       // Member template found
+                       $mode = 'member/';
+               } elseif (substr($template, 0, 8) == 'install_') {
+                       // Installation template found
+                       $mode = 'install/';
+               } elseif (substr($template, 0, 4) == 'ext_') {
+                       // Extension template found
+                       $mode = 'ext/';
+               } elseif (substr($template, 0, 3) == 'la_') {
+                       // 'Logical-area' template found
+                       $mode = 'la/';
+               } elseif (substr($template, 0, 3) == 'js_') {
+                       // JavaScript template found
+                       $mode = 'js/';
+               } elseif (substr($template, 0, 5) == 'menu_') {
+                       // Menu template found
+                       $mode = 'menu/';
+               } else {
+                       // Test for extension
+                       $test = substr($template, 0, strpos($template, '_'));
+
+                       // Probe for valid extension name
+                       if (isExtensionNameValid($test)) {
+                               // Set extra path to extension's name
+                               $mode = $test . '/';
+                       } // END - if
+               }
+
+               ////////////////////////
+               // Generate file name //
+               ////////////////////////
+               $FQFN = $basePath . $mode . $template . '.tpl';
+
+               if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
+                       // Select what depended header/footer template file for admin/guest/member area
+                       $file2 = sprintf("%s%s%s_%s.tpl",
+                               $basePath,
+                               $mode,
+                               $template,
+                               getWhat()
+                       );
+
+                       // Probe for it...
+                       if (isFileReadable($file2)) $FQFN = $file2;
+
+                       // Remove variable from memory
+                       unset($file2);
+               } // END - if
+
+               // Does the special template exists?
+               if (!isFileReadable($FQFN)) {
+                       // Reset to default template
+                       $FQFN = $basePath . $template . '.tpl';
+               } // END - if
+
+               // Now does the final template exists?
+               if (isFileReadable($FQFN)) {
+                       // The local file does exists so we load it. :)
+                       $GLOBALS['tpl_content'] = readFromFile($FQFN);
+
+                       // Replace ' to our own chars to preventing them being quoted
+                       while (strpos($GLOBALS['tpl_content'], "'") !== false) { $GLOBALS['tpl_content'] = str_replace("'", '{QUOT}', $GLOBALS['tpl_content']); }
+
+                       // Do we have to compile the code?
+                       $ret = '';
+                       if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
+                               // Normal HTML output?
+                               if (getOutputMode() == '0') {
+                                       // Add surrounding HTML comments to help finding bugs faster
+                                       $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
+
+                                       // Prepare eval() command
+                                       $eval = '$ret = "' . compileCode(smartAddSlashes($ret)) . '";';
+                               } elseif (substr($template, 0, 3) == 'js_') {
+                                       // JavaScripts don't like entities
+                                       $eval = '$ret = decodeEntities("' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '");';
+                               } else {
+                                       // Prepare eval() command
+                                       $eval = '$ret = "' . compileCode(smartAddSlashes($GLOBALS['tpl_content'])) . '";';
+                               }
+                       } else {
+                               // Add surrounding HTML comments to help finding bugs faster
+                               $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
+                               $eval = '$ret = "' . smartAddSlashes($ret) . '";';
+                       } // END - if
+
+                       // Cache the eval() command here
+                       $GLOBALS['template_eval'][$template] = $eval;
+
+                       // Eval the code
+                       eval($GLOBALS['template_eval'][$template]);
+               } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
+                       // Only admins shall see this warning or when installation mode is active
+                       $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
+(' . $template . ')<br />
+<br />
+{--TEMPLATE_CONTENT--}
+<pre>' . print_r($content, true) . '</pre>
+{--TEMPLATE_DATA--}
+<pre>' . print_r($DATA, true) . '</pre>
+<br /><br />';
+               } else {
+                       // No file!
+                       $GLOBALS['template_eval'][$template] = '404';
+               }
+       } else {
+               // Eval the code
+               eval($GLOBALS['template_eval'][$template]);
+       }
+
+       // Do we have some content to output or return?
+       if (!empty($ret)) {
+               // Not empty so let's put it out! ;)
+               if ($return === true) {
+                       // Return the HTML code
+                       return $ret;
+               } else {
+                       // Output directly
+                       outputHtml($ret);
+               }
+       } elseif (isDebugModeEnabled()) {
+               // Warning, empty output!
+               return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
+       }
+}
+
+// Loads an email template and compiles it
+function loadEmailTemplate ($template, $content = array(), $UID = '0') {
+       global $DATA;
+
+       // Make sure all template names are lowercase!
        $template = strtolower($template);
 
-       // Count the template load
-       incrementConfigEntry('num_templates');
+       // Default 'nickname' if extension is not installed
+       $nick = '---';
 
        // Prepare IP number and User Agent
        $REMOTE_ADDR     = detectRemoteAddr();
-       if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
        $HTTP_USER_AGENT = detectUserAgent();
 
-       // Init some data
-       $ret = '';
-       if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
+       // Default admin
+       $ADMIN = getConfig('MAIN_TITLE');
 
-       // @DEPRECATED Try to rewrite the if() condition
-       if ($template == 'member_support_form') {
-               // Support request of a member
-               $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
-                       array(getUserId()), __FUNCTION__, __LINE__);
+       // Is the admin logged in?
+       if (isAdmin()) {
+               // Get admin id
+               $adminId = getCurrentAdminId();
+
+               // Load Admin data
+               $ADMIN = getAdminEmail($adminId);
+       } // END - if
+
+       // Neutral email address is default
+       $email = getConfig('WEBMASTER');
+
+       // Expiration in a nice output format
+       // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
+       if (getConfig('auto_purge') == '0') {
+               // Will never expire!
+               $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
+       } else {
+               // Create nice date string
+               $EXPIRATION = createFancyTime(getConfig('auto_purge'));
+       }
 
-               // Is content an array?
-               if (is_array($content)) {
-                       // Merge data
-                       $content = merge_array($content, SQL_FETCHARRAY($result));
+       // Is content an array?
+       if (is_array($content)) {
+               // Add expiration to array, $EXPIRATION is now deprecated!
+               $content['expiration'] = $EXPIRATION;
+       } // END - if
 
-                       // Translate gender
-                       $content['gender'] = translateGender($content['gender']);
+       // Load user's data
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
+       if (($UID > 0) && (is_array($content))) {
+               // If nickname extension is installed, fetch nickname as well
+               if (isNicknameUsed($UID)) {
+                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
+                       // Load by nickname
+                       fetchUserData($UID, 'nickname');
                } else {
-                       // @DEPRECATED
-                       // @TODO Find all templates which are using these direct variables and rewrite them.
-                       // @TODO After this step is done, this else-block is history
-                       list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
-
-                       // Translate gender
-                       $gender = translateGender($gender);
-                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
+                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
+                       /// Load by userid
+                       fetchUserData($UID);
                }
 
-               // Free result
-               SQL_FREERESULT($result);
+               // Merge data if valid
+               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
+               if (isUserDataValid()) {
+                       $content = merge_array($content, getUserDataArray());
+               } // END - if
+               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
        } // END - if
 
-       // Generate date/time string
-       $date_time = generateDateTime(time(), '1');
+       // Translate M to male or F to female if present
+       if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
+
+       // Overwrite email from data if present
+       if (isset($content['email'])) $email = $content['email'];
+
+       // Store email for some functions in global data array
+       $DATA['email'] = $email;
 
        // Base directory
-       $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
-       $mode = '';
+       $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
 
        // Check for admin/guest/member templates
-       if (strpos($template, 'admin_') > -1) {
+       if (substr($template, 0, 6) == 'admin_') {
                // Admin template found
-               $mode = 'admin/';
-       } elseif (strpos($template, 'guest_') > -1) {
+               $FQFN = $basePath.'admin/' . $template.'.tpl';
+       } elseif (substr($template, 0, 6) == 'guest_') {
                // Guest template found
-               $mode = 'guest/';
-       } elseif (strpos($template, 'member_') > -1) {
+               $FQFN = $basePath.'guest/' . $template.'.tpl';
+       } elseif (substr($template, 0, 7) == 'member_') {
                // Member template found
-               $mode = 'member/';
-       } elseif (strpos($template, 'install_') > -1) {
-               // Installation template found
-               $mode = 'install/';
-       } elseif (strpos($template, 'ext_') > -1) {
-               // Extension template found
-               $mode = 'ext/';
-       } elseif (strpos($template, 'la_') > -1) {
-               // 'Logical-area' template found
-               $mode = 'la/';
-       } elseif (strpos($template, 'js_') > -1) {
-               // JavaScript template found
-               $mode = 'js/';
+               $FQFN = $basePath.'member/' . $template.'.tpl';
        } else {
                // Test for extension
                $test = substr($template, 0, strpos($template, '_'));
-               if (EXT_IS_ACTIVE($test)) {
+               if (isExtensionNameValid($test)) {
                        // Set extra path to extension's name
-                       $mode = $test . '/';
-               } // END - if
+                       $FQFN = $basePath . $test.'/' . $template.'.tpl';
+               } else {
+                       // No special filename
+                       $FQFN = $basePath . $template.'.tpl';
+               }
        }
 
-       ////////////////////////
-       // Generate file name //
-       ////////////////////////
-       $FQFN = $basePath . $mode . $template . '.tpl';
-
-       if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
-               // Select what depended header/footer template file for admin/guest/member area
-               $file2 = sprintf("%s%s%s_%s.tpl",
-                       $basePath,
-                       $mode,
-                       $template,
-                       getWhat()
-               );
-
-               // Probe for it...
-               if (isFileReadable($file2)) $FQFN = $file2;
-
-               // Remove variable from memory
-               unset($file2);
-       } // END - if
-
        // Does the special template exists?
        if (!isFileReadable($FQFN)) {
                // Reset to default template
-               $FQFN = $basePath . $template . '.tpl';
+               $FQFN = $basePath . $template.'.tpl';
        } // END - if
 
        // Now does the final template exists?
+       $newContent = '';
        if (isFileReadable($FQFN)) {
                // The local file does exists so we load it. :)
-               $tmpl_file = readFromFile($FQFN);
-
-               // Replace ' to our own chars to preventing them being quoted
-               while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
-
-               // Do we have to compile the code?
-               $ret = '';
-               if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
-                       // Okay, compile it!
-                       $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
-                       eval($tmpl_file);
-               } else {
-                       // Simply return loaded code
-                       $ret = $tmpl_file;
-               }
+               $GLOBALS['tpl_content'] = readFromFile($FQFN);
 
-               // Normal HTML output?
-               if ($GLOBALS['output_mode'] == 0) {
-                       // Add surrounding HTML comments to help finding bugs faster
-                       $ret = "<!-- Template " . $template . " - Start -->\n" . $ret . "<!-- Template " . $template . " - End -->\n";
-               } // END - if
-       } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
-               // Only admins shall see this warning or when installation mode is active
-               $ret = "<br /><span class=\"guest_failed\">{--TEMPLATE_404--}</span><br />
-(".basename($FQFN).")<br />
-<br />
+               // Run code
+               $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode(smartAddSlashes($GLOBALS['tpl_content']))."\");";
+               eval($GLOBALS['tpl_content']);
+       } elseif (!empty($template)) {
+               // Template file not found!
+               $newContent = "{--TEMPLATE_404--}: " . $template."<br />
 {--TEMPLATE_CONTENT--}
 <pre>".print_r($content, true)."</pre>
 {--TEMPLATE_DATA--}
 <pre>".print_r($DATA, true)."</pre>
 <br /><br />";
+
+               // Debug mode not active? Then remove the HTML tags
+               if (!isDebugModeEnabled()) $newContent = secureString($newContent);
+       } else {
+               // No template name supplied!
+               $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
        }
 
+       // Is there some content?
+       if (empty($newContent)) {
+               // Compiling failed
+               $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
+               // Add last error if the required function exists
+               if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
+       } // END - if
+
        // Remove content and data
        unset($content);
        unset($DATA);
 
-       // Do we have some content to output or return?
-       if (!empty($ret)) {
-               // Not empty so let's put it out! ;)
-               if ($return === true) {
-                       // Return the HTML code
-                       return $ret;
-               } else {
-                       // Output direct
-                       OUTPUT_HTML($ret);
-               }
-       } elseif (isDebugModeEnabled()) {
-               // Warning, empty output!
-               return "E:" . $template."<br />\n";
-       }
+       // Compile the code and eval it
+       $eval = '$newContent = "' . compileRawCode(smartAddSlashes($newContent)) . '";';
+       eval($eval);
+
+       // Return content
+       return $newContent;
 }
 
 // Send mail out to an email address
-function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
+function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
 
        // Compile subject line (for POINTS constant etc.)
-       $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
-       eval($eval);
+       eval("\$subject = decodeEntities(\"".compileRawCode(smartAddSlashes($subject))."\");");
 
        // Set from header
        if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
                // Value detected, is the message extension installed?
                // @TODO Extension 'msg' does not exist
-               if (EXT_IS_ACTIVE('msg')) {
-                       ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
+               if (isExtensionActive('msg')) {
+                       ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
                        return;
                } else {
-                       // Load email address
-                       $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(bigintval($toEmail)), __FUNCTION__, __LINE__);
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
-
                        // Does the user exist?
-                       if (SQL_NUMROWS($result_email)) {
-                               // Load email address
-                               list($toEmail) = SQL_FETCHROW($result_email);
+                       if (fetchUserData($toEmail)) {
+                               // Get the email
+                               $toEmail = getUserData('email');
                        } else {
                                // Set webmaster
-                               $toEmail = constant('WEBMASTER');
+                               $toEmail = getConfig('WEBMASTER');
                        }
-
-                       // Free result
-                       SQL_FREERESULT($result_email);
                }
        } elseif ($toEmail == '0') {
                // Is the webmaster!
-               $toEmail = constant('WEBMASTER');
+               $toEmail = getConfig('WEBMASTER');
        }
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
 
        // Check for PHPMailer or debug-mode
        if (!checkPhpMailerUsage()) {
                // Not in PHPMailer-Mode
                if (empty($mailHeader)) {
                        // Load email header template
-                       $mailHeader = LOAD_EMAIL_TEMPLATE('header');
+                       $mailHeader = loadEmailTemplate('header');
                } else {
                        // Append header
-                       $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
+                       $mailHeader .= loadEmailTemplate('header');
                }
        } elseif (isDebugModeEnabled()) {
                if (empty($mailHeader)) {
                        // Load email header template
-                       $mailHeader = LOAD_EMAIL_TEMPLATE('header');
+                       $mailHeader = loadEmailTemplate('header');
                } else {
                        // Append header
-                       $mailHeader .= LOAD_EMAIL_TEMPLATE('header');
+                       $mailHeader .= loadEmailTemplate('header');
                }
        }
 
        // Compile "TO"
-       $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
-       eval($eval);
+       eval("\$toEmail = \"".compileRawCode(smartAddSlashes($toEmail))."\";");
 
        // Compile "MSG"
-       $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
-       eval($eval);
+       eval("\$message = \"".compileRawCode(smartAddSlashes($message))."\";");
 
        // Fix HTML parameter (default is no!)
-       if (empty($HTML)) $HTML = 'N';
+       if (empty($isHtml)) $isHtml = 'N';
        if (isDebugModeEnabled()) {
                // In debug mode we want to display the mail instead of sending it away so we can debug this part
-               OUTPUT_HTML("<pre>
-".htmlentities(trim($mailHeader))."
-To      : " . $toEmail."
-Subject : " . $subject."
-Message : " . $message."
-</pre>\n");
-       } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
+               outputHtml('<pre>
+Headers : ' . str_replace('<', '&lt', str_replace('>', '&gt;', htmlentities(trim($mailHeader)))) . '
+To      : ' . $toEmail . '
+Subject : ' . $subject . '
+Message : ' . $message . '
+</pre>');
+       } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
                // Send mail as HTML away
                sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
        } elseif (!empty($toEmail)) {
                // Send Mail away
                sendRawEmail($toEmail, $subject, $message, $mailHeader);
-       } elseif ($HTML == 'N') {
+       } elseif ($isHtml != 'Y') {
                // Problem found!
-               sendRawEmail(constant('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
+               sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
        }
 }
 
@@ -490,7 +631,12 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
 
                // get new instance
                $mail = new PHPMailer();
-               $mail->PluginDir  = sprintf("%sinc/phpmailer/", constant('PATH'));
+
+               // Set charset to UTF-8
+               $mail->CharSet('UTF-8');
+
+               // Path for PHPMailer
+               $mail->PluginDir  = sprintf("%sinc/phpmailer/", getConfig('PATH'));
 
                $mail->IsSMTP();
                $mail->SMTPAuth   = true;
@@ -499,13 +645,13 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
                $mail->Username   = getConfig('SMTP_USER');
                $mail->Password   = getConfig('SMTP_PASSWORD');
                if (empty($from)) {
-                       $mail->From = constant('WEBMASTER');
+                       $mail->From = getConfig('WEBMASTER');
                } else {
                        $mail->From = $from;
                }
-               $mail->FromName   = constant('MAIN_TITLE');
+               $mail->FromName   = getConfig('MAIN_TITLE');
                $mail->Subject    = $subject;
-               if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($message) != $message)) {
+               if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
                        $mail->Body       = $message;
                        $mail->AltBody    = 'Your mail program required HTML support to read this mail!';
                        $mail->WordWrap   = 70;
@@ -514,9 +660,9 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
                        $mail->Body       = decodeEntities($message);
                }
                $mail->AddAddress($toEmail, '');
-               $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
-               $mail->AddCustomHeader('Errors-To:' . constant('WEBMASTER'));
-               $mail->AddCustomHeader('X-Loop:' . constant('WEBMASTER'));
+               $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
+               $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
+               $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
                $mail->Send();
        } else {
                // Use legacy mail() command
@@ -525,16 +671,16 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
 }
 
 // Generate a password in a specified length or use default password length
-function generatePassword ($length = 0) {
+function generatePassword ($length = '0') {
        // Auto-fix invalid length of zero
-       if ($length == 0) $length = getConfig('pass_len');
+       if ($length == '0') $length = getConfig('pass_len');
 
        // Initialize array with all allowed chars
        $ABC = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/,.');
 
        // Start creating password
        $PASS = '';
-       for ($i = 0; $i < $length; $i++) {
+       for ($i = '0'; $i < $length; $i++) {
                $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
        } // END - for
 
@@ -555,49 +701,50 @@ function generateDateTime ($time, $mode = '0') {
        $time = bigintval($time);
 
        // If the stamp is zero it mostly didn't "happen"
-       if ($time == 0) {
+       if ($time == '0') {
                // Never happend
                return getMessage('NEVER_HAPPENED');
        } // END - if
 
-       switch (getLanguage())
-       {
+       switch (getLanguage()) {
                case 'de': // German date / time format
                        switch ($mode) {
                                case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
-                               case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
-                               case '2': $ret = date("d.m.Y|H:i", $time); break;
-                               case '3': $ret = date("d.m.Y", $time); break;
+                               case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
+                               case '2': $ret = date('d.m.Y|H:i', $time); break;
+                               case '3': $ret = date('d.m.Y', $time); break;
                                default:
-                                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
+                                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
                                        break;
                        }
                        break;
 
-                               default: // Default is the US date / time format!
-                                       switch ($mode) {
-                                               case '0': $ret = date("r", $time); break;
-                                               case '1': $ret = date("Y-m-d - g:i A", $time); break;
-                                               case '2': $ret = date("y-m-d|H:i", $time); break;
-                                               case '3': $ret = date("y-m-d", $time); break;
-                                               default:
-                                                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
-                                                       break;
-                                       }
-       }
+               default: // Default is the US date / time format!
+                       switch ($mode) {
+                               case '0': $ret = date('r', $time); break;
+                               case '1': $ret = date('Y-m-d - g:i A', $time); break;
+                               case '2': $ret = date('y-m-d|H:i', $time); break;
+                               case '3': $ret = date('y-m-d', $time); break;
+                               default:
+                                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
+                                       break;
+                       } // END - switch
+       } // END - switch
+
+       // Return result
        return $ret;
 }
 
 // Translates Y/N to yes/no
 function translateYesNo ($yn) {
        // Default
-       $translated = "??? (" . $yn.')';
+       $translated = '??? (' . $yn . ')';
        switch ($yn) {
                case 'Y': $translated = getMessage('YES'); break;
                case 'N': $translated = getMessage('NO'); break;
                default:
                        // Log unknown value
-                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
+                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
                        break;
        }
 
@@ -614,7 +761,7 @@ function translatePoolType ($type) {
        $constName = sprintf("POOL_TYPE_%s", $type);
 
        // Does it exist?
-       if (defined($constName)) {
+       if (isMessageIdValid($constName)) {
                // Then use it
                $translated = getMessage($constName);
        } // END - if
@@ -624,9 +771,9 @@ function translatePoolType ($type) {
 }
 
 // Translates the american decimal dot into a german comma
-function translateComma ($dotted, $cut = true, $max = 0) {
+function translateComma ($dotted, $cut = true, $max = '0') {
        // Default is 3 you can change this in admin area "Misc -> Misc Options"
-       if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
+       if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
 
        // Use from config is default
        $maxComma = getConfig('max_comma');
@@ -635,25 +782,25 @@ function translateComma ($dotted, $cut = true, $max = 0) {
        if ($max > 0) $maxComma = $max;
 
        // Cut zeros off?
-       if (($cut) && ($max == 0)) {
+       if (($cut === true) && ($max == '0')) {
                // Test for commata if in cut-mode
                $com = explode('.', $dotted);
                if (count($com) < 2) {
                        // Don't display commatas even if there are none... ;-)
-                       $maxComma = 0;
+                       $maxComma = '0';
                }
        } // END - if
 
        // Debug log
-       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
 
        // Translate it now
        switch (getLanguage()) {
-               case 'de':
+               case 'de': // German language
                        $dotted = number_format($dotted, $maxComma, ',', '.');
                        break;
 
-               default:
+               default: // All others
                        $dotted = number_format($dotted, $maxComma, '.', ',');
                        break;
        }
@@ -674,7 +821,7 @@ function translateGender ($gender) {
                case 'C': $ret = getMessage('GENDER_C'); break;
                default:
                        // Log unknown gender
-                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
+                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
                        break;
        }
 
@@ -684,8 +831,8 @@ function translateGender ($gender) {
 
 // "Translates" the user status
 function translateUserStatus ($status) {
-       switch ($status)
-       {
+       // Generate message depending on status
+       switch ($status) {
                case 'UNCONFIRMED':
                case 'CONFIRMED':
                case 'LOCKED':
@@ -698,258 +845,122 @@ function translateUserStatus ($status) {
                        break;
 
                default:
-                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
+                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
                        $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
                        break;
-       }
+       } // END - switch
 
        // Return it
        return $ret;
 }
 
 // Generates an URL for the dereferer
-function DEREFERER ($URL) {
+function generateDerefererUrl ($URL) {
        // Don't de-refer our own links!
-       if (substr($URL, 0, strlen(constant('URL'))) != constant('URL')) {
+       if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
                // De-refer this link
-               $URL = 'modules.php?module=loader&amp;url=' . encodeString(compileUriCode($URL));
+               $URL = '{?URL?}/modules.php?module=loader&amp;url=' . encodeString(compileUriCode($URL));
        } // END - if
 
-       // Return link
-       return $URL;
-}
-
-// Generates an URL for the frametester
-function FRAMETESTER ($URL) {
-       // Prepare frametester URL
-       $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&amp;url=%s",
-       encodeString(compileUriCode($URL))
-       );
-       return $frametesterUrl;
-}
-
-// Count entries from e.g. a selection box
-function countSelection ($array) {
-       $ret = 0;
-       if (is_array($array)) {
-               foreach ($array as $key => $selected) {
-                       if (!empty($selected)) $ret++;
-               }
-       }
-       return $ret;
-}
-
-// Generate XHTML code for the CAPTCHA
-function generateCaptchaCode ($code, $type, $DATA, $uid) {
-       return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '" />';
-}
-
-// Loads an email template and compiles it
-function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
-       global $DATA;
-
-       // Our configuration is kept non-global here
-       $_CONFIG = getConfigArray();
-
-       // Make sure all template names are lowercase!
-       $template = strtolower($template);
-
-       // Default 'nickname' if extension is not installed
-       $nick = '---';
-
-       // Prepare IP number and User Agent
-       $REMOTE_ADDR     = detectRemoteAddr();
-       $HTTP_USER_AGENT = detectUserAgent();
-
-       // Default admin
-       $ADMIN = constant('MAIN_TITLE');
-
-       // Is the admin logged in?
-       if (IS_ADMIN()) {
-               // Get admin id
-               $aid = getCurrentAdminId();
-
-               // Load Admin data
-               $ADMIN = getAdminEmail($aid);
-       } // END - if
-
-       // Neutral email address is default
-       $email = constant('WEBMASTER');
-
-       // Expiration in a nice output format
-       // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
-       if (getConfig('auto_purge') == 0) {
-               // Will never expire!
-               $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
-       } else {
-               // Create nice date string
-               $EXPIRATION = createFancyTime(getConfig('auto_purge'));
-       }
-
-       // Is content an array?
-       if (is_array($content)) {
-               // Add expiration to array, $EXPIRATION is now deprecated!
-               $content['expiration'] = $EXPIRATION;
-       } // END - if
-
-       // Load user's data
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
-       if (($UID > 0) && (is_array($content))) {
-               // If nickname extension is installed, fetch nickname as well
-               if (EXT_IS_ACTIVE('nickname')) {
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
-                       // Load nickname
-                       $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
-                       array(bigintval($UID)), __FUNCTION__, __LINE__);
-               } else {
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
-                       /// Load normal data
-                       $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
-                       array(bigintval($UID)), __FUNCTION__, __LINE__);
-               }
-
-               // Fetch and merge data
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
-               $content = merge_array($content, SQL_FETCHARRAY($result));
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
-
-               // Free result
-               SQL_FREERESULT($result);
-       } // END - if
-
-       // Translate M to male or F to female if present
-       if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
-
-       // Overwrite email from data if present
-       if (isset($content['email'])) $email = $content['email'];
-
-       // Store email for some functions in global data array
-       $DATA['email'] = $email;
-
-       // Base directory
-       $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
-
-       // Check for admin/guest/member templates
-       if (strpos($template, 'admin_') > -1) {
-               // Admin template found
-               $FQFN = $basePath.'admin/' . $template.'.tpl';
-       } elseif (strpos($template, 'guest_') > -1) {
-               // Guest template found
-               $FQFN = $basePath.'guest/' . $template.'.tpl';
-       } elseif (strpos($template, 'member_') > -1) {
-               // Member template found
-               $FQFN = $basePath.'member/' . $template.'.tpl';
-       } else {
-               // Test for extension
-               $test = substr($template, 0, strpos($template, '_'));
-               if (EXT_IS_ACTIVE($test)) {
-                       // Set extra path to extension's name
-                       $FQFN = $basePath . $test.'/' . $template.'.tpl';
-               } else {
-                       // No special filename
-                       $FQFN = $basePath . $template.'.tpl';
-               }
-       }
-
-       // Does the special template exists?
-       if (!isFileReadable($FQFN)) {
-               // Reset to default template
-               $FQFN = $basePath . $template.'.tpl';
-       } // END - if
-
-       // Now does the final template exists?
-       $newContent = '';
-       if (isFileReadable($FQFN)) {
-               // The local file does exists so we load it. :)
-               $tmpl_file = readFromFile($FQFN);
-               $tmpl_file = SQL_ESCAPE($tmpl_file);
-
-               // Run code
-               $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
-               eval($tmpl_file);
-       } elseif (!empty($template)) {
-               // Template file not found!
-               $newContent = "{--TEMPLATE_404--}: " . $template."<br />
-{--TEMPLATE_CONTENT--}
-<pre>".print_r($content, true)."</pre>
-{--TEMPLATE_DATA--}
-<pre>".print_r($DATA, true)."</pre>
-<br /><br />";
-
-               // Debug mode not active? Then remove the HTML tags
-               if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
-       } else {
-               // No template name supplied!
-               $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
-       }
+       // Return link
+       return $URL;
+}
 
-       // Is there some content?
-       if (empty($newContent)) {
-               // Compiling failed
-               $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $tmpl_file;
-               // Add last error if the required function exists
-               if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
+// Generates an URL for the frametester
+function generateFrametesterUrl ($URL) {
+       // Prepare frametester URL
+       $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&amp;url=%s",
+               encodeString(compileUriCode($URL))
+       );
+
+       // Return the new URL
+       return $frametesterUrl;
+}
+
+// Count entries from e.g. a selection box
+function countSelection ($array) {
+       // Integrity check
+       if (!is_array($array)) {
+               // Not an array!
+               debug_report_bug(__FUNCTION__.': No array provided.');
        } // END - if
 
-       // Remove content and data
-       unset($content);
-       unset($DATA);
+       // Init count
+       $ret = '0';
+
+       // Count all entries
+       foreach ($array as $key => $selected) {
+               // Is it checked?
+               if (!empty($selected)) $ret++;
+       } // END - foreach
+
+       // Return counted selections
+       return $ret;
+}
 
-       // Return compiled content
-       return COMPILE_CODE($newContent);
+// Generate XHTML code for the CAPTCHA
+function generateCaptchaCode ($code, $type, $DATA, $userid) {
+       return '<img border="0" alt="Code ' . $code . '" src="{?URL?}/mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '" />';
 }
 
 // Generates a timestamp (some wrapper for mktime())
-function makeTime ($H, $M, $S, $stamp) {
+function makeTime ($hours, $minutes, $seconds, $stamp) {
        // Extract day, month and year from given timestamp
-       $day   = date('d', $stamp);
-       $month = date('m', $stamp);
-       $year  = date('Y', $stamp);
+       $days   = date('d', $stamp);
+       $months = date('m', $stamp);
+       $years  = date('Y', $stamp);
 
        // Create timestamp for wished time which depends on extracted date
-       return mktime($H, $M, $S, $month, $day, $year);
+       return mktime(
+               $hours,
+               $minutes,
+               $seconds,
+               $months,
+               $days,
+               $years
+       );
 }
 
 // Redirects to an URL and if neccessarry extends it with own base URL
 function redirectToUrl ($URL) {
-       // Compile out URI codes
-       $URL = compileUriCode($URL);
+       // Compile out codes
+       eval('$URL = "' . compileRawCode($URL) . '";');
 
        // Check if http(s):// is there
        if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
                // Make all URLs full-qualified
-               $URL = constant('URL') . '/' . $URL;
+               $URL = getConfig('URL') . '/' . $URL;
        } // END - if
 
        // Three different debug ways...
        //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
-       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
        //* DEBUG: */ die($URL);
 
        // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
        $rel = ' rel="external"';
 
        // Do we have internal or external URL?
-       if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
+       if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
                // Own (=internal) URL
                $rel = '';
        } // END - if
 
        // Get output buffer
-       $OUTPUT = ob_get_contents();
+       $GLOBALS['output'] = ob_get_contents();
 
        // Clear it only if there is content
-       if (!empty($OUTPUT)) {
+       if (!empty($GLOBALS['output'])) {
                clearOutputBuffer();
        } // END - if
 
        // Simple probe for bots/spiders from search engines
        if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
                // Secure the URL against bad things such als HTML insertions and so on...
-               $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
+               $URL = secureString($URL);
 
                // Output new location link as anchor
-               OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
+               outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
        } elseif (!headers_sent()) {
                // Load URL when headers are not sent
                //* DEBUG: */ debug_report_bug("URL={$URL}");
@@ -957,7 +968,7 @@ function redirectToUrl ($URL) {
        } else {
                // Output error message
                loadInclude('inc/header.php');
-               LOAD_TEMPLATE('redirect_url', false, str_replace('&amp;', '&', $URL));
+               loadTemplate('redirect_url', false, str_replace('&amp;', '&', $URL));
                loadInclude('inc/footer.php');
        }
 
@@ -973,15 +984,39 @@ function redirectToConfiguredUrl ($configEntry) {
        // Is this URL set?
        if (is_null($URL)) {
                // Then abort here
-               trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
+               debug_report_bug(sprintf("Configuration entry %s is not set!", $configEntry));
        } // END - if
 
        // Load the URL
        redirectToUrl($URL);
 }
 
-//
-function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
+// Compiles the given HTML/mail code
+function compileCode ($code, $simple = false, $constants = true, $full = true) {
+       // Is the code a string?
+       if (!is_string($code)) {
+               // Silently return it
+               return $code;
+       } // END - if
+
+       // Start couting
+       $startCompile = explode(' ', microtime());
+
+       // Comile the code
+       $code = compileRawCode($code, $simple, $constants, $full);
+
+       // Get timing
+       $compiled = explode(' ', microtime());
+
+       // Add timing
+       $code .= '<!-- Compilation time: ' . ((($compiled[1] + $compiled[0]) - ($startCompile[1] + $startCompile[0])) * 1000). 'ms //-->';
+
+       // Return compiled code
+       return $code;
+}
+
+// Compiles the code (use compileCode() only for HTML because of the comments)
+function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
        // Is the code a string?
        if (!is_string($code)) {
                // Silently return it
@@ -992,17 +1027,20 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
        $secChars = $GLOBALS['security_chars'];
 
        // Select smaller set of chars to replace when we e.g. want to compile URLs
-       if (!$full) $secChars = $GLOBALS['url_chars'];
+       if ($full === false) $secChars = $GLOBALS['url_chars'];
+
+       // Compile more through a filter
+       $code = runFilterChain('compile_code', $code);
 
        // Compile constants
        if ($constants === true) {
                // BEFORE 0.2.1 : Language and data constants
                // WITH 0.2.1+  : Only language constants
-               $code = str_replace('{--','".', str_replace('--}','."', $code));
+               $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
 
                // BEFORE 0.2.1 : Not used
                // WITH 0.2.1+  : Data constants
-               $code = str_replace('{!','".', str_replace("!}", '."', $code));
+               $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
        } // END - if
 
        // Compile QUOT and other non-HTML codes
@@ -1015,7 +1053,7 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
        if ($simple) $code = str_replace("'", '{QUOT}', $code);
 
        // Find $content[bla][blub] entries
-       preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
+       preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
 
        // Are some matches found?
        if ((count($matches) > 0) && (count($matches[0]) > 0)) {
@@ -1031,36 +1069,36 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
                                $test = substr($found, 0, strlen($match));
 
                                // Does this entry exist?
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
+                               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
                                if ($test == $match) {
                                        // Match found!
-                                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
+                                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
                                        $fuzzyFound = true;
                                        break;
                                } // END - if
                        } // END - foreach
 
                        // Skip this entry?
-                       if ($fuzzyFound) continue;
+                       if ($fuzzyFound === true) continue;
 
                        // Take all string elements
                        if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
                                // Replace it in the code
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
-                               $newMatch = str_replace("[" . $matches[4][$key]."]", "['" . $matches[4][$key]."']", $match);
+                               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
+                               $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
                                $code = str_replace($match, "\"." . $newMatch.".\"", $code);
-                               $matchesFound[$key."_" . $matches[4][$key]] = 1;
+                               $matchesFound[$key . '_' . $matches[4][$key]] = 1;
                                $matchesFound[$match] = 1;
                        } elseif (!isset($matchesFound[$match])) {
                                // Not yet replaced!
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
+                               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
                                $code = str_replace($match, "\"." . $match.".\"", $code);
                                $matchesFound[$match] = 1;
                        }
                } // END - foreach
        } // END - if
 
-       // Return compiled code
+       // Return it
        return $code;
 }
 
@@ -1080,13 +1118,13 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
  * Sie, dass es doch nicht so schwer ist! :-)                           *
  *                                                                      *
  ************************************************************************/
-function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
+function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
        $dummy = $array;
        while ($primary_key < count($a_sort)) {
                foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
                        foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
                                $match = false;
-                               if (!$nums) {
+                               if ($nums === false) {
                                        // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
                                        if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
                                } elseif ($key != $key2) {
@@ -1116,23 +1154,23 @@ function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums =
 }
 
 //
-function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
+function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
        $OUT = '';
 
        if ($type == 'yn') {
                // This is a yes/no selection only!
                if ($id > 0) $prefix .= "[" . $id."]";
-               $OUT .= "    <select name=\"" . $prefix."\" class=\"register_select\" size=\"1\">\n";
+               $OUT .= "    <select name=\"" . $prefix."\" class=\"" . $class . "\" size=\"1\">\n";
        } else {
                // Begin with regular selection box here
                if (!empty($prefix)) $prefix .= "_";
                $type2 = $type;
                if ($id > 0) $type2 .= "[" . $id."]";
-               $OUT .= "    <select name=\"".strtolower($prefix . $type2)."\" class=\"register_select\" size=\"1\">\n";
+               $OUT .= "    <select name=\"".strtolower($prefix . $type2)."\" class=\"" . $class . "\" size=\"1\">\n";
        }
 
        switch ($type) {
-               case "day": // Day
+               case 'day': // Day
                        for ($idx = 1; $idx < 32; $idx++) {
                                $OUT .= "<option value=\"" . $idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
@@ -1140,7 +1178,7 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
                        } // END - for
                        break;
 
-               case "month": // Month
+               case 'month': // Month
                        foreach ($GLOBALS['month_descr'] as $month => $descr) {
                                $OUT .= "<option value=\"" . $month."\"";
                                if ($default == $month) $OUT .= ' selected="selected"';
@@ -1148,12 +1186,12 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
                        } // END - for
                        break;
 
-               case "year": // Year
+               case 'year': // Year
                        // Get current year
                        $year = date('Y', time());
 
                        // Use configured min age or fixed?
-                       if (GET_EXT_VERSION('other') >= '0.2.1') {
+                       if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
                                // Configured
                                $startYear = $year - getConfig('min_age');
                        } else {
@@ -1181,7 +1219,7 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
                                // Get current year and subtract the configured minimum age
                                $OUT .= "<option value=\"".($minYear - 1)."\">&lt;" . $minYear."</option>\n";
                                // Calculate earliest year depending on extension version
-                               if (GET_EXT_VERSION('other') >= '0.2.1') {
+                               if ((isExtensionActive('other')) && (getExtensionVersion('other') >= '0.2.1')) {
                                        // Use configured minimum age
                                        $year = date('Y', time()) - getConfig('min_age');
                                } else {
@@ -1198,9 +1236,9 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
                        }
                        break;
 
-               case "sec":
-               case "min":
-                       for ($idx = 0; $idx < 60; $idx+=5) {
+               case 'sec':
+               case 'min':
+                       for ($idx = '0'; $idx < 60; $idx+=5) {
                                if (strlen($idx) == 1) $idx = '0' . $idx;
                                $OUT .= "<option value=\"" . $idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
@@ -1208,8 +1246,8 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
                        } // END - for
                        break;
 
-               case "hour":
-                       for ($idx = 0; $idx < 24; $idx++) {
+               case 'hour':
+                       for ($idx = '0'; $idx < 24; $idx++) {
                                if (strlen($idx) == 1) $idx = '0' . $idx;
                                $OUT .= "<option value=\"" . $idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
@@ -1221,7 +1259,7 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
                        $OUT .= "<option value=\"Y\"";
                        if ($default == 'Y') $OUT .= ' selected="selected"';
                        $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
-                       if ($default == 'N') $OUT .= ' selected="selected"';
+                       if ($default != 'Y') $OUT .= ' selected="selected"';
                        $OUT .= ">{--NO--}</option>\n";
                        break;
        }
@@ -1233,52 +1271,50 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
 // Deprecated : $length
 // Optional   : $DATA
 //
-function generateRandomCode ($length, $code, $uid, $DATA = '') {
-       // Fix missing _MAX constant
-       // @TODO Rewrite this unnice code
-       if (!defined('_MAX')) define('_MAX', 15235);
-
+function generateRandomCode ($length, $code, $userid, $DATA = '') {
        // Build server string
-       $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH').'inc/databases.php');
+       $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
 
        // Build key string
-       $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
+       $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
        if (isConfigEntrySet('secret_key'))  $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
        if (isConfigEntrySet('file_hash'))   $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
-       $keys .= getConfig('ENCRYPT_SEPERATOR') . date("d-m-Y (l-F-T)", getConfig('patch_ctime'));
+       $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
        if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
 
        // Build string from misc data
-       $data   = $code.getConfig('ENCRYPT_SEPERATOR') . $uid.getConfig('ENCRYPT_SEPERATOR') . $DATA;
+       $data   = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
 
        // Add more additional data
-       if (isSessionVariableSet('u_hash'))         $data .= getConfig('ENCRYPT_SEPERATOR').getSession('u_hash');
-       if (isUserIdSet())                          $data .= getConfig('ENCRYPT_SEPERATOR').getUserId();
-       if (isSessionVariableSet('mxchange_theme')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
-       if (isSessionVariableSet('mx_lang'))        $data .= getConfig('ENCRYPT_SEPERATOR').getLanguage();
-       if (isset($GLOBALS['refid']))               $data .= getConfig('ENCRYPT_SEPERATOR') . $GLOBALS['refid'];
+       if (isSessionVariableSet('u_hash'))         $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
+
+       // Add referal id, language, theme and userid
+       $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
+       $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
+       $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
+       $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
 
        // Calculate number for generating the code
        $a = $code + getConfig('_ADD') - 1;
 
-       if (isConfigEntrySet('master_hash')) {
+       if (isConfigEntrySet('master_salt')) {
                // Generate hash with master salt from modula of number with the prime number and other data
-               $saltedHash = generateHash(($a % getConfig('_PRIME')).getConfig('ENCRYPT_SEPERATOR') . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
+               $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
 
                // Create number from hash
-               $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
+               $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
        } else {
                // Generate hash with "hash of site key" from modula of number with the prime number and other data
-               $saltedHash = generateHash(($a % getConfig('_PRIME')).getConfig('ENCRYPT_SEPERATOR') . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, 8));
+               $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
 
                // Create number from hash
-               $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
+               $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
        }
 
        // At least 10 numbers shall be secure enought!
        $len = getConfig('code_length');
-       if ($len == 0) $len = $length;
-       if ($len == 0) $len = 10;
+       if ($len == '0') $len = $length;
+       if ($len == '0') $len = 10;
 
        // Cut off requested counts of number
        $return = substr(str_replace('.', '', $rcode), 0, $len);
@@ -1290,16 +1326,15 @@ function generateRandomCode ($length, $code, $uid, $DATA = '') {
 // Does only allow numbers
 function bigintval ($num, $castValue = true) {
        // Filter all numbers out
-       $ret = preg_replace("/[^0123456789]/", '', $num);
+       $ret = preg_replace('/[^0123456789]/', '', $num);
 
        // Shall we cast?
-       if ($castValue) $ret = (double)$ret;
+       if ($castValue === true) $ret = (double)$ret;
 
        // Has the whole value changed?
-       // @TODO Remove this if() block if all is working fine
        if ('' . $ret . '' != '' . $num . '') {
                // Log the values
-               //debug_report_bug("{$ret}<>{$num}");
+               debug_report_bug('Problem with number found. ret=' . $ret . ', num='. $num);
        } // END - if
 
        // Return result
@@ -1307,34 +1342,41 @@ function bigintval ($num, $castValue = true) {
 }
 
 // Insert the code in $img_code into jpeg or PNG image
-function GENERATE_IMAGE ($img_code, $headerSent=true) {
-       if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
+function generateImageOrCode ($img_code, $headerSent = true) {
+       // Is the code size oversized or shouldn't we display it?
+       if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
                // Stop execution of function here because of over-sized code length
-               return;
-       } elseif (!$headerSent) {
-               // Return in an HTML code code
-               return "<img src=\"{!URL!}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
+               debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
+       } elseif ($headerSent === false) {
+               // Return an HTML code here
+               return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
        }
 
        // Load image
-       $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
+       $img = sprintf("%s/theme/%s/images/code_bg.%s",
+               getConfig('PATH'),
+               getCurrentTheme(),
+               getConfig('img_type')
+       );
+
+       // Is it readable?
        if (isFileReadable($img)) {
                // Switch image type
                switch (getConfig('img_type'))
                {
                        case 'jpg':
                                // Okay, load image and hide all errors
-                               $image = @imagecreatefromjpeg($img);
+                               $image = imagecreatefromjpeg($img);
                                break;
 
                        case 'png':
                                // Okay, load image and hide all errors
-                               $image = @imagecreatefrompng($img);
+                               $image = imagecreatefrompng($img);
                                break;
                }
        } else {
                // Exit function here
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
+               logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
                return;
        }
 
@@ -1363,38 +1405,38 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
        //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
 
        // Do we have a leap year?
-       $SWITCH = 0;
+       $SWITCH = '0';
        $TEST = date('Y', time()) / 4;
        $M1 = date('m', time());
        $M2 = date('m', (time() + $timestamp));
 
        // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
-       if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02"))  $SWITCH = getConfig('one_day');
+       if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02"))  $SWITCH = getConfig('ONE_DAY');
 
        // First of all years...
        $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
-       //* DEBUG: */ print("Y={$Y}<br />\n");
+       //* DEBUG: */ print("Y={$Y}<br />");
        // Next months...
        $M = abs(floor($timestamp / 2628000 - $Y * 12));
-       //* DEBUG: */ print("M={$M}<br />\n");
+       //* DEBUG: */ print("M={$M}<br />");
        // Next weeks
-       $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
-       //* DEBUG: */ print("W={$W}<br />\n");
+       $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
+       //* DEBUG: */ print("W={$W}<br />");
        // Next days...
-       $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
-       //* DEBUG: */ print("D={$D}<br />\n");
+       $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
+       //* DEBUG: */ print("D={$D}<br />");
        // Next hours...
-       $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
-       //* DEBUG: */ print("h={$h}<br />\n");
+       $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24) - $W * 7 * 24 - $D * 24));
+       //* DEBUG: */ print("h={$h}<br />");
        // Next minutes..
-       $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
-       //* DEBUG: */ print("m={$m}<br />\n");
+       $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
+       //* DEBUG: */ print("m={$m}<br />");
        // And at last seconds...
-       $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
-       //* DEBUG: */ print("s={$s}<br />\n");
+       $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
+       //* DEBUG: */ print("s={$s}<br />");
 
        // Is seconds zero and time is < 60 seconds?
-       if (($s == 0) && ($timestamp < 60)) {
+       if (($s == '0') && ($timestamp < 60)) {
                // Fix seconds
                $s = round($timestamp);
        } // END - if
@@ -1453,7 +1495,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                if (ereg('Y', $display) || (empty($display))) {
                        // Generate year selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ye\" size=\"1\">\n";
-                       for ($idx = 0; $idx <= 10; $idx++) {
+                       for ($idx = '0'; $idx <= 10; $idx++) {
                                $OUT .= "    <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $Y) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1466,7 +1508,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                if (ereg('M', $display) || (empty($display))) {
                        // Generate month selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
-                       for ($idx = 0; $idx <= 11; $idx++)
+                       for ($idx = '0'; $idx <= 11; $idx++)
                        {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $M) $OUT .= ' selected="selected"';
@@ -1480,7 +1522,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                if (ereg("W", $display) || (empty($display))) {
                        // Generate week selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
-                       for ($idx = 0; $idx <= 4; $idx++) {
+                       for ($idx = '0'; $idx <= 4; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $W) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1493,7 +1535,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                if (ereg("D", $display) || (empty($display))) {
                        // Generate day selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
-                       for ($idx = 0; $idx <= 31; $idx++) {
+                       for ($idx = '0'; $idx <= 31; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $D) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1506,7 +1548,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                if (ereg("h", $display) || (empty($display))) {
                        // Generate hour selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
-                       for ($idx = 0; $idx <= 23; $idx++)      {
+                       for ($idx = '0'; $idx <= 23; $idx++)    {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $h) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1519,7 +1561,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                if (ereg('m', $display) || (empty($display))) {
                        // Generate minute selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
-                       for ($idx = 0; $idx <= 59; $idx++) {
+                       for ($idx = '0'; $idx <= 59; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $m) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1532,7 +1574,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                if (ereg("s", $display) || (empty($display))) {
                        // Generate second selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
-                       for ($idx = 0; $idx <= 59; $idx++) {
+                       for ($idx = '0'; $idx <= 59; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $s) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1550,98 +1592,34 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
 }
 
 //
-function createTimestampFromSelections ($prefix, $POST) {
+function createTimestampFromSelections ($prefix, $postData) {
        // Initial return value
-       $ret = 0;
+       $ret = '0';
 
        // Do we have a leap year?
-       $SWITCH = 0;
+       $SWITCH = '0';
        $TEST = date('Y', time()) / 4;
        $M1   = date('m', time());
        // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
-       if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02"))  $SWITCH = getConfig('one_day');
+       if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02"))  $SWITCH = getConfig('ONE_DAY');
        // First add years...
-       $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
+       $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
        // Next months...
-       $ret += $POST[$prefix."_mo"] * 2628000;
+       $ret += $postData[$prefix."_mo"] * 2628000;
        // Next weeks
-       $ret += $POST[$prefix."_we"] * 604800;
+       $ret += $postData[$prefix."_we"] * 604800;
        // Next days...
-       $ret += $POST[$prefix."_da"] * 86400;
+       $ret += $postData[$prefix."_da"] * 86400;
        // Next hours...
-       $ret += $POST[$prefix."_ho"] * 3600;
+       $ret += $postData[$prefix."_ho"] * 3600;
        // Next minutes..
-       $ret += $POST[$prefix."_mi"] * 60;
+       $ret += $postData[$prefix."_mi"] * 60;
        // And at last seconds...
-       $ret += $POST[$prefix."_se"];
+       $ret += $postData[$prefix."_se"];
        // Return calculated value
        return $ret;
 }
 
-// Sends out mail to all administrators
-// IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
-function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
-       // Trim template name
-       $template = trim($template);
-
-       // Load email template
-       $message = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
-
-       // Check which admin shall receive this mail
-       $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
-       array($template), __FUNCTION__, __LINE__);
-       if (SQL_NUMROWS($result) == 0) {
-               // Create new entry (to all admins)
-               SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
-               array($template), __FUNCTION__, __LINE__);
-       } else {
-               // Load admin IDs...
-               // @TODO This can be, somehow, rewritten
-               $adminIds = array();
-               while ($content = SQL_FETCHARRAY($result)) {
-                       $adminIds[] = $content['admin_id'];
-               } // END - while
-
-               // Free memory
-               SQL_FREERESULT($result);
-
-               // Init result
-               $result = false;
-
-               // "implode" IDs and query string
-               $aid = implode(',', $adminIds);
-               if ($aid == '-1') {
-                       if (EXT_IS_ACTIVE('events')) {
-                               // Add line to user events
-                               EVENTS_ADD_LINE($subj, $message, $UID);
-                       } else {
-                               // Log error for debug
-                               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
-                               $template,
-                               $subj,
-                               $UID
-                               ));
-                       }
-               } elseif ($aid == '0') {
-                       // Select all email adresses
-                       $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
-                       __FUNCTION__, __LINE__);
-               } else {
-                       // If Admin-ID is not "to-all" select
-                       $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
-                       array($aid), __FUNCTION__, __LINE__);
-               }
-       }
-
-       // Load email addresses and send away
-       while ($content = SQL_FETCHARRAY($result)) {
-               sendEmail($content['email'], $subj, $message);
-       } // END - while
-
-       // Free memory
-       SQL_FREERESULT($result);
-}
-
 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
 function createFancyTime ($stamp) {
        // Get data array with years/months/weeks/days/...
@@ -1650,8 +1628,7 @@ function createFancyTime ($stamp) {
        foreach($data as $k => $v) {
                if ($v > 0) {
                        // Value is greater than 0 "eval" data to return string
-                       $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
-                       eval($eval);
+                       eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
                        break;
                } // END - if
        } // END - foreach
@@ -1669,10 +1646,10 @@ function createFancyTime ($stamp) {
        return $ret;
 }
 
-//
-function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
+// Generates a navigation row for listing emails
+function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
        $SEP = ''; $TOP = '';
-       if (!$show_form) {
+       if ($show_form === false) {
                $TOP = " top2";
                $SEP = "<tr><td colspan=\"" . $colspan."\" class=\"seperator\">&nbsp;</td></tr>";
        }
@@ -1680,56 +1657,54 @@ function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
        $NAV = '';
        for ($page = 1; $page <= $PAGES; $page++) {
                // Is the page currently selected or shall we generate a link to it?
-               if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
+               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
                        // Is currently selected, so only highlight it
-                       $NAV .= "<strong>-";
+                       $NAV .= '<strong>-';
                } else {
                        // Open anchor tag and add base URL
-                       $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&amp;what=" . getWhat()."&amp;page=" . $page."&amp;offset=" . $offset;
+                       $NAV .= '<a href="{?URL?}/modules.php?module=admin&amp;what=' . getWhat() . '&amp;page=' . $page . '&amp;offset=' . $offset;
 
                        // Add userid when we shall show all mails from a single member
-                       if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&amp;uid=".bigintval(REQUEST_GET('uid'));
+                       if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&amp;userid=' . bigintval(getRequestElement('userid'));
 
                        // Close open anchor tag
-                       $NAV .= "\">";
+                       $NAV .= '">';
                }
                $NAV .= $page;
-               if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
+               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
                        // Is currently selected, so only highlight it
-                       $NAV .= "-</strong>";
+                       $NAV .= '-</strong>';
                } else {
                        // Close anchor tag
-                       $NAV .= "</a>";
+                       $NAV .= '</a>';
                }
 
                // Add seperator if we have not yet reached total pages
-               if ($page < $PAGES) $NAV .= "&nbsp;|&nbsp;";
+               if ($page < $PAGES) $NAV .= '&nbsp;|&nbsp;';
        } // END - for
 
        // Define constants only once
-       if (!defined('__NAV_OUTPUT')) {
-               define('__NAV_OUTPUT' , $NAV);
-               define('__NAV_COLSPAN', $colspan);
-               define('__NAV_TOP'    , $TOP);
-               define('__NAV_SEP'    , $SEP);
-       } // END - if
+       $content['nav']  = $NAV;
+       $content['span'] = $colspan;
+       $content['top']  = $TOP;
+       $content['sep']  = $SEP;
 
        // Load navigation template
-       $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
+       $OUT = loadTemplate('admin_email_nav_row', true, $content);
 
        if ($return === true) {
                // Return generated HTML-Code
                return $OUT;
        } else {
                // Output HTML-Code
-               OUTPUT_HTML($OUT);
+               outputHtml($OUT);
        }
 }
 
 // Extract host from script name
 function extractHostnameFromUrl (&$script) {
        // Use default SERVER_URL by default... ;) So?
-       $url = constant('SERVER_URL');
+       $url = getConfig('SERVER_URL');
 
        // Is this URL valid?
        if (substr($script, 0, 7) == 'http://') {
@@ -1745,7 +1720,7 @@ function extractHostnameFromUrl (&$script) {
        if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
 
        // Generate relative URL
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
+       //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
        if (substr(strtolower($script), 0, 7) == 'http://') {
                // But only if http:// is in front!
                $script = substr($script, (strlen($url) + 7));
@@ -1754,7 +1729,7 @@ function extractHostnameFromUrl (&$script) {
                $script = substr($script, (strlen($url) + 8));
        }
 
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
+       //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
        if (substr($script, 0, 1) == '/') $script = substr($script, 1);
 
        // Return host name
@@ -1762,25 +1737,37 @@ function extractHostnameFromUrl (&$script) {
 }
 
 // Send a GET request
-function sendGetRequest ($script) {
-       // Compile the script name
-       $script = COMPILE_CODE($script);
-
+function sendGetRequest ($script, $data = array()) {
        // Extract host name from script
        $host = extractHostnameFromUrl($script);
 
+       // Add data
+       $scriptData = http_build_query($data, '', '&');
+
+       // Do we have a question-mark in the script?
+       if (strpos($script, '?') === false) {
+               // No, so first char must be question mark
+               $scriptData = '?' . $scriptData;
+       } else {
+               // Ok, add &
+               $scriptData = '&' . $scriptData;
+       }
+
+       // Add script data
+       $script .= $scriptData;
+
        // Generate GET request header
-       $request  = "GET /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
-       $request .= "Host: " . $host . getConfig('HTTP_EOL');
-       $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
-       if (defined('FULL_VERSION')) {
-               $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
+       $request  = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
+       $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
+       $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
+       if (isConfigEntrySet('FULL_VERSION')) {
+               $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
        } else {
-               $request .= "User-Agent: " . constant('TITLE') . "/?.?.?" . getConfig('HTTP_EOL');
+               $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
        }
-       $request .= "Content-Type: text/plain" . getConfig('HTTP_EOL');
-       $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
-       $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
+       $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
+       $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
+       $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
 
        // Send the raw request
        $response = sendRawRequest($host, $request);
@@ -1794,28 +1781,25 @@ function sendPostRequest ($script, $postData) {
        // Is postData an array?
        if (!is_array($postData)) {
                // Abort here
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
+               logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
                return array('', '', '');
        } // END - if
 
-       // Compile the script name
-       $script = COMPILE_CODE($script);
-
        // Extract host name from script
        $host = extractHostnameFromUrl($script);
 
        // Construct request
-       $data = http_build_query($postData, '','&');
+       $data = http_build_query($postData, '', '&');
 
        // Generate POST request header
-       $request  = "POST /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
-       $request .= "Host: " . $host . getConfig('HTTP_EOL');
-       $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
-       $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
-       $request .= "Content-type: application/x-www-form-urlencoded" . getConfig('HTTP_EOL');
-       $request .= "Content-length: " . strlen($data) . getConfig('HTTP_EOL');
-       $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
-       $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
+       $request  = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
+       $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
+       $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
+       $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
+       $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
+       $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
+       $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
+       $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
        $request .= $data;
 
        // Send the raw request
@@ -1828,7 +1812,7 @@ function sendPostRequest ($script, $postData) {
 // Sends a raw request to another host
 function sendRawRequest ($host, $request) {
        // Init errno and errdesc with 'all fine' values
-       $errno = 0; $errdesc = '';
+       $errno = '0'; $errdesc = '';
 
        // Initialize array
        $response = array('', '', '');
@@ -1837,16 +1821,16 @@ function sendRawRequest ($host, $request) {
        $useProxy = false;
 
        // Are proxy settins set?
-       if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
+       if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
                // Then use it
                $useProxy = true;
        } // END - if
 
        // Open connection
-       //* DEBUG: */ die("SCRIPT=" . $script."<br />\n");
+       //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
        if ($useProxy === true) {
                // Connect to host through proxy connection
-               $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
+               $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
        } else {
                // Connect to host directly
                $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
@@ -1867,7 +1851,7 @@ function sendRawRequest ($host, $request) {
                // Use login data to proxy? (username at least!)
                if (getConfig('proxy_username') != '') {
                        // Add it as well
-                       $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . COMPILE_CODE(getConfig('proxy_password')));
+                       $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
                        $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
                } // END - if
 
@@ -1941,9 +1925,6 @@ function sendRawRequest ($host, $request) {
 
 // Taken from www.php.net eregi() user comments
 function isEmailValid ($email) {
-       // Compile email
-       $email = COMPILE_CODE($email);
-
        // Check first part of email address
        $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
 
@@ -1961,14 +1942,14 @@ function isEmailValid ($email) {
 function isUrlValid ($URL, $compile=true) {
        // Trim URL a little
        $URL = trim(urldecode($URL));
-       //* DEBUG: */ echo $URL."<br />";
+       //* DEBUG: */ outputHtml($URL.'<br />');
 
        // Compile some chars out...
        if ($compile === true) $URL = compileUriCode($URL, false, false, false);
-       //* DEBUG: */ echo $URL."<br />";
+       //* DEBUG: */ outputHtml($URL.'<br />');
 
        // Check for the extension filter
-       if (EXT_IS_ACTIVE('filter')) {
+       if (isExtensionActive('filter')) {
                // Use the extension's filter set
                return FILTER_VALIDATE_URL($URL, false);
        } // END - if
@@ -1979,37 +1960,39 @@ function isUrlValid ($URL, $compile=true) {
 }
 
 // Generate a list of administrative links to a given userid
-function generateMemberAdminActionLinks ($uid, $status = '') {
+function generateMemberAdminActionLinks ($userid, $status = '') {
+       // Make sure userid is a number
+       if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
+
        // Define all main targets
-       $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
+       $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
 
        // Begin of navigation links
-       $eval = "\$OUT = \"[&nbsp;";
+       $OUT = "[&nbsp;";
 
-       foreach ($TARGETS as $tar) {
-               $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&amp;what=" . $tar."&amp;uid=" . $uid."\\\" title=\\\"{--ADMIN_LINK_";
-               //* DEBUG: */ echo "*" . $tar.'/' . $status."*<br />\n";
-               if (($tar == "lock_user") && ($status == 'LOCKED')) {
+       foreach ($targetArray as $tar) {
+               $OUT .= "<span class=\"admin_user_link\"><a href=\"{?URL?}/modules.php?module=admin&amp;what=" . $tar . "&amp;userid=" . $userid . "\" title=\"{--ADMIN_LINK_";
+               //* DEBUG: */ outputHtml("*" . $tar.'/' . $status."*<br />");
+               if (($tar == 'lock_user') && ($status == 'LOCKED')) {
                        // Locked accounts shall be unlocked
-                       $eval .= "UNLOCK_USER";
+                       $OUT .= 'UNLOCK_USER';
                } else {
                        // All other status is fine
-                       $eval .= strtoupper($tar);
+                       $OUT .= strtoupper($tar);
                }
-               $eval .= "_TITLE--}\\\">{--ADMIN_";
-               if (($tar == "lock_user") && ($status == 'LOCKED')) {
+               $OUT .= "_TITLE--}\">{--ADMIN_";
+               if (($tar == 'lock_user') && ($status == 'LOCKED')) {
                        // Locked accounts shall be unlocked
-                       $eval .= "UNLOCK_USER";
+                       $OUT .= 'UNLOCK_USER';
                } else {
                        // All other status is fine
-                       $eval .= strtoupper($tar);
+                       $OUT .= strtoupper($tar);
                }
-               $eval .= "--}</a></span>&nbsp;|&nbsp;";
+               $OUT .= "--}</a></span>&nbsp;|&nbsp;";
        }
 
        // Finish navigation link
-       $eval = substr($eval, 0, -7)."]\";";
-       eval($eval);
+       $OUT = substr($OUT, 0, -7) . ']';
 
        // Return string
        return $OUT;
@@ -2021,19 +2004,19 @@ function generateEmailLink ($email, $table = 'admins') {
        $EMAIL = 'mailto:' . $email;
 
        // Check for several extensions
-       if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
+       if ((isExtensionActive('admins')) && ($table == 'admins')) {
                // Create email link for contacting admin in guest area
                $EMAIL = generateAdminEmailLink($email);
-       } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
+       } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
                // Create email link for contacting a member within admin area (or later in other areas, too?)
-               $EMAIL = generateEmailLink($email, 'user_data');
-       } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
+               $EMAIL = generateUserEmailLink($email, 'admin');
+       } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
                // Create email link to contact sponsor within admin area (or like the link above?)
-               $EMAIL = generateEmailLink($email, 'sponsor_data');
+               $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
        }
 
        // Shall I close the link when there is no admin?
-       if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
+       if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
 
        // Return email link
        return $EMAIL;
@@ -2042,7 +2025,7 @@ function generateEmailLink ($email, $table = 'admins') {
 // Generate a hash for extra-security for all passwords
 function generateHash ($plainText, $salt = '') {
        // Is the required extension 'sql_patches' there and a salt is not given?
-       if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
+       if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
                // Extension sql_patches is missing/outdated so we hash the plain text with MD5
                return md5($plainText);
        } // END - if
@@ -2056,32 +2039,39 @@ function generateHash ($plainText, $salt = '') {
        // When the salt is empty build a new one, else use the first x configured characters as the salt
        if (empty($salt)) {
                // Build server string (inc/databases.php is no longer updated with every commit)
-               $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
+               $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
 
                // Build key string
-               $keys   = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key').getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash').getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig('patch_ctime')).getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
+               $keys   = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('secret_key') . getConfig('ENCRYPT_SEPERATOR') . getConfig('file_hash') . getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime')) . getConfig('ENCRYPT_SEPERATOR') . getConfig('master_salt');
 
                // Additional data
-               $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
+               $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
 
                // Calculate number for generating the code
                $a = time() + getConfig('_ADD') - 1;
 
                // Generate SHA1 sum from modula of number and the prime number
-               $sha1 = sha1(($a % getConfig('_PRIME')) . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a);
-               //* DEBUG: */ echo "SHA1=" . $sha1." (".strlen($sha1).")<br />";
+               $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
+               //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
                $sha1 = scrambleString($sha1);
-               //* DEBUG: */ echo "Scrambled=" . $sha1." (".strlen($sha1).")<br />";
+               //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
                //* DEBUG: */ $sha1b = descrambleString($sha1);
-               //* DEBUG: */ echo "Descrambled=" . $sha1b." (".strlen($sha1b).")<br />";
+               //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
 
                // Generate the password salt string
                $salt = substr($sha1, 0, getConfig('salt_length'));
-               //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
+               //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
        } else {
                // Use given salt
+               //* DEBUG: */ print 'salt=' . $salt . '<br />';
                $salt = substr($salt, 0, getConfig('salt_length'));
-               //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
+               //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
+
+               // Sanity check on salt
+               if (strlen($salt) != getConfig('salt_length')) {
+                       // Not the same!
+                       debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
+               } // END - if
        }
 
        // Return hash
@@ -2106,8 +2096,8 @@ function scrambleString($str) {
        }
 
        // Scramble string here
-       //* DEBUG: */ echo "***Original=" . $str."***<br />";
-       for ($idx = 0; $idx < strlen($str); $idx++) {
+       //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
+       for ($idx = '0'; $idx < strlen($str); $idx++) {
                // Get char on scrambled position
                $char = substr($str, $scrambleNums[$idx], 1);
 
@@ -2116,7 +2106,7 @@ function scrambleString($str) {
        } // END - for
 
        // Return scrambled string
-       //* DEBUG: */ echo "***Scrambled=" . $scrambled."***<br />";
+       //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
        return $scrambled;
 }
 
@@ -2132,15 +2122,15 @@ function descrambleString($str) {
        if (count($scrambleNums) != 40) return $str;
 
        // Begin descrambling
-       $orig = str_repeat(" ", 40);
-       //* DEBUG: */ echo "+++Scrambled=" . $str."+++<br />";
-       for ($idx = 0; $idx < 40; $idx++) {
+       $orig = str_repeat(' ', 40);
+       //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
+       for ($idx = '0'; $idx < 40; $idx++) {
                $char = substr($str, $idx, 1);
                $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
        } // END - for
 
        // Return scrambled string
-       //* DEBUG: */ echo "+++Original=" . $orig."+++<br />";
+       //* DEBUG: */ outputHtml("+++Original=" . $orig."+++<br />");
        return $orig;
 }
 
@@ -2150,7 +2140,7 @@ function genScrambleString ($len) {
        $scrambleNumbers = array();
 
        // First we need to setup randomized numbers from 0 to 31
-       for ($idx = 0; $idx < $len; $idx++) {
+       for ($idx = '0'; $idx < $len; $idx++) {
                // Generate number
                $rand = mt_rand(0, ($len -1));
 
@@ -2174,10 +2164,10 @@ function generatePassString ($passHash) {
        $ret = $passHash;
 
        // Is a secret key and master salt already initialized?
-       if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
+       if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
                // Only calculate when the secret key is generated
                $newHash = ''; $start = 9;
-               for ($idx = 0; $idx < 10; $idx++) {
+               for ($idx = '0'; $idx < 10; $idx++) {
                        $part1 = hexdec(substr($passHash, $start, 4));
                        $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
                        $mod = dechex($idx);
@@ -2186,21 +2176,22 @@ function generatePassString ($passHash) {
                        } elseif ($part2 > $part1) {
                                $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
                        }
-                       $mod = substr(round($mod), 0, 4);
-                       $mod = str_repeat('0', 4-strlen($mod)) . $mod;
-                       //* DEBUG: */ echo "*" . $start.'=' . $mod."*<br />";
+                       $mod = substr($mod, 0, 4);
+                       //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
+                       $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
+                       //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
                        $start += 4;
                        $newHash .= $mod;
                } // END - for
 
-               //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
+               //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
                $ret = generateHash($newHash, getConfig('master_salt'));
-               //* DEBUG: */ print($ret."<br />\n");
+               //* DEBUG: */ print('ret='.$ret.'<br />');
        } else {
                // Hash it simple
-               //* DEBUG: */ echo "--" . $passHash."--<br />\n";
+               //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
                $ret = md5($passHash);
-               //* DEBUG: */ echo "++" . $ret."++<br />\n";
+               //* DEBUG: */ outputHtml("++" . $ret."++<br />");
        }
 
        // Return result
@@ -2235,10 +2226,10 @@ function app_die ($F, $L, $message) {
                $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
 
                // Better log this message away
-               DEBUG_LOG($F, $L, $message);
+               logDebugMessage($F, $L, $message);
 
                // Load the message template
-               LOAD_TEMPLATE('admin_settings_saved', false, $message);
+               loadTemplate('admin_settings_saved', false, $message);
 
                // Load footer
                loadIncludeOnce('inc/footer.php');
@@ -2263,18 +2254,16 @@ function displayParsingTime() {
        $start = explode(' ', $GLOBALS['startTime']);
        $end = explode(' ', $endTime);
        $runTime = $end[0] - $start[0];
-       if ($runTime < 0) $runTime = 0;
-       $runTime = translateComma($runTime);
+       if ($runTime < 0) $runTime = '0';
 
        // Prepare output
        $content = array(
-               'runtime'               => $runTime,
-               'numSQLs'               => (getConfig('sql_count') + 1),
-               'numTemplates'  => (getConfig('num_templates') + 1)
+               'runtime'  => translateComma($runTime),
+               'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
        );
 
        // Load the template
-       LOAD_TEMPLATE('show_timings', false, $content);
+       loadTemplate('show_timings', false, $content);
 }
 
 // Check wether a boolean constant is set
@@ -2286,14 +2275,14 @@ function isBooleanConstantAndTrue ($constName) { // : Boolean
        // In cache?
        if (isset($GLOBALS['cache_array']['const'][$constName])) {
                // Use cache
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />\n";
+               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
                $res = ($GLOBALS['cache_array']['const'][$constName] === true);
        } else {
                // Check constant
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />\n";
+               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
                if (defined($constName)) {
                        // Found!
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />\n";
+                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
                        $res = (constant($constName) === true);
                } // END - if
 
@@ -2313,66 +2302,66 @@ function isApacheModuleLoaded ($apacheModule) {
 }
 
 // Get current theme name
-function getCurrentTheme() {
+function getCurrentTheme () {
        // The default theme is 'default'... ;-)
        $ret = 'default';
 
        // Load default theme if not empty from configuration
-       if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
+       if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
 
        if (!isSessionVariableSet('mxchange_theme')) {
                // Set default theme
-               setSession('mxchange_theme', $ret);
-       } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
+               setTheme($ret);
+       } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
                //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
                // Get theme from cookie
                $ret = getSession('mxchange_theme');
 
                // Is it valid?
-               if (getThemeId($ret) == 0) {
+               if (getThemeId($ret) == '0') {
                        // Fix it to default
                        $ret = 'default';
                } // END - if
-       } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
+       } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
                // Prepare FQFN for checking
-               $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
+               $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
 
                // Installation mode active
-               if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
+               if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
                        // Set cookie from URL data
-                       setSession('mxchange_theme', REQUEST_GET('theme'));
-               } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
+                       setTheme(getRequestElement('theme'));
+               } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
                        // Set cookie from posted data
-                       setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
+                       setTheme(SQL_ESCAPE(postRequestElement('theme')));
                }
 
                // Set return value
                $ret = getSession('mxchange_theme');
        } else {
                // Invalid design, reset cookie
-               setSession('mxchange_theme', $ret);
+               setTheme($ret);
        }
 
-       // Add (maybe) found theme.php file to inclusion list
-       $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
-
-       // Try to load the requested include file
-       if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
-
        // Return theme value
        return $ret;
 }
 
+// Setter for theme in session
+function setTheme ($newTheme) {
+       setSession('mxchange_theme', $newTheme);
+}
+
 // Get id from theme
+// @TODO Try to move this to inc/libs/theme_functions.php
 function getThemeId ($name) {
        // Is the extension 'theme' installed?
-       if (!EXT_IS_ACTIVE('theme')) {
+       if (!isExtensionActive('theme')) {
                // Then abort here
                return 0;
        } // END - if
 
        // Default id
-       $id = 0;
+       $id = '0';
 
        // Is the cache entry there?
        if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
@@ -2380,11 +2369,11 @@ function getThemeId ($name) {
                $id = $GLOBALS['cache_array']['themes']['id'][$name];
 
                // Count up
-               incrementConfigEntry('cache_hits');
-       } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
+               incrementStatsEntry('cache_hits');
+       } elseif (getExtensionVersion('cache') != '0.1.8') {
                // Check if current theme is already imported or not
-               $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
-               array($name), __FUNCTION__, __LINE__);
+               $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
+                       array($name), __FUNCTION__, __LINE__);
 
                // Entry found?
                if (SQL_NUMROWS($result) == 1) {
@@ -2401,26 +2390,26 @@ function getThemeId ($name) {
 }
 
 // Generates an error code from given account status
-function generateErrorCodeFromUserStatus ($status) {
-       // @TODO The status should never be empty
-       if (empty($status)) {
-               // Something really bad happend here
-               debug_report_bug(__FUNCTION__ . ': status is empty.');
+function generateErrorCodeFromUserStatus ($status='') {
+       // If no status is provided, use the default, cached
+       if ((empty($status)) && (isMember())) {
+               // Get user status
+               $status = getUserData('status');
        } // END - if
 
        // Default error code if unknown account status
        $errorCode = getCode('UNKNOWN_STATUS');
 
        // Generate constant name
-       $constantName = sprintf("ID_%s", $status);
+       $codeName = sprintf("ID_%s", $status);
 
        // Is the constant there?
-       if (isCodeSet($constantName)) {
+       if (isCodeSet($codeName)) {
                // Then get it!
-               $errorCode = getCode($constantName);
+               $errorCode = getCode($codeName);
        } else {
                // Unknown status
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
+               logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
        }
 
        // Return error code
@@ -2430,33 +2419,33 @@ function generateErrorCodeFromUserStatus ($status) {
 // Function to search for the last modifified file
 function searchDirsRecursive ($dir, &$last_changed) {
        // Get dir as array
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />\n";
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
        // Does it match what we are looking for? (We skip a lot files already!)
        // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
        $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
        $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
 
        // Walk through all entries
        foreach ($ds as $d) {
                // Generate proper FQFN
-               $FQFN = str_replace('//', '/', constant('PATH') . $dir. '/'. $d);
+               $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
 
                // Is it a file and readable?
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
+               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
                if (isDirectory($FQFN)) {
                        // $FQFN is a directory so also crawl into this directory
                        $newDir = $d;
                        if (!empty($dir)) $newDir = $dir . '/'. $d;
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />\n";
+                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
                        searchDirsRecursive($newDir, $last_changed);
                } elseif (isFileReadable($FQFN)) {
                        // $FQFN is a filename and no directory
                        $time = filemtime($FQFN);
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />\n";
+                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
                        if ($last_changed['time'] < $time) {
                                // This file is newer as the file before
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
+                               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
                                $last_changed['path_name'] = $FQFN;
                                $last_changed['time'] = $time;
                        } // END - if
@@ -2469,50 +2458,19 @@ function getActualVersion ($type = 'Revision') {
        // By default nothing is new... ;-)
        $new = false;
 
-       if (EXT_IS_ACTIVE('cache')) {
-               // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
-               if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') {
-                       // Force rebuild by URL parameter
-                       $new = true;
-               } elseif ((
-                       !isset($GLOBALS['cache_array']['revision'][$type])
-               ) || (
-                       count($GLOBALS['cache_array']['revision']) < 3
-               ) || (
-                       !$GLOBALS['cache_instance']->loadCacheFile('revision')
-               )) {
-                       // Out-dated cache
-                       $new = true;
-               } // END - if
-
-               // Is the cache file outdated/invalid?
-               if ($new === true) {
-                       // Reload the cache file
-                       $GLOBALS['cache_instance']->loadCacheFile('revision');
-
-                       // Destroy cache file
-                       $GLOBALS['cache_instance']->destroyCacheFile(false, true);
-
-                       // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
-                       unset($GLOBALS['cache_array']['revision']);
-
-                       // Reload load_cach-revison.php
-                       loadInclude('inc/loader/load_cache-revision.php');
-
-                       // Abort here
-                       return;
-               } // END - if
+       // Is the cache entry there?
+       if (isset($GLOBALS['cache_array']['revision'][$type])) {
+               // Found so increase cache hit
+               incrementStatsEntry('cache_hits');
 
-               // Return found value
+               // Return it
                return $GLOBALS['cache_array']['revision'][$type][0];
        } else {
-               // Old Version without ext-cache active (deprecated ?)
-
                // FQFN of revision file
-               $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
+               $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
 
-               // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
-               if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
+               // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
+               if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
                        // Forced rebuild of .revision file
                        $new = true;
                } else {
@@ -2526,13 +2484,18 @@ function getActualVersion ($type = 'Revision') {
 
                                // Get array for mapping information
                                $mapper = array_flip(getSearchFor());
-                               //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
+                               //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
 
                                // Is the content valid?
-                               if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
+                               if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
                                        // File needs update!
                                        $new = true;
                                } else {
+                                       // Generate fake cache entry
+                                       foreach ($mapper as $map=>$idx) {
+                                               $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
+                                       } // END - foreach
+
                                        // Return found value
                                        return trim($ins_vers[$mapper[$type]]);
                                }
@@ -2541,7 +2504,11 @@ function getActualVersion ($type = 'Revision') {
 
                // Has it been updated?
                if ($new === true)  {
+                       // Write it
                        writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
+
+                       // ... and call recursive
+                       return getActualVersion($type);
                } // END - if
        }
 }
@@ -2550,7 +2517,7 @@ function getActualVersion ($type = 'Revision') {
 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
 function getSearchFor () {
        // Add Revision, Date, Tag and Author
-       $searchFor = array('Revision', 'Date', 'Tag', 'Author');
+       $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
 
        // Return the created array
        return $searchFor;
@@ -2571,7 +2538,7 @@ function getArrayFromActualVersion () {
        $akt_vers = array();
 
        // Init value for counting the founded keywords
-       $res = 0;
+       $res = '0';
 
        // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
        searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
@@ -2586,27 +2553,27 @@ function getArrayFromActualVersion () {
        foreach ($searchFor as $search) {
                // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
                $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
-               // This trimms the search-result and puts it in the $akt_vers-return array
-               if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
+               // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
+               if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
        } // END - foreach
 
        // Save the last-changed filename for debugging
-       $akt_vers['File'] = $last_changed['path_name'];
+       $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
 
        // at least 3 keyword-Tags are needed for propper values
        if ($res && $res >= 3
-       && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
-       && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
-       && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
+       && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
+       && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
+       && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
                // Prepare content witch need special treadment
 
                // Prepare timestamp for date
-               preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
-               $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
+               preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
+               $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
 
                // Add author to the Tag if the author is set and is not quix0r (lead coder)
-               if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
-                       $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
+               if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
+                       $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
                } // END - if
 
        } else {
@@ -2615,14 +2582,15 @@ function getArrayFromActualVersion () {
 
                // Prepare content
                // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
-               if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
-               if (!isset($akt_vers['Date'])     || $akt_vers['Date']     == '') $akt_vers['Date']     = trim($version[9]);
-               if (!isset($akt_vers['Tag'])      || $akt_vers['Tag']      == '') $akt_vers['Tag']      = trim($version[8]);
-               if (!isset($akt_vers['Author'])   || $akt_vers['Author']   == '') $akt_vers['Author']   = "quix0r";
+               if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
+               if (!isset($GLOBALS['cache_array']['revision']['Date'])     || $GLOBALS['cache_array']['revision']['Date']     == '') $GLOBALS['cache_array']['revision']['Date']     = trim($version[9]);
+               if (!isset($GLOBALS['cache_array']['revision']['Tag'])      || $GLOBALS['cache_array']['revision']['Tag']      == '') $GLOBALS['cache_array']['revision']['Tag']      = trim($version[8]);
+               if (!isset($GLOBALS['cache_array']['revision']['Author'])   || $GLOBALS['cache_array']['revision']['Author']   == '') $GLOBALS['cache_array']['revision']['Author']   = 'quix0r';
+               if (!isset($GLOBALS['cache_array']['revision']['File'])     || $GLOBALS['cache_array']['revision']['File']     == '') $GLOBALS['cache_array']['revision']['File']     = trim($version[11]);
        }
 
        // Return prepared array
-       return $akt_vers;
+       return $GLOBALS['cache_array']['revision'];
 }
 
 // Back-ported from the new ship-simu engine. :-)
@@ -2648,23 +2616,35 @@ function debug_get_printable_backtrace () {
 
 // Output a debug backtrace to the user
 function debug_report_bug ($message = '') {
+       // Is this already called?
+       if (isset($GLOBALS[__FUNCTION__])) {
+               // Other backtrace
+               print 'Message:'.$message.'<br />Backtrace:<pre>';
+               debug_print_backtrace();
+               die('</pre>');
+       } // END - if
+
+       // Set this function as called
+       $GLOBALS[__FUNCTION__] = true;
+
        // Init message
        $debug = '';
+
        // Is the optional message set?
        if (!empty($message)) {
                // Use and log it
                $debug = sprintf("Note: %s<br />\n",
-               $message
+                       $message
                );
 
                // @TODO Add a little more infos here
-               DEBUG_LOG(__FUNCTION__, __LINE__, $message);
+               logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
        } // END - if
 
        // Add output
-       $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>inc/cache/debug.log</strong> in your report (you can now attach files):<pre>";
+       $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>" . getConfig('CACHE_PATH') . "debug.log</strong> in your report (you can now attach files):<pre>";
        $debug .= debug_get_printable_backtrace();
-       $debug .= "</pre>\nRequest-URI: " . $_SERVER['REQUEST_URI']."<br />\n";
+       $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
        $debug .= "Thank you for finding bugs.";
 
        // And abort here
@@ -2680,20 +2660,42 @@ function generateSeed () {
 }
 
 // Converts a message code to a human-readable message
-function convertCodeToMessage ($code) {
+function getMessageFromErrorCode ($code) {
        $message = '';
        switch ($code) {
+               case '': break;
                case getCode('LOGOUT_DONE')      : $message = getMessage('LOGOUT_DONE'); break;
                case getCode('LOGOUT_FAILED')    : $message = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
                case getCode('DATA_INVALID')     : $message = getMessage('MAIL_DATA_INVALID'); break;
                case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
                case getCode('ACCOUNT_LOCKED')   : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
-               case getCode('USER_404')         : $message = getMessage('USER_NOT_FOUND'); break;
+               case getCode('USER_404')         : $message = getMessage('USER_404'); break;
                case getCode('STATS_404')        : $message = getMessage('MAIL_STATS_404'); break;
                case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
+               case getCode('WRONG_PASS')       : $message = getMessage('LOGIN_WRONG_PASS'); break;
+               case getCode('WRONG_ID')         : $message = getMessage('LOGIN_WRONG_ID'); break;
+               case getCode('ID_LOCKED')        : $message = getMessage('LOGIN_ID_LOCKED'); break;
+               case getCode('ID_UNCONFIRMED')   : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
+               case getCode('ID_GUEST')         : $message = getMessage('LOGIN_ID_GUEST'); break;
+               case getCode('NO_COOKIES')       : $message = getMessage('LOGIN_NO_COOKIES'); break;
+               case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
+               case getCode('BEG_SAME_AS_OWN')  : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
+               case getCode('LOGIN_FAILED')     : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
+               case getCode('MODULE_MEM_ONLY')  : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
+               case getCode('OVERLENGTH')       : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
+               case getCode('URL_FOUND')        : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
+               case getCode('SUBJ_URL')         : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
+               case getCode('BLIST_URL')        : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
+               case getCode('NO_RECS_LEFT')     : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
+               case getCode('INVALID_TAGS')     : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
+               case getCode('MORE_POINTS')      : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
+               case getCode('MORE_RECEIVERS1')  : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
+               case getCode('MORE_RECEIVERS2')  : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
+               case getCode('MORE_RECEIVERS3')  : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
+               case getCode('INVALID_URL')      : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
 
                case getCode('ERROR_MAILID'):
-                       if (EXT_IS_ACTIVE($ext, true)) {
+                       if (isExtensionActive('mailid', true)) {
                                $message = getMessage('ERROR_CONFIRMING_MAIL');
                        } else {
                                $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
@@ -2701,24 +2703,46 @@ function convertCodeToMessage ($code) {
                        break;
 
                case getCode('EXTENSION_PROBLEM'):
-                       if (REQUEST_ISSET_GET('ext')) {
-                               $message = generateExtensionInactiveNotInstalledMessage(REQUEST_GET('ext'));
+                       if (isGetRequestElementSet('ext')) {
+                               $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
                        } else {
                                $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
                        }
                        break;
 
-               case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
-               case getCode('BEG_SAME_AS_OWN')  : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
-               case getCode('LOGIN_FAILED')     : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
-               case getCode('MODULE_MEM_ONLY')  : $message = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
+               case getCode('URL_TLOCK'):
+                       $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
+                               array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
+
+                       // Load timestamp from last order
+                       list($timestamp) = SQL_FETCHROW($result);
+                       $timestamp = generateDateTime($timestamp, 1);
+
+                       // Free memory
+                       SQL_FREERESULT($result);
+
+                       // Calculate hours...
+                       $STD = round(getConfig('url_tlock') / 60 / 60);
+
+                       // Minutes...
+                       $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
+
+                       // And seconds
+                       $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
+
+                       // Finally contruct the message
+                       // @TODO Rewrite this old lost code to a template
+                       $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
+                       {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
+                       {--MEMBER_LAST_TLOCK--}: ".$timestamp;
+                       break;
 
                default:
                        // Missing/invalid code
                        $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
 
                        // Log it
-                       DEBUG_LOG(__FUNCTION__, __LINE__, $message);
+                       logDebugMessage(__FUNCTION__, __LINE__, $message);
                        break;
        } // END - switch
 
@@ -2726,40 +2750,10 @@ function convertCodeToMessage ($code) {
        return $message;
 }
 
-// Generate a "link" for the given admin id (aid)
-function generateAdminLink ($aid) {
-       // No assigned admin is default
-       $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
-
-       // Zero? = Not assigned
-       if (bigintval($aid) > 0) {
-               // Load admin's login
-               $login = getAdminLogin($aid);
-
-               // Is the login valid?
-               if ($login != '***') {
-                       // Is the extension there?
-                       if (EXT_IS_ACTIVE('admins')) {
-                               // Admin found
-                               $admin = "<a href=\"".generateEmailLink(getAdminEmail($aid), 'admins')."\">" . $login."</a>";
-                       } else {
-                               // Extension not found
-                               $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
-                       }
-               } else {
-                       // Maybe deleted?
-                       $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
-               }
-       } // END - if
-
-       // Return result
-       return $admin;
-}
-
 // Compile characters which are allowed in URLs
 function compileUriCode ($code, $simple = true) {
        // Compile constants
-       if (!$simple) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
+       if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
 
        // Compile QUOT and other non-HTML codes
        $code = str_replace('{DOT}', '.',
@@ -2781,7 +2775,7 @@ function compileUriCode ($code, $simple = true) {
 // Function taken from user comments on www.php.net / function eregi()
 function isUrlValidSimple ($url) {
        // Prepare URL
-       $url = strip_tags(str_replace("\\", '', COMPILE_CODE(urldecode($url))));
+       $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
 
        // Allows http and https
        $http      = "(http|https)+(:\/\/)";
@@ -2829,7 +2823,7 @@ function isUrlValidSimple ($url) {
                        // @TODO Are these convertions still required?
                        $pat = str_replace('.', "&#92;&#46;", $pat);
                        $pat = str_replace('@', "&#92;&#64;", $pat);
-                       echo $key."=&nbsp;" . $pat . "<br />";
+                       //* DEBUG: */ outputHtml($key."=&nbsp;" . $pat . '<br />');
                } // END - if
 
                // Check if expression matches
@@ -2858,20 +2852,24 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
                $tmp = $FQFN . '.tmp';
 
                // Open the source file
-               $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . '<br />');
+               $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
 
                // Is the resource valid?
                if (is_resource($fp)) {
                        // Open temporary file
-                       $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . '<br />');
+                       $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
 
                        // Is the resource again valid?
                        if (is_resource($fp_tmp)) {
+                               // Mark temporary file as readable
+                               $GLOBALS['file_readable'][$tmp] = true;
+
+                               // Start reading
                                while (!feof($fp)) {
                                        // Read from source file
                                        $line = fgets ($fp, 1024);
 
-                                       if (strpos($line, $search) > -1) { $next = 0; $found = true; }
+                                       if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
 
                                        if ($next > -1) {
                                                if ($next === $seek) {
@@ -2901,90 +2899,45 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
                                copyFileVerified($tmp, $FQFN, 0644);
                                return removeFile($tmp);
                        } elseif ($found === false) {
-                               OUTPUT_HTML('<strong>CHANGE:</strong> 404!');
+                               outputHtml('<strong>CHANGE:</strong> 404!');
                        } else {
-                               OUTPUT_HTML('<strong>TMP:</strong> UNDONE!');
+                               outputHtml('<strong>TMP:</strong> UNDONE!');
                        }
                }
        } else {
                // File not found, not readable or writeable
-               OUTPUT_HTML('<strong>404:</strong> ' . $FQFN . '<br />');
+               outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
        }
 
        // An error was detected!
        return false;
 }
 // Send notification to admin
-function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
-       if (GET_EXT_VERSION('admins') >= '0.4.1') {
+function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
+       if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
                // Send new way
-               SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
+               sendAdminsEmails($subject, $templateName, $content, $userid);
        } else {
                // Send out out-dated way
-               $message = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
-               SEND_ADMIN_EMAILS($subject, $message);
+               $message = loadEmailTemplate($templateName, $content, $userid);
+               sendAdminEmails($subject, $message);
        }
 }
 
 // Debug message logger
-function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
+function logDebugMessage ($funcFile, $line, $message, $force=true) {
        // Is debug mode enabled?
        if ((isDebugModeEnabled()) || ($force === true)) {
                // Remove CRLF
                $message = str_replace("\r", '', str_replace("\n", '', $message));
 
                // Log this message away, we better don't call app_die() here to prevent an endless loop
-               $fp = fopen(constant('PATH') . 'inc/cache/debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
-               fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . strip_tags($message) . "\n");
+               $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
+               fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
                fclose($fp);
        } // END - if
 }
 
-// Load more reset scripts
-function runResetIncludes () {
-       // Is the reset set or old sql_patches?
-       if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
-               // Then abort here
-               DEBUG_LOG(__FUNCTION__, __LINE__, 'Cannot run reset! Please report this bug. Thanks');
-       } // END - if
-
-       // Get more daily reset scripts
-       SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
-
-       // Update database
-       if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
-
-       // Is the config entry set?
-       if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
-               // Create current week mark
-               $currWeek = date('W', time());
-
-               // Has it changed?
-               if (getConfig('last_week') != $currWeek) {
-                       // Include weekly reset scripts
-                       MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
-
-                       // Update config
-                       if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
-               } // END - if
-
-               // Create current month mark
-               $currMonth = date('m', time());
-
-               // Has it changed?
-               if (getConfig('last_month') != $currMonth) {
-                       // Include monthly reset scripts
-                       MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
-
-                       // Update config
-                       if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
-               } // END - if
-       } // END - if
-
-       // Run the filter
-       runFilterChain('load_includes');
-}
-
 // Handle extra values
 function handleExtraValues ($filterFunction, $value, $extraValue) {
        // Default is the value itself
@@ -3019,8 +2972,9 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
 }
 
 // Converts timestamp selections into a timestamp
-function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
+function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
        // Init test variable
+       $skip  = false;
        $test2 = '';
 
        // Get last three chars
@@ -3030,24 +2984,23 @@ function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
        if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
                // Found a multi-selection for timings?
                $test = substr($id, 0, -3);
-               if ((isset($POST[$test.'_ye'])) && (isset($POST[$test.'_mo'])) && (isset($POST[$test.'_we'])) && (isset($POST[$test.'_da'])) && (isset($POST[$test.'_ho'])) && (isset($POST[$test.'_mi'])) && (isset($POST[$test.'_se'])) && ($test != $test2)) {
+               if ((isset($postData[$test.'_ye'])) && (isset($postData[$test.'_mo'])) && (isset($postData[$test.'_we'])) && (isset($postData[$test.'_da'])) && (isset($postData[$test.'_ho'])) && (isset($postData[$test.'_mi'])) && (isset($postData[$test.'_se'])) && ($test != $test2)) {
                        // Generate timestamp
-                       $POST[$test] = createTimestampFromSelections($test, $POST);
-                       $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
+                       $postData[$test] = createTimestampFromSelections($test, $postData);
+                       $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
+                       $GLOBALS['skip_config'][$test] = true;
 
                        // Remove data from array
                        foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
-                               unset($POST[$test.'_' . $rem]);
+                               unset($postData[$test . '_' . $rem]);
                        } // END - foreach
 
                        // Skip adding
-                       unset($id); $skip = true; $test2 = $test;
+                       unset($id);
+                       $skip = true;
+                       $test2 = $test;
                } // END - if
-       } else {
-               // Process this entry
-               $skip = false;
-               $test2 = '';
-       }
+       } // END - if
 }
 
 // Reverts the german decimal comma into Computer decimal dot
@@ -3076,7 +3029,7 @@ function convertCommaToDot ($str) {
 }
 
 // Handle menu-depending failed logins and return the rendered content
-function HANDLE_LOGIN_FAILTURES ($accessLevel) {
+function handleLoginFailtures ($accessLevel) {
        // Default output is empty ;-)
        $OUT = '';
 
@@ -3085,14 +3038,14 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
                // Ignore zero values
                if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
                        // Non-guest has login failures found, get both data and prepare it for template
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
+                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
                        $content = array(
                                'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
-                               'last_failure'   => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
+                               'last_failure'   => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
                        );
 
                        // Load template
-                       $OUT = LOAD_TEMPLATE('login_failures', true, $content);
+                       $OUT = loadTemplate('login_failures', true, $content);
                } // END - if
 
                // Reset session data
@@ -3105,59 +3058,43 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
 }
 
 // Rebuild cache
-function rebuildCacheFiles ($cache, $inc = '') {
+function rebuildCacheFile ($cache, $inc = '', $force = false) {
+       // Debug message
+       /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
+
        // Shall I remove the cache file?
-       if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
+       if (isCacheInstanceValid()) {
                // Rebuild cache
                if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
                        // Destroy it
-                       $GLOBALS['cache_instance']->destroyCacheFile();
+                       $GLOBALS['cache_instance']->removeCacheFile($force);
                } // END - if
 
                // Include file given?
                if (!empty($inc)) {
                        // Construct FQFN
-                       $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
+                       $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
 
                        // Is the include there?
-                       if (isIncludeReadable($INC)) {
+                       if (isIncludeReadable($inc)) {
                                // And rebuild it from scratch
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
-                               loadInclude($INC);
+                               //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
+                               loadInclude($inc);
                        } else {
                                // Include not found!
-                               DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
+                               logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
                        }
                } // END - if
        } // END - if
 }
 
-// Purge admin menu cache
-function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
-       // Is the cache extension enabled or no cache instance or admin menu cache disabled?
-       if (!EXT_IS_ACTIVE('cache')) {
-               // Cache extension not active
-               return false;
-       } elseif (!isCacheInstanceValid()) {
-               // No cache instance!
-               DEBUG_LOG(__FUNCTION__, __LINE__, 'No cache instance found.');
-               return false;
-       } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
-               // Caching disabled (currently experiemental!)
-               return false;
-       }
-
-       // Experiemental feature!
-       debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
-}
-
 // Determines the real remote address
 function determineRealRemoteAddress () {
        // Is a proxy in use?
-       if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
+       if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                // Proxy was used
                $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
-       } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
+       } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                // Yet, another proxy
                $address = $_SERVER['HTTP_CLIENT_IP'];
        } else {
@@ -3166,7 +3103,7 @@ function determineRealRemoteAddress () {
        }
 
        // This strips out the real address from proxy output
-       if (strstr($address, ',')){
+       if (strstr($address, ',')) {
                $addressArray = explode(',', $address);
                $address = $addressArray[0];
        } // END - if
@@ -3200,47 +3137,70 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
                );
 
                // Mail inserted into bonus pool
-               if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
+               if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
        } elseif ($output) {
                // More entered than can be reached!
-               LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
+               loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
        } else {
                // Debug log
-               DEBUG_LOG(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
+               logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
        }
 }
 
 // Determines referal id and sets it
-function DETERMINE_REFID () {
+function determineReferalId () {
+       // Skip this in non-html-mode and outside ref.php
+       if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
+
        // Check if refid is set
-       if ((REQUEST_ISSET_GET('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
+       if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
+               // This is fine...
+       } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
                // The variable user comes from the click-counter script click.php and we only accept this here
-               $GLOBALS['refid'] = bigintval(REQUEST_GET('user'));
-       } elseif (REQUEST_ISSET_POST('refid')) {
+               $GLOBALS['refid'] = bigintval(getRequestElement('user'));
+       } elseif (isPostRequestElementSet('refid')) {
                // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
-               $GLOBALS['refid'] = strip_tags(REQUEST_POST('refid'));
-       } elseif (REQUEST_ISSET_GET('refid')) {
+               $GLOBALS['refid'] = secureString(postRequestElement('refid'));
+       } elseif (isGetRequestElementSet('refid')) {
                // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
-               $GLOBALS['refid'] = strip_tags(REQUEST_GET('refid'));
-       } elseif (REQUEST_ISSET_GET('ref')) {
+               $GLOBALS['refid'] = secureString(getRequestElement('refid'));
+       } elseif (isGetRequestElementSet('ref')) {
                // Set refid=ref (the referal link uses such variable)
-               $GLOBALS['refid'] = strip_tags(REQUEST_GET('ref'));
+               $GLOBALS['refid'] = secureString(getRequestElement('ref'));
        } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
                // Set session refid als global
                $GLOBALS['refid'] = bigintval(getSession('refid'));
-       } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
-               // Set default refid as refid in URL
-               $GLOBALS['refid'] = getConfig('def_refid');
-       } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
+       } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
                // Select a random user which has confirmed enougth mails
                $GLOBALS['refid'] = determineRandomReferalId();
+       } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
+               // Set default refid as refid in URL
+               $GLOBALS['refid'] = getConfig('def_refid');
        } else {
-               // No default ID when sql_patches is not installed or none set
-               $GLOBALS['refid'] = 0;
+               // No default id when sql_patches is not installed or none set
+               $GLOBALS['refid'] = '0';
        }
 
        // Set cookie when default refid > 0
-       if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
+       if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
+               // Default is not found
+               $found = false;
+
+               // Do we have nickname or userid set?
+               if (isNicknameUsed($GLOBALS['refid'])) {
+                       // Nickname in URL, so load the id
+                       $found = fetchUserData($GLOBALS['refid'], 'nickname');
+               } elseif ($GLOBALS['refid'] > 0) {
+                       // Direct userid entered
+                       $found = fetchUserData($GLOBALS['refid']);
+               }
+
+               // Is the record valid?
+               if (($found === false) || (!isUserDataValid())) {
+                       // No, then reset referal id
+                       $GLOBALS['refid'] = getConfig('def_refid');
+               } // END - if
+
                // Set cookie
                setSession('refid', $GLOBALS['refid']);
        } // END - if
@@ -3249,25 +3209,24 @@ function DETERMINE_REFID () {
        return $GLOBALS['refid'];
 }
 
-// Enables the reset mode. Only call this function if you really want the
-// reset to be run!
-function enableResetMode () {
+// Enables the reset mode and runs it
+function doReset () {
        // Enable the reset mode
        $GLOBALS['reset_enabled'] = true;
 
        // Run filters
-       runFilterChain('reset_enabled');
+       runFilterChain('reset');
 }
 
 // Our shutdown-function
 function shutdown () {
        // Call the filter chain 'shutdown'
-       runFilterChain('shutdown', null, false);
+       runFilterChain('shutdown', null);
 
        if (SQL_IS_LINK_UP()) {
                // Close link
                SQL_CLOSE(__FILE__, __LINE__);
-       } elseif ((!isInstalling()) && (isInstalled())) {
+       } elseif (!isInstallationPhase()) {
                // No database link
                addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
        }
@@ -3276,45 +3235,54 @@ function shutdown () {
        exit;
 }
 
-// Setter for userid
-function setUserId ($userid) {
-       $GLOBALS['userid'] = bigintval($userid);
+// Init member id
+function initMemberId () {
+       $GLOBALS['member_id'] = '0';
+}
+
+// Setter for member id
+function setMemberId ($memberid) {
+       // We should not set member id to zero
+       if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
+
+       // Set it secured
+       $GLOBALS['member_id'] = bigintval($memberid);
 }
 
-// Getter for userid or returns zero
-function getUserId () {
-       // Default userid
-       $userid = 0;
+// Getter for member id or returns zero
+function getMemberId () {
+       // Default member id
+       $memberid = '0';
 
-       // Is the userid set?
-       if (isUserIdSet()) {
+       // Is the member id set?
+       if (isMemberIdSet()) {
                // Then use it
-               $userid = $GLOBALS['userid'];
+               $memberid = $GLOBALS['member_id'];
        } // END - if
 
        // Return it
-       return $userid;
+       return $memberid;
 }
 
-// Checks ether the userid is set
-function isUserIdSet () {
-       return (isset($GLOBALS['userid']));
+// Checks ether the member id is set
+function isMemberIdSet () {
+       return (isset($GLOBALS['member_id']));
 }
 
 // Handle message codes from URL
 function handleCodeMessage () {
-       if (REQUEST_ISSET_GET('msg')) {
+       if (isGetRequestElementSet('code')) {
                // Default extension is 'unknown'
                $ext = 'unknown';
 
                // Is extension given?
-               if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
+               if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
 
-               // Convert the 'msg' parameter from URL to a human-readable message
-               $message = convertCodeToMessage(REQUEST_GET('msg'));
+               // Convert the 'code' parameter from URL to a human-readable message
+               $message = getMessageFromErrorCode(getRequestElement('code'));
 
                // Load message template
-               LOAD_TEMPLATE('message', false, $message);
+               loadTemplate('message', false, $message);
        } // END - if
 }
 
@@ -3345,14 +3313,14 @@ function generateExtensionInactiveMessage ($ext_name) {
        // Is the extension empty?
        if (empty($ext_name)) {
                // This should not happen
-               trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
+               debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
        } // END - if
 
        // Default message
        $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
 
        // Is an admin logged in?
-       if (IS_ADMIN()) {
+       if (isAdmin()) {
                // Then output admin message
                $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
        } // END - if
@@ -3366,14 +3334,14 @@ function generateExtensionNotInstalledMessage ($ext_name) {
        // Is the extension empty?
        if (empty($ext_name)) {
                // This should not happen
-               trigger_error(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
+               debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
        } // END - if
 
        // Default message
        $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
 
        // Is an admin logged in?
-       if (IS_ADMIN()) {
+       if (isAdmin()) {
                // Then output admin message
                $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
        } // END - if
@@ -3399,7 +3367,7 @@ function generateExtensionInactiveNotInstalledMessage ($ext_name) {
                        break;
 
                default: // Should not happen!
-                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
+                       logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
                        $message = sprintf("Invalid state of extension %s detected.", $ext_name);
                        break;
        } // END - switch
@@ -3418,25 +3386,25 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
        $excludeArray[] = '.svn';
        $excludeArray[] = '.htaccess';
 
-       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
        // Init includes
        $files = array();
 
        // Open directory
-       $dirPointer = opendir(constant('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
+       $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
 
        // Read all entries
        while ($baseFile = readdir($dirPointer)) {
                // Exclude '.', '..' and entries in $excludeArray automatically
                if (in_array($baseFile, $excludeArray, true))  {
                        // Exclude them
-                       //* DEBUG: */ print 'excluded=' . $baseFile . '<br />';
+                       //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
                        continue;
                } // END - if
 
                // Construct include filename and FQFN
-               $fileName = $baseDir . '/' . $baseFile;
-               $FQFN = constant('PATH') . $fileName;
+               $fileName = $baseDir . $baseFile;
+               $FQFN = getConfig('PATH') . $fileName;
 
                // Remove double slashes
                $FQFN = str_replace('//', '/', $FQFN);
@@ -3444,9 +3412,9 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
                // Check if the base filename matches an exclusion pattern and if the pattern is not empty
                if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
                        // These Lines are only for debugging!!
-                       //* DEBUG: */ print 'baseDir:' . $baseDir . '<br />';
-                       //* DEBUG: */ print 'baseFile:' . $baseFile . '<br />';
-                       //* DEBUG: */ print 'FQFN:' . $FQFN . '<br />';
+                       //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
+                       //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
+                       //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
 
                        // Exclude this one
                        continue;
@@ -3455,39 +3423,36 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
                // Skip also files with non-matching prefix genericly
                if (($recursive === true) && (isDirectory($FQFN))) {
                        // Is a redirectory so read it as well
-                       $files = merge_array($files, getArrayFromDirectory ($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
+                       $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
 
                        // And skip further processing
                        continue;
                } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
                        // Skip this file
-                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
                        continue;
                } elseif (!isFileReadable($FQFN)) {
                        // Not readable so skip it
-                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
                        continue;
                }
 
                // Is the file a PHP script or other?
-               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
                if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
                        // Is this a valid include file?
                        if ($extension == '.php') {
                                // Remove both for extension name
                                $extName = substr($baseFile, strlen($prefix), -4);
 
-                               // Try to find it
-                               $extId = GET_EXT_ID($extName);
-
                                // Is the extension valid and active?
-                               if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
+                               if (isExtensionNameValid($extName)) {
                                        // Then add this file
-                                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
+                                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
                                        $files[] = $fileName;
-                               } elseif ($extId == 0) {
+                               } else {
                                        // Add non-extension files as well
-                                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
+                                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
                                        if ($addBaseDir === true) {
                                                $files[] = $fileName;
                                        } else {
@@ -3498,7 +3463,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
                                // We found .php file but should not search for them, why?
                                debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
                        }
-               } else {
+               } elseif (substr($baseFile, -4, 4) == $extension) {
                        // Other, generic file found
                        $files[] = $fileName;
                }
@@ -3511,10 +3476,217 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
        asort($files);
 
        // Return array with include files
-       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '- Left!');
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
        return $files;
 }
 
+// Maps a module name into a database table name
+function mapModuleToTable ($moduleName) {
+       // Map only these, still lame code...
+       switch ($moduleName) {
+               // 'index' is the guest's menu
+               case 'index': $moduleName = 'guest';  break;
+               // ... and 'login' the member's menu
+               case 'login': $moduleName = 'member'; break;
+               // Anything else will not be mapped, silently.
+       } // END - switch
+
+       // Return result
+       return $moduleName;
+}
+
+// Add SQL debug data to array for later output
+function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
+       // Already executed?
+       if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
+               // Then abort here, we don't need to profile a query twice
+               return;
+       } // END - if
+
+       // Remeber this as profiled (or not, but we don't care here)
+       $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
+
+       // Do we have cache?
+       if (!isset($GLOBALS['debug_sql_available'])) {
+               // Check it and cache it in $GLOBALS
+               $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
+       } // END - if
+       
+       // Don't execute anything here if we don't need or ext-other is missing
+       if ($GLOBALS['debug_sql_available'] === false) {
+               return;
+       } // END - if
+
+       // Generate record
+       $record = array(
+               'num_rows' => SQL_NUMROWS($result),
+               'affected' => SQL_AFFECTEDROWS(),
+               'sql_str'  => $sqlString,
+               'timing'   => $timing,
+               'file'     => basename($F),
+               'line'     => $L
+       );
+
+       // Add it
+       $GLOBALS['debug_sqls'][] = $record;
+}
+
+// Initializes the cache instance
+function initCacheInstance () {
+       // Load include for CacheSystem class
+       loadIncludeOnce('inc/classes/cachesystem.class.php');
+
+       // Initialize cache system only when it's needed
+       $GLOBALS['cache_instance'] = new CacheSystem();
+       if ($GLOBALS['cache_instance']->getStatus() != 'done') {
+               // Failed to initialize cache sustem
+               addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
+       } // END - if
+}
+
+// Getter for message from array or raw message
+function getMessageFromIndexedArray ($message, $pos, $array) {
+       // Check if the requested message was found in array
+       if (isset($array[$pos])) {
+               // ... if yes then use it!
+               $ret = $array[$pos];
+       } else {
+               // ... else use default message
+               $ret = $message;
+       }
+
+       // Return result
+       return $ret;
+}
+
+// Print code with line numbers
+function linenumberCode ($code)    {
+       if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
+       $count_lines = count($codeE);
+
+       $r = 'Line | Code:<br />';
+       foreach($codeE as $line => $c) {
+               $r .= '<div class="line"><span class="linenum">';
+               if ($count_lines == 1) {
+                       $r .= 1;
+               } else {
+                       $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
+               }
+               $r .= '</span>|';
+
+               // Add code
+               $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
+       }
+
+       return '<div class="code">' . $r . '</div>';
+}
+
+// Convert ';' to ', ' for e.g. receiver list
+function convertReceivers ($old) {
+       return str_replace(';', ', ', $old);
+}
+
+// Determines the right page title
+function determinePageTitle () {
+       // Config and database connection valid?
+       if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+               // Init title
+               $TITLE = '';
+
+               // Title decoration enabled?
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
+
+               // Do we have some extra title?
+               if (isExtraTitleSet()) {
+                       // Then prepent it
+                       $TITLE .= getExtraTitle() . ' by ';
+               } // END - if
+
+               // Add main title
+               $TITLE .= getConfig('MAIN_TITLE');
+
+               // Add title of module? (middle decoration will also be added!)
+               if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
+                       $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
+               } // END - if
+
+               // Add title from what file
+               $mode = '';
+               if (getModule() == 'login') $mode = 'member';
+               elseif (getModule() == 'index') $mode = 'guest';
+               if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
+
+               // Add title decorations? (right)
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
+
+               // Remember title in constant for the template
+               $pageTitle = $TITLE;
+       } elseif ((isInstalled()) && (isAdminRegistered())) {
+               // Installed, admin registered but no ext-sql_patches
+               $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
+       } elseif ((isInstalled()) && (!isAdminRegistered())) {
+               // Installed but no admin registered
+               $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
+       } elseif ((!isInstalled()) || (!isAdminRegistered())) {
+               // Installation mode
+               $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
+       } else {
+               // Configuration not found!
+               $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
+
+               // Do not add the fatal message in installation mode
+               if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
+       }
+
+       // Return title
+       return $pageTitle;
+}
+
+// Checks wethere there is a cache file there. This function is cached.
+function isTemplateCached ($template) {
+       // Do we have cached this result?
+       if (!isset($GLOBALS['template_cache'][$template])) {
+               // Generate FQFN
+               $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+               // Is it there?
+               $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
+       } // END - if
+
+       // Return it
+       return $GLOBALS['template_cache'][$template];
+}
+
+// Flushes non-flushed template cache to disk
+function flushTemplateCache ($template, $eval) {
+       // Is this cache flushed?
+       if ((!isTemplateCached($template)) && ($eval != '404')) {
+               // Generate FQFN
+               $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+               // Replace username with a call
+               $eval = str_replace('$username', '".getUsername()."', $eval);
+
+               // And flush it
+               writeToFile($FQFN, $eval, true);
+       } // END - if
+}
+
+// Reads a template cache
+function readTemplateCache ($template) {
+       // Check it again
+       if (isTemplateCached($template)) {
+               // Generate FQFN
+               $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+               // And read from it
+               $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
+       } // END - if
+
+       // And return it
+       return $GLOBALS['template_eval'][$template];
+}
+
 //////////////////////////////////////////////////
 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
 //////////////////////////////////////////////////
@@ -3528,5 +3700,29 @@ if (!function_exists('html_entity_decode')) {
        }
 } // END - if
 
+if (!function_exists('http_build_query')) {
+       // Taken from documentation on www.php.net, credits to Marco K. (Germany)
+       function http_build_query($data, $prefix='', $sep='', $key='') {
+               $ret = array();
+               foreach ((array)$data as $k => $v) {
+                       if (is_int($k) && $prefix != null) {
+                               $k = urlencode($prefix . $k);
+                       } // END - if
+
+                       if ((!empty($key)) || ($key === 0))  $k = $key.'['.urlencode($k).']';
+
+                       if (is_array($v) || is_object($v)) {
+                               array_push($ret, http_build_query($v, '', $sep, $k));
+                       } else {
+                               array_push($ret, $k.'='.urlencode($v));
+                       }
+               } // END - foreach
+
+               if (empty($sep)) $sep = ini_get('arg_separator.output');
+
+               return implode($sep, $ret);
+       }
+}// // END - if
+
 // [EOF]
 ?>