More fixes for installation and extension registration
[mailer.git] / inc / functions.php
index 9e3240ea54feb9c9ae6009f5765e6b80727da1ef..eb36b77d60840cef80982cc30d907c83fb9cbdd9 100644 (file)
@@ -85,16 +85,7 @@ function outputHtml ($htmlCode, $newLine = true) {
                                app_die(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
                                break;
                } // END - switch
-       } elseif ((getPhpCaching() == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
-               // Headers already sent?
-               if (headers_sent()) {
-                       // Log this error
-                       logDebugMessage(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
-
-                       // Trigger an user error
-                       debug_report_bug('Headers are already sent!');
-               } // END - if
-
+       } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
                // Output cached HTML code
                $GLOBALS['output'] = ob_get_contents();
 
@@ -108,12 +99,12 @@ function outputHtml ($htmlCode, $newLine = true) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
-               // Compile and run finished rendered HTML code
-               compileFinalOutput();
-
                // Send all HTTP headers
                sendHttpHeaders();
 
+               // Compile and run finished rendered HTML code
+               compileFinalOutput();
+
                // Output code here, DO NOT REMOVE! ;-)
                outputRawCode($GLOBALS['output']);
        } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
@@ -122,14 +113,17 @@ function outputHtml ($htmlCode, $newLine = true) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
-               // Compile and run finished rendered HTML code
-               compileFinalOutput();
-
                // Send all HTTP headers
                sendHttpHeaders();
 
+               // Compile and run finished rendered HTML code
+               compileFinalOutput();
+
                // Output code here, DO NOT REMOVE! ;-)
                outputRawCode($GLOBALS['output']);
+       } else {
+               // And flush all headers
+               flushHeaders();
        }
 }
 
@@ -142,7 +136,7 @@ function sendHttpHeaders () {
        sendHeader('HTTP/1.1 200');
 
        // General headers for no caching
-       sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
+       sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
        sendHeader('Last-Modified: ' . $now);
        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
@@ -177,8 +171,26 @@ function compileFinalOutput () {
                $cnt++;
        } // END - while
 
+       // Compress it?
+       if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
+               // Compress it for HTTP gzip
+               $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
+
+               // Add header
+               sendHeader('Content-Encoding: gzip');
+       } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
+               // Compress it for HTTP deflate
+               $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
+
+               // Add header
+               sendHeader('Content-Encoding: deflate');
+       }
+
        // Add final length
        sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
+
+       // Flush all headers
+       flushHeaders();
 }
 
 // Output the raw HTML code
@@ -217,7 +229,6 @@ function addFatalMessage ($F, $L, $message, $extra = '') {
        $GLOBALS['fatal_messages'][] = $message;
 
        // Log fatal messages away
-       debug_report_bug($message);
        logDebugMessage($F, $L, 'Fatal error message: ' . $message);
 }
 
@@ -400,7 +411,7 @@ function detectExtraTemplatePath ($template) {
 }
 
 // Loads an email template and compiles it
