Possible fix for non-working nickname referal link
[mailer.git] / inc / functions.php
index e32114a46e717753adf5828f7992b5bba29a0e9f..c22a559d614a9168bc1a520b162191694ef2c01f 100644 (file)
@@ -43,6 +43,9 @@ if (!defined('__SECURITY')) {
 
 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
 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();
@@ -116,12 +119,12 @@ function outputHtml ($htmlCode, $newLine = true) {
                sendHeader('Content-language: ' . getLanguage());
 
                // Extension 'rewrite' installed?
-               if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
+               if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
                // Init counter
-               $cnt = 0;
+               $cnt = '0';
 
                // Compile and run finished rendered HTML code
                while (((strpos($GLOBALS['output'], '{--') > 0) || (strpos($GLOBALS['output'], '{!') > 0) || (strpos($GLOBALS['output'], '{?') > 0)) && ($cnt < 3)) {
@@ -136,7 +139,7 @@ function outputHtml ($htmlCode, $newLine = true) {
                        // Was that eval okay?
                        if (empty($newContent)) {
                                // Something went wrong!
-                               debug_report_bug('Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
+                               debug_report_bug('Evaluation error:<pre>' . linenumberCode($eval) . '</pre>');
                        } // END - if
                        $GLOBALS['output'] = $newContent;
 
@@ -148,7 +151,7 @@ function outputHtml ($htmlCode, $newLine = true) {
                outputRawCode($GLOBALS['output']);
        } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
                // Rewrite links when rewrite extension is active
-               if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
+               if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
@@ -205,7 +208,7 @@ function addFatalMessage ($F, $L, $message, $extra='') {
 // 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])) {
@@ -226,7 +229,10 @@ function loadTemplate ($template, $return=false, $content=array()) {
        global $DATA;
 
        // Do we have cache?
-       if (!isset($GLOBALS['template_eval'][$template])) {
+       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();
 
@@ -238,41 +244,7 @@ function loadTemplate ($template, $return=false, $content=array()) {
 
                // Init some data
                $ret = '';
-               if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
-
-               // Generate date/time string
-               $date_time = generateDateTime(time(), '1');
-
-               // Is content an array
-               if (is_array($content)) $content['date_time'] = $date_time;
-
-               // @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 content an array?
-                       if (is_array($content)) {
-                               // Merge data
-                               $content = merge_array($content, SQL_FETCHARRAY($result));
-
-                               // Translate gender
-                               $content['gender'] = translateGender($content['gender']);
-                       } 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);
-                               logDebugMessage(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
-                       }
-
-                       // Free result
-                       SQL_FREERESULT($result);
-               } // END - if
+               if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
 
                // Base directory
                $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
@@ -353,12 +325,15 @@ function loadTemplate ($template, $return=false, $content=array()) {
                        $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 ($GLOBALS['output_mode'] == 0) {
+                               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($GLOBALS['tpl_content'])) . '";';
+                                       $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'])) . '";';
@@ -374,20 +349,20 @@ function loadTemplate ($template, $return=false, $content=array()) {
 
                        // Eval the code
                        eval($GLOBALS['template_eval'][$template]);
-               } else {
-                       // No file!
-                       $GLOBALS['template_eval'][$template] = '404';
-               }
-       } elseif (((isAdmin()) || ((isInstalling()) && (!isInstalled()))) && ($GLOBALS['template_eval'][$template] == '404')) {
-               // Only admins shall see this warning or when installation mode is active
-               $ret = '<br /><span class=\\"guest_failed\\">{--TEMPLATE_404--}</span><br />
+               } 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 />\";';
+<br /><br />';
+               } else {
+                       // No file!
+                       $GLOBALS['template_eval'][$template] = '404';
+               }
        } else {
                // Eval the code
                eval($GLOBALS['template_eval'][$template]);
@@ -400,7 +375,7 @@ function loadTemplate ($template, $return=false, $content=array()) {
                        // Return the HTML code
                        return $ret;
                } else {
-                       // Output direct
+                       // Output directly
                        outputHtml($ret);
                }
        } elseif (isDebugModeEnabled()) {
@@ -413,9 +388,6 @@ function loadTemplate ($template, $return=false, $content=array()) {
 function loadEmailTemplate ($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);
 
@@ -443,7 +415,7 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
 
        // Expiration in a nice output format
        // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
-       if (getConfig('auto_purge') == 0) {
+       if (getConfig('auto_purge') == '0') {
                // Will never expire!
                $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
        } else {
@@ -458,28 +430,25 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        } // END - if
 
        // Load user's data
-       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />");
+       //* 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 (isExtensionActive('nickname')) {
+               if (isNicknameUsed($UID)) {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
-                       // 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__);
+                       // Load by nickname
+                       fetchUserData($UID, 'nickname');
                } else {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
-                       /// 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__);
+                       /// Load by userid
+                       fetchUserData($UID);
                }
 
-               // Fetch and merge data
+               // Merge data if valid
                //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
-               $content = merge_array($content, SQL_FETCHARRAY($result));
+               if (isUserDataValid()) {
+                       $content = merge_array($content, getUserDataArray());
+               } // END - if
                //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
-
-               // Free result
-               SQL_FREERESULT($result);
        } // END - if
 
        // Translate M to male or F to female if present
@@ -527,10 +496,9 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        if (isFileReadable($FQFN)) {
                // The local file does exists so we load it. :)
                $GLOBALS['tpl_content'] = readFromFile($FQFN);
-               $GLOBALS['tpl_content'] = SQL_ESCAPE($GLOBALS['tpl_content']);
 
                // Run code
-               $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode($GLOBALS['tpl_content'])."\");";
+               $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode(smartAddSlashes($GLOBALS['tpl_content']))."\");";
                eval($GLOBALS['tpl_content']);
        } elseif (!empty($template)) {
                // Template file not found!
@@ -561,7 +529,7 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        unset($DATA);
 
        // Compile the code and eval it
-       $eval = '$newContent = "' . compileCode(addSmartSlashes($newContent)) . '";';
+       $eval = '$newContent = "' . compileRawCode(smartAddSlashes($newContent)) . '";';
        eval($eval);
 
        // Return content
@@ -573,7 +541,7 @@ 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(\"".compileCode(smartAddSlashes($subject))."\");");
+       eval("\$subject = decodeEntities(\"".compileRawCode(smartAddSlashes($subject))."\");");
 
        // Set from header
        if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
@@ -583,22 +551,14 @@ function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '
                        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: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
-
                        // 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 = getConfig('WEBMASTER');
                        }
-
-                       // Free result
-                       SQL_FREERESULT($result_email);
                }
        } elseif ($toEmail == '0') {
                // Is the webmaster!
@@ -627,21 +587,21 @@ function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '
        }
 
        // Compile "TO"
-       eval("\$toEmail = \"".compileCode(smartAddSlashes($toEmail))."\";");
+       eval("\$toEmail = \"".compileRawCode(smartAddSlashes($toEmail))."\";");
 
        // Compile "MSG"
-       eval("\$message = \"".compileCode(smartAddSlashes($message))."\";");
+       eval("\$message = \"".compileRawCode(smartAddSlashes($message))."\";");
 
        // Fix HTML parameter (default is no!)
        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
-               outputHtml("<pre>
-".htmlentities(trim($mailHeader))."
-To      : " . $toEmail."
-Subject : " . $subject."
-Message : " . $message."
-</pre>\n");
+               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);
@@ -671,6 +631,11 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
 
                // get new instance
                $mail = new PHPMailer();
+
+               // Set charset to UTF-8
+               $mail->CharSet('UTF-8');
+
+               // Path for PHPMailer
                $mail->PluginDir  = sprintf("%sinc/phpmailer/", getConfig('PATH'));
 
                $mail->IsSMTP();
@@ -706,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
 
@@ -736,7 +701,7 @@ 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
@@ -744,10 +709,10 @@ function generateDateTime ($time, $mode = '0') {
        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 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;
                                default:
                                        logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
                                        break;
@@ -756,10 +721,10 @@ function generateDateTime ($time, $mode = '0') {
 
                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;
+                               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;
@@ -806,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');
@@ -817,12 +782,12 @@ function translateComma ($dotted, $cut = true, $max = 0) {
        if ($max > 0) $maxComma = $max;
 
        // Cut zeros off?
-       if (($cut === true) && ($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
 
@@ -921,7 +886,7 @@ function countSelection ($array) {
        } // END - if
 
        // Init count
-       $ret = 0;
+       $ret = '0';
 
        // Count all entries
        foreach ($array as $key => $selected) {
@@ -935,24 +900,31 @@ function countSelection ($array) {
 
 // Generate XHTML code for the CAPTCHA
 function generateCaptchaCode ($code, $type, $DATA, $userid) {
-       return '<IMG border="0" alt="Code" src="{?URL?}/mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '" />';
+       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://')) {
@@ -962,7 +934,7 @@ function redirectToUrl ($URL) {
 
        // Three different debug ways...
        //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
-       //* DEBUG: */ logDebugMessage(__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
@@ -1027,6 +999,30 @@ function compileCode ($code, $simple = false, $constants = true, $full = true) {
                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
+               return $code;
+       } // END - if
+
        // Init replacement-array with full security characters
        $secChars = $GLOBALS['security_chars'];
 
@@ -1102,7 +1098,7 @@ function compileCode ($code, $simple = false, $constants = true, $full = true) {
                } // END - foreach
        } // END - if
 
-       // Return compiled code
+       // Return it
        return $code;
 }
 
@@ -1122,7 +1118,7 @@ function compileCode ($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) {
@@ -1158,19 +1154,19 @@ function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums =
 }
 
 //
-function addSelectionBox ($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) {
@@ -1242,7 +1238,7 @@ function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
 
                case 'sec':
                case 'min':
-                       for ($idx = 0; $idx < 60; $idx+=5) {
+                       for ($idx = '0'; $idx < 60; $idx+=5) {
                                if (strlen($idx) == 1) $idx = '0' . $idx;
                                $OUT .= "<option value=\"" . $idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
@@ -1251,7 +1247,7 @@ function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
                        break;
 
                case 'hour':
-                       for ($idx = 0; $idx < 24; $idx++) {
+                       for ($idx = '0'; $idx < 24; $idx++) {
                                if (strlen($idx) == 1) $idx = '0' . $idx;
                                $OUT .= "<option value=\"" . $idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
@@ -1296,12 +1292,12 @@ function generateRandomCode ($length, $code, $userid, $DATA = '') {
        $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
        $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
        $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
-       $data .= getConfig('ENCRYPT_SEPERATOR') . getUserId();
+       $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'));
 
@@ -1309,7 +1305,7 @@ function generateRandomCode ($length, $code, $userid, $DATA = '') {
                $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(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
@@ -1317,8 +1313,8 @@ function generateRandomCode ($length, $code, $userid, $DATA = '') {
 
        // 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);
@@ -1333,13 +1329,12 @@ function bigintval ($num, $castValue = true) {
        $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
@@ -1347,17 +1342,24 @@ function bigintval ($num, $castValue = true) {
 }
 
 // Insert the code in $img_code into jpeg or PNG image
-function generateImageOrCode ($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;
+               debug_report_bug('img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
        } elseif ($headerSent === false) {
-               // Return in an HTML code code
+               // 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", getConfig('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'))
@@ -1403,7 +1405,7 @@ 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));
@@ -1434,7 +1436,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
        //* 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
@@ -1493,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";
@@ -1506,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"';
@@ -1520,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";
@@ -1533,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";
@@ -1546,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";
@@ -1559,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";
@@ -1572,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";
@@ -1592,10 +1594,10 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
 //
 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)
@@ -1655,7 +1657,7 @@ function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=fals
        $NAV = '';
        for ($page = 1; $page <= $PAGES; $page++) {
                // Is the page currently selected or shall we generate a link to it?
-               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
+               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
                        // Is currently selected, so only highlight it
                        $NAV .= '<strong>-';
                } else {
@@ -1669,7 +1671,7 @@ function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=fals
                        $NAV .= '">';
                }
                $NAV .= $page;
-               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
+               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
                        // Is currently selected, so only highlight it
                        $NAV .= '-</strong>';
                } else {
@@ -1718,7 +1720,7 @@ function extractHostnameFromUrl (&$script) {
        if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
 
        // Generate relative URL
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />");
+       //* 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));
@@ -1727,7 +1729,7 @@ function extractHostnameFromUrl (&$script) {
                $script = substr($script, (strlen($url) + 8));
        }
 
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />");
+       //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
        if (substr($script, 0, 1) == '/') $script = substr($script, 1);
 
        // Return host name
@@ -1735,10 +1737,25 @@ function extractHostnameFromUrl (&$script) {
 }
 
 // Send a GET request
-function sendGetRequest ($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');
@@ -1768,14 +1785,11 @@ function sendPostRequest ($script, $postData) {
                return array('', '', '');
        } // END - if
 
-       // Compile the script name
-       $script = compileCode($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');
@@ -1798,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('', '', '');
@@ -1813,10 +1827,10 @@ function sendRawRequest ($host, $request) {
        } // END - if
 
        // Open connection
-       //* DEBUG: */ die("SCRIPT=" . $script."<br />");
+       //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
        if ($useProxy === true) {
                // Connect to host through proxy connection
-               $fp = @fsockopen(compileCode(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);
@@ -1837,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(compileCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileCode(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
 
@@ -1911,9 +1925,6 @@ function sendRawRequest ($host, $request) {
 
 // Taken from www.php.net eregi() user comments
 function isEmailValid ($email) {
-       // Compile email
-       $email = compileCode($email);
-
        // Check first part of email address
        $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
 
@@ -1931,11 +1942,11 @@ function isEmailValid ($email) {
 function isUrlValid ($URL, $compile=true) {
        // Trim URL a little
        $URL = trim(urldecode($URL));
-       //* DEBUG: */ outputHtml($URL."<br />");
+       //* DEBUG: */ outputHtml($URL.'<br />');
 
        // Compile some chars out...
        if ($compile === true) $URL = compileUriCode($URL, false, false, false);
-       //* DEBUG: */ outputHtml($URL."<br />");
+       //* DEBUG: */ outputHtml($URL.'<br />');
 
        // Check for the extension filter
        if (isExtensionActive('filter')) {
@@ -2014,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 (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('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
@@ -2052,8 +2063,15 @@ function generateHash ($plainText, $salt = '') {
                //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
        } else {
                // Use given salt
+               //* DEBUG: */ print 'salt=' . $salt . '<br />';
                $salt = substr($salt, 0, getConfig('salt_length'));
-               //* DEBUG: */ outputHtml("GIVEN={$salt}<br />");
+               //* 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
@@ -2079,7 +2097,7 @@ function scrambleString($str) {
 
        // Scramble string here
        //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
-       for ($idx = 0; $idx < strlen($str); $idx++) {
+       for ($idx = '0'; $idx < strlen($str); $idx++) {
                // Get char on scrambled position
                $char = substr($str, $scrambleNums[$idx], 1);
 
@@ -2106,7 +2124,7 @@ function descrambleString($str) {
        // Begin descrambling
        $orig = str_repeat(' ', 40);
        //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
-       for ($idx = 0; $idx < 40; $idx++) {
+       for ($idx = '0'; $idx < 40; $idx++) {
                $char = substr($str, $idx, 1);
                $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
        } // END - for
@@ -2122,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));
 
@@ -2146,10 +2164,10 @@ function generatePassString ($passHash) {
        $ret = $passHash;
 
        // Is a secret key and master salt already initialized?
-       if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('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);
@@ -2158,16 +2176,17 @@ 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: */ outputHtml("*" . $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 />");
+               //* DEBUG: */ print('ret='.$ret.'<br />');
        } else {
                // Hash it simple
                //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
@@ -2235,7 +2254,7 @@ function displayParsingTime() {
        $start = explode(' ', $GLOBALS['startTime']);
        $end = explode(' ', $endTime);
        $runTime = $end[0] - $start[0];
-       if ($runTime < 0) $runTime = 0;
+       if ($runTime < 0) $runTime = '0';
 
        // Prepare output
        $content = array(
@@ -2288,7 +2307,7 @@ function getCurrentTheme () {
        $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
@@ -2299,7 +2318,7 @@ function getCurrentTheme () {
                $ret = getSession('mxchange_theme');
 
                // Is it valid?
-               if (getThemeId($ret) == 0) {
+               if (getThemeId($ret) == '0') {
                        // Fix it to default
                        $ret = 'default';
                } // END - if
@@ -2342,7 +2361,7 @@ function getThemeId ($name) {
        } // END - if
 
        // Default id
-       $id = 0;
+       $id = '0';
 
        // Is the cache entry there?
        if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
@@ -2371,23 +2390,23 @@ 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
                logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
@@ -2400,12 +2419,12 @@ function generateErrorCodeFromUserStatus ($status) {
 // Function to search for the last modifified file
 function searchDirsRecursive ($dir, &$last_changed) {
        // Get dir as array
-       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />");
+       //* 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: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
 
        // Walk through all entries
        foreach ($ds as $d) {
@@ -2418,7 +2437,7 @@ function searchDirsRecursive ($dir, &$last_changed) {
                        // $FQFN is a directory so also crawl into this directory
                        $newDir = $d;
                        if (!empty($dir)) $newDir = $dir . '/'. $d;
-                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
+                       //* 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
@@ -2519,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);
@@ -2597,6 +2616,17 @@ 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 = '';
 
@@ -2646,6 +2676,7 @@ function getMessageFromErrorCode ($code) {
                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;
@@ -2654,7 +2685,7 @@ function getMessageFromErrorCode ($code) {
                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('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;
@@ -2685,7 +2716,7 @@ function getMessageFromErrorCode ($code) {
 
                        // Load timestamp from last order
                        list($timestamp) = SQL_FETCHROW($result);
-                       $timestamp = generateDateTime($timestamp, '1');
+                       $timestamp = generateDateTime($timestamp, 1);
 
                        // Free memory
                        SQL_FREERESULT($result);
@@ -2719,36 +2750,6 @@ function getMessageFromErrorCode ($code) {
        return $message;
 }
 
-// Generate a "link" for the given admin id (admin_id)
-function generateAdminLink ($adminId) {
-       // No assigned admin is default
-       $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
-
-       // Zero? = Not assigned
-       if (bigintval($adminId) > 0) {
-               // Load admin's login
-               $login = getAdminLogin($adminId);
-
-               // Is the login valid?
-               if ($login != '***') {
-                       // Is the extension there?
-                       if (isExtensionActive('admins')) {
-                               // Admin found
-                               $admin = "<a href=\"".generateEmailLink(getAdminEmail($adminId), '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'), $adminId)."</div>";
-               }
-       } // END - if
-
-       // Return result
-       return $admin;
-}
-
 // Compile characters which are allowed in URLs
 function compileUriCode ($code, $simple = true) {
        // Compile constants
@@ -2774,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 = secureString(str_replace("\\", '', compileCode(urldecode($url))));
+       $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
 
        // Allows http and https
        $http      = "(http|https)+(:\/\/)";
@@ -2822,7 +2823,7 @@ function isUrlValidSimple ($url) {
                        // @TODO Are these convertions still required?
                        $pat = str_replace('.', "&#92;&#46;", $pat);
                        $pat = str_replace('@', "&#92;&#64;", $pat);
-                       //* DEBUG: */ outputHtml($key."=&nbsp;" . $pat . "<br />");
+                       //* DEBUG: */ outputHtml($key."=&nbsp;" . $pat . '<br />');
                } // END - if
 
                // Check if expression matches
@@ -2868,7 +2869,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
                                        // 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) {
@@ -2913,7 +2914,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
 }
 // Send notification to admin
 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
-       if (getExtensionVersion('admins') >= '0.4.1') {
+       if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
                // Send new way
                sendAdminsEmails($subject, $templateName, $content, $userid);
        } else {
@@ -2932,7 +2933,7 @@ function logDebugMessage ($funcFile, $line, $message, $force=true) {
 
                // Log this message away, we better don't call app_die() here to prevent an endless loop
                $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() . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
+               fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
                fclose($fp);
        } // END - if
 }
@@ -2973,6 +2974,7 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
 // Converts timestamp selections into a timestamp
 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
        // Init test variable
+       $skip  = false;
        $test2 = '';
 
        // Get last three chars
@@ -2985,21 +2987,20 @@ function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
                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
                        $postData[$test] = createTimestampFromSelections($test, $postData);
-                       $DATA[] = sprintf("%s='%s'", $test, $postData[$test]);
+                       $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($postData[$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
@@ -3040,7 +3041,7 @@ function handleLoginFailtures ($accessLevel) {
                        //* 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
@@ -3148,8 +3149,8 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
 
 // Determines referal id and sets it
 function determineReferalId () {
-       // Skip this in non-html-mode
-       if (getOutputMode() != '0') return false;
+       // 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 ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
@@ -3176,12 +3177,33 @@ function determineReferalId () {
                // 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;
+
+               // Set current userid here if no member
+               if (!isMember()) setCurrentUserId($GLOBALS['refid');
+
+               // 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
@@ -3216,29 +3238,38 @@ 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
@@ -3370,7 +3401,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
                // Exclude '.', '..' and entries in $excludeArray automatically
                if (in_array($baseFile, $excludeArray, true))  {
                        // Exclude them
-                       //* DEBUG: */ outputHtml('excluded=' . $baseFile . "<br />");
+                       //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
                        continue;
                } // END - if
 
@@ -3384,9 +3415,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: */ outputHtml('baseDir:' . $baseDir . "<br />");
-                       //* DEBUG: */ outputHtml('baseFile:' . $baseFile . "<br />");
-                       //* DEBUG: */ outputHtml('FQFN:' . $FQFN . "<br />");
+                       //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
+                       //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
+                       //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
 
                        // Exclude this one
                        continue;
@@ -3469,8 +3500,25 @@ function mapModuleToTable ($moduleName) {
 
 // Add SQL debug data to array for later output
 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
-       // Don't execute anything here if we don't need
-       if (getConfig('display_debug_sqls') != 'Y') return;
+       // 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(
@@ -3495,7 +3543,7 @@ function initCacheInstance () {
        $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'));
+               addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
        } // END - if
 }
 
@@ -3514,89 +3562,132 @@ function getMessageFromIndexedArray ($message, $pos, $array) {
        return $ret;
 }
 
-// Handles fatal errors
-function handleFatalErrors () {
-       // Do we have errors to handle and right output mode?
-       if ((getTotalFatalErrors() == 0) || (getOutputMode() != 0)) {
-               // Abort executing here
-               return false;
-       } // END - if
+// Print code with line numbers
+function linenumberCode ($code)    {
+       if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
+       $count_lines = count($codeE);
 
-       // Set content type
-       setContentType('text/html');
+       $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>|';
 
-       // Load config here
-       loadIncludeOnce('inc/load_config.php');
+               // Add code
+               $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
+       }
 
-       // Set unset variable
-       if (empty($check)) $check = '';
+       return '<div class="code">' . $r . '</div>';
+}
 
-       // Default is none
-       $content = '';
+// Convert ';' to ', ' for e.g. receiver list
+function convertReceivers ($old) {
+       return str_replace(';', ', ', $old);
+}
 
-       // Installation phase or regular mode?
-       if ((isInstallationPhase())) {
-               // While we are installing ouput other header than while it is installed... :-)
-               $OUT = '';
-               foreach (getFatalArray() as $key => $value) {
-                       // Prepare content for the template
-                       $content = array(
-                               'key'   => ($key + 1),
-                               'value' => $value
-                       );
+// 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 = '';
 
-                       // Load row template
-                       $OUT .= loadTemplate('install_fatal_row', true, $content);
-               }
+               // Title decoration enabled?
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
 
-               // Load main template
-               $content = loadTemplate('install_fatal_table', true, $OUT);
-       } elseif (isInstalled()) {
-               // Display all runtime fatal errors
-               $OUT = '';
-               foreach (getFatalArray() as $key => $value) {
-                       // Prepare content for the template
-                       $content = array(
-                               'key'   => ($key + 1),
-                               'value' => $value
-                       );
+               // Do we have some extra title?
+               if (isExtraTitleSet()) {
+                       // Then prepent it
+                       $TITLE .= getExtraTitle() . ' by ';
+               } // END - if
 
-                       // Load row template
-                       $OUT .= loadTemplate('runtime_fatal_row', true, $content);
-               }
+               // 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
 
-               // Load main template
-               $content = loadTemplate('runtime_fatal_table', true, $OUT);
+               // 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'));
        }
 
-       // Message to regular users (non-admin)
-       $CORR = getMessage('FATAL_REPORT_ERRORS');
+       // 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);
 
-       // PHP warnings fixed
-       if ($check == 'done') {
-               if (isAdmin()) $CORR = getMessage('FATAL_CORRECT_ERRORS');
+               // Is it there?
+               $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
        } // END - if
 
-       // Remember all in array
-       $content = array(
-               'rows' => $content,
-               'corr' => $CORR
-       );
+       // Return it
+       return $GLOBALS['template_cache'][$template];
+}
 
-       // Load footer
-       loadIncludeOnce('inc/header.php');
+// 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);
 
-       // Load main template
-       loadTemplate('fatal_errors', false, $content);
+               // Replace username with a call
+               $eval = str_replace('$username', '".getUsername()."', $eval);
 
-       // Delete all to prevent double-display
-       initFatalMessages();
+               // And flush it
+               writeToFile($FQFN, $eval, true);
+       } // END - if
+}
 
-       // Load footer
-       loadIncludeOnce('inc/footer.php');
+// 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);
 
-       // Abort here
-       shutdown();
+               // And read from it
+               $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
+       } // END - if
+
+       // And return it
+       return $GLOBALS['template_eval'][$template];
 }
 
 //////////////////////////////////////////////////
@@ -3612,5 +3703,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]
 ?>