-function loadEmailTemplate ($template, $content = array(), $UID = '0') {
+function loadEmailTemplate ($template, $content = array(), $userid = '0') {
        global $DATA;
 
        // Make sure all template names are lowercase!
@@ -409,53 +420,36 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        // Default 'nickname' if extension is not installed
        $nick = '---';
 
-       // Prepare IP number and User Agent
-       $REMOTE_ADDR     = detectRemoteAddr();
-       $HTTP_USER_AGENT = detectUserAgent();
-
-       // Default admin
-       $ADMIN = getConfig('MAIN_TITLE');
-
-       // 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)) {
-               // Add expiration to array, $EXPIRATION is now deprecated!
-               $content['expiration'] = $EXPIRATION;
+               // Add expiration to array
+               if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
+                       // Will never expire!
+                       $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
+               } elseif (isConfigEntrySet('auto_purge')) {
+                       // Create nice date string
+                       $content['expiration'] = createFancyTime(getConfig('auto_purge'));
+               } else {
+                       // Missing entry
+                       $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
+               }
        } // END - if
 
        // 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))) {
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$userid},template={$template},content[]=".gettype($content).'<br />');
+       if (($userid > 0) && (is_array($content))) {
                // If nickname extension is installed, fetch nickname as well
-               if ((isExtensionActive('nickname')) && (isNicknameUsed($UID))) {
+               if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
                        // Load by nickname
-                       fetchUserData($UID, 'nickname');
+                       fetchUserData($userid, 'nickname');
                } else {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
                        /// Load by userid
-                       fetchUserData($UID);
+                       fetchUserData($userid);
                }
 
                // Merge data if valid
@@ -473,7 +467,7 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        if (isset($content['email'])) $email = $content['email'];
 
        // Store email for some functions in global data array
-       // @TODO Do only use $contentn, not $DATA or raw variables
+       // @TODO Do only use $content, not $DATA or raw variables
        $DATA['email'] = $email;
 
        // Base directory
@@ -519,7 +513,7 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        // Is there some content?
        if (empty($newContent)) {
                // Compiling failed
-               $newContent = "Compiler error for template {$template}!\nUncompiled content:\n" . $GLOBALS['tpl_content'];
+               $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.";
@@ -594,10 +588,10 @@ function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '
        if (isDebugModeEnabled()) {
                // In debug mode we want to display the mail instead of sending it away so we can debug this part
                outputHtml('<pre>
-Headers : ' . str_replace('<', '&lt', str_replace('>', '&gt;', secureString(trim($mailHeader)))) . '
-To      : ' . $toEmail . '
-Subject : ' . $subject . '
-Message : ' . $message . '
+Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
+To      : ' . htmlentities(utf8_decode($toEmail)) . '
+Subject : ' . htmlentities(utf8_decode($subject)) . '
+Message : ' . htmlentities(utf8_decode($message)) . '
 </pre>');
        } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
                // Send mail as HTML away
@@ -758,7 +752,7 @@ function translateYesNo ($yn) {
 // Translates the "pool type" into human-readable
 function translatePoolType ($type) {
        // Default?type is unknown
-       $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
+       $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
 
        // Generate constant
        $constName = sprintf("POOL_TYPE_%s", $type);
@@ -849,7 +843,7 @@ function translateUserStatus ($status) {
 
                default:
                        logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
-                       $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
+                       $ret = getMaskedMessage('UNKNOWN_STATUS', $status);
                        break;
        } // END - switch
 
@@ -938,28 +932,19 @@ function redirectToUrl ($URL) {
                $rel = '';
        } // END - if
 
-       // Get output buffer
-       $GLOBALS['output'] = ob_get_contents();
-
-       // Clear it only if there is content
-       if (!empty($GLOBALS['output'])) {
-               clearOutputBuffer();
-       } // END - if
-
        // Three different ways to debug...
        //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
        //* DEBUG: */ die($URL);
 
        // Simple probe for bots/spiders from search engines
-       if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
+       if (isSpider()) {
                // Secure the URL against bad things such als HTML insertions and so on...
                $URL = secureString($URL);
 
                // Output new location link as anchor
                outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
        } elseif (!headers_sent()) {
-               //* DEBUG: */ debug_report_bug("URL={$URL}");
                // Clear own output buffer
                $GLOBALS['output'] = '';
 
@@ -1399,6 +1384,16 @@ function generateImageOrCode ($img_code, $headerSent = true) {
 }
 // Create selection box or array of splitted timestamp
 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
+       // Do not continue if ONE_DAY is absend
+       if (!isConfigEntrySet('ONE_DAY')) {
+               // And return the timestamp itself or empty array
+               if ($return_array === true) {
+                       return array();
+               } else {
+                       return $timestamp;
+               }
+       } // END - if
+
        // Calculate 2-seconds timestamp
        $stamp = round($timestamp);
        //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
@@ -1493,7 +1488,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";
+                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ye\" size=\"1\">\n";
                        for ($idx = '0'; $idx <= 10; $idx++) {
                                $OUT .= "    <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $Y) $OUT .= ' selected="selected"';
@@ -1501,12 +1496,12 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        }
                        $OUT .= "  </select></td>\n";
                } else {
-                       $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
+                       $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
                }
 
                if (ereg('M', $display) || (empty($display))) {
                        // Generate month selection
-                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
+                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mo\" size=\"1\">\n";
                        for ($idx = '0'; $idx <= 11; $idx++)
                        {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
@@ -1515,12 +1510,12 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        }
                        $OUT .= "  </select></td>\n";
                } else {
-                       $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_mo\" value=\"0\" />\n";
+                       $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
                }
 
                if (ereg('W', $display) || (empty($display))) {
                        // Generate week selection
-                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_we\" size=\"1\">\n";
+                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_we\" size=\"1\">\n";
                        for ($idx = '0'; $idx <= 4; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $W) $OUT .= ' selected="selected"';
@@ -1528,12 +1523,12 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        }
                        $OUT .= "  </select></td>\n";
                } else {
-                       $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_we\" value=\"0\" />\n";
+                       $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
                }
 
                if (ereg('D', $display) || (empty($display))) {
                        // Generate day selection
-                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_da\" size=\"1\">\n";
+                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_da\" size=\"1\">\n";
                        for ($idx = '0'; $idx <= 31; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $D) $OUT .= ' selected="selected"';
@@ -1541,12 +1536,12 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        }
                        $OUT .= "  </select></td>\n";
                } else {
-                       $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_da\" value=\"0\" />\n";
+                       $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
                }
 
                if (ereg('h', $display) || (empty($display))) {
                        // Generate hour selection
-                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_ho\" size=\"1\">\n";
+                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_ho\" size=\"1\">\n";
                        for ($idx = '0'; $idx <= 23; $idx++)    {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $h) $OUT .= ' selected="selected"';
@@ -1554,12 +1549,12 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        }
                        $OUT .= "  </select></td>\n";
                } else {
-                       $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_ho\" value=\"0\" />\n";
+                       $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
                }
 
                if (ereg('m', $display) || (empty($display))) {
                        // Generate minute selection
-                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mi\" size=\"1\">\n";
+                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_mi\" size=\"1\">\n";
                        for ($idx = '0'; $idx <= 59; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $m) $OUT .= ' selected="selected"';
@@ -1567,12 +1562,12 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        }
                        $OUT .= "  </select></td>\n";
                } else {
-                       $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_mi\" value=\"0\" />\n";
+                       $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
                }
 
                if (ereg('s', $display) || (empty($display))) {
                        // Generate second selection
-                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_se\" size=\"1\">\n";
+                       $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix . "_se\" size=\"1\">\n";
                        for ($idx = '0'; $idx <= 59; $idx++) {
                                $OUT .= "  <option class=\"mini_select\" value=\"" . $idx."\"";
                                if ($idx == $s) $OUT .= ' selected="selected"';
@@ -1580,7 +1575,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        }
                        $OUT .= "  </select></td>\n";
                } else {
-                       $OUT .= "<input type=\"hidden\" name=\"" . $prefix."_se\" value=\"0\" />\n";
+                       $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
                }
                $OUT .= "</tr>\n";
                $OUT .= "</table>\n";
@@ -1600,21 +1595,21 @@ function createTimestampFromSelections ($prefix, $postData) {
        $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") && ($postData[$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 += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
+       $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
        // Next months...
-       $ret += $postData[$prefix."_mo"] * 2628000;
+       $ret += $postData[$prefix . '_mo'] * 2628000;
        // Next weeks
-       $ret += $postData[$prefix."_we"] * 604800;
+       $ret += $postData[$prefix . '_we'] * 604800;
        // Next days...
-       $ret += $postData[$prefix."_da"] * 86400;
+       $ret += $postData[$prefix . '_da'] * 86400;
        // Next hours...
-       $ret += $postData[$prefix."_ho"] * 3600;
+       $ret += $postData[$prefix . '_ho'] * 3600;
        // Next minutes..
-       $ret += $postData[$prefix."_mi"] * 60;
+       $ret += $postData[$prefix . '_mi'] * 60;
        // And at last seconds...
-       $ret += $postData[$prefix."_se"];
+       $ret += $postData[$prefix . '_se'];
        // Return calculated value
        return $ret;
 }
@@ -1741,19 +1736,19 @@ function sendGetRequest ($script, $data = array()) {
        $host = extractHostnameFromUrl($script);
 
        // Add data
-       $scriptData = http_build_query($data, '', '&');
+       $body = 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;
+               $body = '?' . $body;
        } else {
                // Ok, add &
-               $scriptData = '&' . $scriptData;
+               $body = '&' . $body;
        }
 
        // Add script data
-       $script .= $scriptData;
+       $script .= $body;
 
        // Generate GET request header
        $request  = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
@@ -1764,8 +1759,11 @@ function sendGetRequest ($script, $data = array()) {
        } else {
                $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
        }
-       $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
+       $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
+       $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
        $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
+       $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
+       $request .= 'Content-Length: '.strlen($body) . getConfig('HTTP_EOL');
        $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
 
        // Send the raw request
@@ -1788,18 +1786,17 @@ function sendPostRequest ($script, $postData) {
        $host = extractHostnameFromUrl($script);
 
        // Construct request
-       $data = http_build_query($postData, '', '&');
+       $body = 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: ' . 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 .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
        $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
-       $request .= $data;
+       $request .= $body;
 
        // Send the raw request
        $response = sendRawRequest($host, $request);
@@ -1844,19 +1841,19 @@ function sendRawRequest ($host, $request) {
        // Do we use proxy?
        if ($useProxy === true) {
                // Generate CONNECT request header
-               $proxyTunnel  = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
-               $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
+               $proxyTunnel  = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
+               $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
 
                // Use login data to proxy? (username at least!)
                if (getConfig('proxy_username') != '') {
                        // Add it as well
                        $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
-                       $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
+                       $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
                } // END - if
 
                // Add last new-line
                $proxyTunnel .= getConfig('HTTP_EOL');
-               //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>" . $proxyTunnel."</pre>");
+               //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
 
                // Write request
                fputs($fp, $proxyTunnel);
@@ -1903,7 +1900,7 @@ function sendRawRequest ($host, $request) {
                }
        } // END - foreach
 
-       //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
+       //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
 
        // Proxy agent found?
        if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
@@ -1967,11 +1964,11 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
        $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
 
        // Begin of navigation links
-       $OUT = "[&nbsp;";
+       $OUT = '[&nbsp;';
 
        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 />");
+               $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
                        $OUT .= 'UNLOCK_USER';
@@ -1979,7 +1976,7 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
                        // All other status is fine
                        $OUT .= strtoupper($tar);
                }
-               $OUT .= "_TITLE--}\">{--ADMIN_";
+               $OUT .= '_TITLE--}">{--ADMIN_';
                if (($tar == 'lock_user') && ($status == 'LOCKED')) {
                        // Locked accounts shall be unlocked
                        $OUT .= 'UNLOCK_USER';
@@ -1987,7 +1984,7 @@ function generateMemberAdminActionLinks ($userid, $status = '') {
                        // All other status is fine
                        $OUT .= strtoupper($tar);
                }
-               $OUT .= "--}</a></span>&nbsp;|&nbsp;";
+               $OUT .= '--}</a></span>&nbsp;|&nbsp;';
        }
 
        // Finish navigation link
@@ -2051,15 +2048,15 @@ function generateHash ($plainText, $salt = '') {
 
                // 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: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")<br />");
+               //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
                $sha1 = scrambleString($sha1);
-               //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
+               //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
                //* DEBUG: */ $sha1b = descrambleString($sha1);
-               //* DEBUG: */ outputHtml("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: */ outputHtml($salt." (".strlen($salt).")<br />");
+               //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
        } else {
                // Use given salt
                //* DEBUG: */ print 'salt=' . $salt . '<br />';
@@ -2094,8 +2091,11 @@ function scrambleString($str) {
                $scrambleNums = explode(':', genScrambleString(strlen($str)));
        }
 
+       // Compare both lengths and abort if different
+       if (strlen($str) != count($scrambleNums)) return $str;
+
        // Scramble string here
-       //* DEBUG: */ outputHtml("***Original=" . $str."***<br />");
+       //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
        for ($idx = '0'; $idx < strlen($str); $idx++) {
                // Get char on scrambled position
                $char = substr($str, $scrambleNums[$idx], 1);
@@ -2105,7 +2105,7 @@ function scrambleString($str) {
        } // END - for
 
        // Return scrambled string
-       //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***<br />");
+       //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
        return $scrambled;
 }
 
@@ -2122,14 +2122,14 @@ function descrambleString($str) {
 
        // Begin descrambling
        $orig = str_repeat(' ', 40);
-       //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++<br />");
+       //* 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: */ outputHtml("+++Original=" . $orig."+++<br />");
+       //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
        return $orig;
 }
 
@@ -2225,10 +2225,10 @@ function app_die ($F, $L, $message) {
                $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
 
                // Better log this message away
-               logDebugMessage($F, $L, $message);
+               if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
 
                // Load the message template
-               loadTemplate('admin_settings_saved', false, $message);
+               loadTemplate('app_die_message', false, $message);
 
                // Load footer
                loadIncludeOnce('inc/footer.php');
@@ -2327,7 +2327,7 @@ function generateErrorCodeFromUserStatus ($status='') {
        $errorCode = getCode('UNKNOWN_STATUS');
 
        // Generate constant name
-       $codeName = sprintf("ID_%s", $status);
+       $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
 
        // Is the constant there?
        if (isCodeSet($codeName)) {
@@ -2592,12 +2592,11 @@ function debug_report_bug ($message = '', $sendEmail = true) {
        $debug .= "Thank you for finding bugs.";
 
        // Send an email? (e.g. not wanted for evaluation errors)
-       if ($sendEmail === true) {
+       if (($sendEmail === true) && (!isInstallationPhase())) {
                // Prepare content
                $content = array(
                        'message'     => trim($message),
-                       'backtrace'   => trim(debug_get_mailable_backtrace()),
-                       'request_uri' => trim(getRequestUri())
+                       'backtrace'   => trim(debug_get_mailable_backtrace())
                );
 
                // Send email to webmaster
@@ -2605,8 +2604,7 @@ function debug_report_bug ($message = '', $sendEmail = true) {
        } // END - if
 
        // And abort here
-       // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
-       die($debug);
+       app_die(__FUNCTION__, __LINE__, $debug);
 }
 
 // Generates a ***weak*** seed
@@ -2619,40 +2617,40 @@ 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_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('COOKIES_DISABLED') : $message = getMessage('LOGIN_COOKIES_DISABLED'); 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('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('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('ACCOUNT_LOCKED')     : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
+               case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
+               case getCode('COOKIES_DISABLED')   : $message = getMessage('LOGIN_COOKIES_DISABLED'); 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 = getMaskedMessage('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 = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
+               case getCode('INVALID_URL')        : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
+               case getCode('UNKNOWN_ERROR')      : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
+               case getCode('UNKNOWN_STATUS')     : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
 
                case getCode('ERROR_MAILID'):
                        if (isExtensionActive('mailid', true)) {
                                $message = getMessage('ERROR_CONFIRMING_MAIL');
                        } else {
-                               $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
+                               $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
                        }
                        break;
 
@@ -2665,16 +2663,19 @@ function getMessageFromErrorCode ($code) {
                        break;
 
                case getCode('URL_TLOCK'):
+                       // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
                        $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);
 
+                       // Translate it for templates
+                       $timestamp = generateDateTime($timestamp, 1);
+
                        // Calculate hours...
                        $STD = round(getConfig('url_tlock') / 60 / 60);
 
@@ -2693,7 +2694,7 @@ function getMessageFromErrorCode ($code) {
 
                default:
                        // Missing/invalid code
-                       $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
+                       $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
 
                        // Log it
                        logDebugMessage(__FUNCTION__, __LINE__, $message);
@@ -2868,7 +2869,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
 }
 // Send notification to admin
 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
-       if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
+       if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
                // Send new way
                sendAdminsEmails($subject, $templateName, $content, $userid);
        } else {
@@ -3073,15 +3074,15 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
        if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
 
        // Generate receiver list
-       $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
+       $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
 
        // Receivers added?
-       if (!empty($RECEIVER)) {
+       if (!empty($receiver)) {
                // Add bonus mail to queue
                addBonusMailToQueue(
                $data['subject'],
                $data['text'],
-               $RECEIVER,
+               $receiver,
                $data['points'],
                $data['seconds'],
                $data['url'],
@@ -3177,7 +3178,8 @@ function shutdown () {
        // Call the filter chain 'shutdown'
        runFilterChain('shutdown', null);
 
-       if (SQL_IS_LINK_UP()) {
+       // Check if not in installation phase and the link is up
+       if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
                // Close link
                SQL_CLOSE(__FILE__, __LINE__);
        } elseif (!isInstallationPhase()) {
@@ -3271,12 +3273,12 @@ function generateExtensionInactiveMessage ($ext_name) {
        } // END - if
 
        // Default message
-       $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
+       $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
 
        // Is an admin logged in?
        if (isAdmin()) {
                // Then output admin message
-               $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
+               $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
        } // END - if
 
        // Return prepared message
@@ -3292,12 +3294,12 @@ function generateExtensionNotInstalledMessage ($ext_name) {
        } // END - if
 
        // Default message
-       $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
+       $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
 
        // Is an admin logged in?
        if (isAdmin()) {
                // Then output admin message
-               $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
+               $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED', $ext_name);
        } // END - if
 
        // Return prepared message
@@ -3552,7 +3554,7 @@ function determinePageTitle () {
                $TITLE = '';
 
                // Title decoration enabled?
-               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
 
                // Do we have some extra title?
                if (isExtraTitleSet()) {
@@ -3584,7 +3586,7 @@ function determinePageTitle () {
                $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
        } elseif ((isInstalled()) && (!isAdminRegistered())) {
                // Installed but no admin registered
-               $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
+               $pageTitle = getMessage('SETUP_OF_MXCHANGE');
        } elseif ((!isInstalled()) || (!isAdminRegistered())) {
                // Installation mode
                $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
@@ -3837,7 +3839,7 @@ function encodeUrl ($url, $outputMode = '0') {
        if (strpos($url, session_name()) !== false) return $url;
 
        // Do we have a valid session?
-       if ((($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
+       if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
                // Invalid session
                // Determine right seperator
                $seperator = '&amp;';
@@ -3856,7 +3858,7 @@ function encodeUrl ($url, $outputMode = '0') {
        } // END - if
 
        // Add {?URL?} ?
-       if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}')) {
+       if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
                // Add it
                $url = '{?URL?}/' . $url;
        } // END - if
@@ -3867,8 +3869,14 @@ function encodeUrl ($url, $outputMode = '0') {
 
 // Simple check for spider
 function isSpider () {
+       // Get the UA
+       $userAgent = strtolower(detectUserAgent(true));
+
+       // It should not be empty, if so it is better a spider/bot
+       if (empty($userAgent)) return true;
+
        // Is it a spider?
-       return ((strpos('spider', strtolower(detectUserAgent(true))) !== false) || (strpos('bot', strtolower(detectUserAgent(true))) !== false));
+       return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false));
 }
 
 //////////////////////////////////////////////////