]> git.mxchange.org Git - mailer.git/blobdiff - inc/functions.php
Old config.php is now automatically updated to new config-local.php format, several...
[mailer.git] / inc / functions.php
index 49ecee6906b7c82217b5860fd49e96f0b1144cc5..2276a0f42b35d7aec9db2ec014aa7ab8926f6c53 100644 (file)
@@ -41,7 +41,7 @@ if (!defined('__SECURITY')) {
        require($INC);
 }
 
-// Output HTML code directly or "render" it. You addionally switch the new-line character off
+// Output HTML code directly or 'render' it. You addionally switch the new-line character off
 function OUTPUT_HTML ($HTML, $newLine = true) {
        // Some global variables
        global $OUTPUT;
@@ -49,41 +49,40 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
        // Do we have HTML-Code here?
        if (!empty($HTML)) {
                // Yes, so we handle it as you have configured
-               switch (constant('OUTPUT_MODE'))
+               switch (getConfig('OUTPUT_MODE'))
                {
-               case "render":
-                       // That's why you don't need any \n at the end of your HTML code... :-)
-                       if (constant('_OB_CACHING') == "on") {
-                               // Output into PHP's internal buffer
-                               outputRawCode($HTML);
-
+                       case 'render':
                                // That's why you don't need any \n at the end of your HTML code... :-)
-                               if ($newLine) echo "\n";
-                       } else {
-                               // Render mode for old or lame servers...
-                               $OUTPUT .= $HTML;
+                               if (constant('_OB_CACHING') == 'on') {
+                                       // Output into PHP's internal buffer
+                                       outputRawCode($HTML);
 
-                               // That's why you don't need any \n at the end of your HTML code... :-)
-                               if ($newLine) $OUTPUT .= "\n";
-                       }
-                       break;
+                                       // That's why you don't need any \n at the end of your HTML code... :-)
+                                       if ($newLine) echo "\n";
+                               } else {
+                                       // Render mode for old or lame servers...
+                                       $OUTPUT .= $HTML;
 
-               case 'direct':
-                       // If we are switching from render to direct output rendered code
-                       if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { outputRawCode($OUTPUT); $OUTPUT = ''; }
+                                       // That's why you don't need any \n at the end of your HTML code... :-)
+                                       if ($newLine) $OUTPUT .= "\n";
+                               }
+                               break;
 
-                       // The same as above... ^
-                       outputRawCode($HTML);
-                       if ($newLine) echo "\n";
-                       break;
+                       case 'direct':
+                               // If we are switching from render to direct output rendered code
+                               if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != 'on')) { outputRawCode($OUTPUT); $OUTPUT = ''; }
 
-               default:
-                       // Huh, something goes wrong or maybe you have edited config.php ???
-                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
-                       app_die(__FUNCTION__, __LINE__, "<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
-                       break;
+                               // The same as above... ^
+                               outputRawCode($HTML);
+                               if ($newLine) echo "\n";
+                               break;
+
+                       default:
+                               // Huh, something goes wrong or maybe you have edited config.php ???
+                               app_die(__FUNCTION__, __LINE__, "<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
+                               break;
                }
-       } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
+       } elseif ((constant('_OB_CACHING') == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
                // Headers already sent?
                if (headers_sent()) {
                        // Log this error
@@ -102,20 +101,20 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
                } // END - if
 
                // Send HTTP header
-               header("HTTP/1.1 200");
+               sendHeader('HTTP/1.1 200');
 
                // Used later
                $now = gmdate('D, d M Y H:i:s') . ' GMT';
 
                // General headers for no caching
-               header("Expired: " . $now); // RFC2616 - Section 14.21
-               header("Last-Modified: " . $now);
-               header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
-               header("Pragma: no-cache"); // HTTP/1.0
-               header("Connection: Close");
+               sendHeader('Expired: ' . $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
+               sendHeader('Connection: Close');
 
                // Extension 'rewrite' installed?
-               if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
+               if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != '1') && ($GLOBALS['output_mode'] != '-1')) {
                        $OUTPUT = rewriteLinksInCode($OUTPUT);
                } // END - if
 
@@ -136,9 +135,9 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
 
                // Output code here, DO NOT REMOVE! ;-)
                outputRawCode($OUTPUT);
-       } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
+       } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
                // Rewrite links when rewrite extension is active
-               if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
+               if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != '1') && ($GLOBALS['output_mode'] != '-1')) {
                        $OUTPUT = rewriteLinksInCode($OUTPUT);
                } // END - if
 
@@ -158,8 +157,8 @@ function outputRawCode ($HTML) {
        // Output stripped HTML code to avoid broken JavaScript code, etc.
        echo stripslashes(stripslashes($HTML));
 
-       // Flush the output if only constant('_OB_CACHING') is not "on"
-       if (constant('_OB_CACHING') != "on") {
+       // Flush the output if only constant('_OB_CACHING') is not 'on'
+       if (constant('_OB_CACHING') != 'on') {
                // Flush it
                flush();
        } // END - if
@@ -234,7 +233,7 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
        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__);
+               array(getUserId()), __FUNCTION__, __LINE__);
 
                // Is content an array?
                if (is_array($content)) {
@@ -259,7 +258,7 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
        } // END - if
 
        // Generate date/time string
-       $date_time = generateDateTime(time(), "1");
+       $date_time = generateDateTime(time(), '1');
 
        // Base directory
        $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
@@ -301,10 +300,10 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
        if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($mode == "guest/") || ($mode == "member/") || ($mode == "admin/"))) {
                // Select what depended header/footer template file for admin/guest/member area
                $file2 = sprintf("%s%s%s_%s.tpl",
-                       $basePath,
-                       $mode,
-                       $template,
-                       SQL_ESCAPE($GLOBALS['what'])
+               $basePath,
+               $mode,
+               $template,
+               SQL_ESCAPE($GLOBALS['what'])
                );
 
                // Probe for it...
@@ -343,12 +342,12 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
                $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
        } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
                // Only admins shall see this warning or when installation mode is active
-               $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
+               $ret = "<br /><span class=\"guest_failed\">{--TEMPLATE_404--}</span><br />
 (".basename($FQFN).")<br />
 <br />
-".TEMPLATE_CONTENT."
+{--TEMPLATE_CONTENT--}
 <pre>".print_r($content, true)."</pre>
-".TEMPLATE_DATA."
+{--TEMPLATE_DATA--}
 <pre>".print_r($DATA, true)."</pre>
 <br /><br />";
        }
@@ -411,7 +410,7 @@ function sendEmail($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '')
        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
 
        // Check for PHPMailer or debug-mode
-       if (!CHECK_PHPMAILER_USAGE()) {
+       if (!checkPhpMailerUsage()) {
                // Not in PHPMailer-Mode
                if (empty($mailHeader)) {
                        // Load email header template
@@ -450,32 +449,30 @@ Message : ".$message."
 </pre>\n");
        } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
                // Send mail as HTML away
-               SEND_HTML_EMAIL($toEmail, $subject, $message, $mailHeader);
+               sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
        } elseif (!empty($toEmail)) {
                // Send Mail away
-               SEND_RAW_EMAIL($toEmail, $subject, $message, $mailHeader);
+               sendRawEmail($toEmail, $subject, $message, $mailHeader);
        } elseif ($HTML == 'N') {
                // Problem found!
-               SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$subject, $message, $mailHeader);
+               sendRawEmail(constant('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
        }
 }
 
 // Check if legacy or PHPMailer command
 // @TODO Rewrite this to an extension 'smtp'
 // @private
-function CHECK_PHPMAILER_USAGE() {
-       return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != '') && (constant('SMTP_USER') != ''));
+function checkPhpMailerUsage() {
+       return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
 }
 
-/*
- * Send out a raw email with PHPMailer class or legacy mail() command
- */
-function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
+// Send out a raw email with PHPMailer class or legacy mail() command
+function sendRawEmail ($toEmail, $subject, $msg, $from) {
        // Shall we use PHPMailer class or legacy mode?
-       if (CHECK_PHPMAILER_USAGE()) {
+       if (checkPhpMailerUsage()) {
                // Use PHPMailer class with SMTP enabled
-               loadIncludeOnce("inc/phpmailer/class.phpmailer.php");
-               loadIncludeOnce("inc/phpmailer/class.smtp.php");
+               loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
+               loadIncludeOnce('inc/phpmailer/class.smtp.php');
 
                // get new instance
                $mail = new PHPMailer();
@@ -483,10 +480,10 @@ function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
 
                $mail->IsSMTP();
                $mail->SMTPAuth   = true;
-               $mail->Host       = constant('SMTP_HOSTNAME');
+               $mail->Host       = getConfig('SMTP_HOSTNAME');
                $mail->Port       = 25;
-               $mail->Username   = constant('SMTP_USER');
-               $mail->Password   = constant('SMTP_PASSWORD');
+               $mail->Username   = getConfig('SMTP_USER');
+               $mail->Password   = getConfig('SMTP_PASSWORD');
                if (empty($from)) {
                        $mail->From = constant('WEBMASTER');
                } else {
@@ -496,7 +493,7 @@ function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
                $mail->Subject    = $subject;
                if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($msg) != $msg)) {
                        $mail->Body       = $msg;
-                       $mail->AltBody    = "Your mail program required HTML support to read this mail!";
+                       $mail->AltBody    = 'Your mail program required HTML support to read this mail!';
                        $mail->WordWrap   = 70;
                        $mail->IsHTML(true);
                } else {
@@ -504,8 +501,8 @@ function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
                }
                $mail->AddAddress($toEmail, '');
                $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
-               $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
-               $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
+               $mail->AddCustomHeader('Errors-To:' . constant('WEBMASTER'));
+               $mail->AddCustomHeader('X-Loop:' . constant('WEBMASTER'));
                $mail->Send();
        } else {
                // Use legacy mail() command
@@ -551,28 +548,28 @@ 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;
-                       default:
-                               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
-                               break;
-               }
-               break;
-
-       default: // Default is the US date / time format!
-               switch ($mode) {
-                       case '0': $ret = date("r", $time); break;
-                       case '1': $ret = date("Y-m-d - g:i A", $time); break;
-                       case '2': $ret = date("y-m-d|H:i", $time); break;
-                       case '3': $ret = date("y-m-d", $time); break;
-                       default:
-                               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
-                               break;
-               }
+               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;
+                               default:
+                                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
+                                       break;
+                       }
+                       break;
+
+                               default: // Default is the US date / time format!
+                                       switch ($mode) {
+                                               case '0': $ret = date("r", $time); break;
+                                               case '1': $ret = date("Y-m-d - g:i A", $time); break;
+                                               case '2': $ret = date("y-m-d|H:i", $time); break;
+                                               case '3': $ret = date("y-m-d", $time); break;
+                                               default:
+                                                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
+                                                       break;
+                                       }
        }
        return $ret;
 }
@@ -580,7 +577,7 @@ function generateDateTime ($time, $mode = '0') {
 // Translates Y/N to yes/no
 function translateYesNo ($yn) {
        // Default
-       $translated = "??? (".$yn.")";
+       $translated = "??? (".$yn.')';
        switch ($yn) {
                case 'Y': $translated = getMessage('YES'); break;
                case 'N': $translated = getMessage('NO'); break;
@@ -638,13 +635,13 @@ function translateComma ($dotted, $cut = true, $max = 0) {
 
        // Translate it now
        switch (getLanguage()) {
-       case 'de':
-               $dotted = number_format($dotted, $maxComma, ',', '.');
-               break;
+               case 'de':
+                       $dotted = number_format($dotted, $maxComma, ',', '.');
+                       break;
 
-       default:
-               $dotted = number_format($dotted, $maxComma, '.', ',');
-               break;
+               default:
+                       $dotted = number_format($dotted, $maxComma, '.', ',');
+                       break;
        }
 
        // Return translated value
@@ -675,21 +672,21 @@ function translateGender ($gender) {
 function translateUserStatus ($status) {
        switch ($status)
        {
-       case 'UNCONFIRMED':
-       case 'CONFIRMED':
-       case 'LOCKED':
-               $ret = getMessage(sprintf("ACCOUNT_%s", $status));
-               break;
-
-       case '':
-       case null:
-               $ret = getMessage('ACCOUNT_DELETED');
-               break;
-
-       default:
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
-               $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
-               break;
+               case 'UNCONFIRMED':
+               case 'CONFIRMED':
+               case 'LOCKED':
+                       $ret = getMessage(sprintf("ACCOUNT_%s", $status));
+                       break;
+
+               case '':
+               case null:
+                       $ret = getMessage('ACCOUNT_DELETED');
+                       break;
+
+               default:
+                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
+                       $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
+                       break;
        }
 
        // Return it
@@ -712,7 +709,7 @@ function DEREFERER ($URL) {
 function FRAMETESTER ($URL) {
        // Prepare frametester URL
        $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&amp;url=%s",
-               encodeString(compileUriCode($URL))
+       encodeString(compileUriCode($URL))
        );
        return $frametesterUrl;
 }
@@ -728,61 +725,11 @@ function countSelection ($array) {
        return $ret;
 }
 
-// Wrapper for $_POST['sel']
-function countPostSelection () {
-       return countSelection(REQUEST_POST('sel'));
-}
-
 // Generate XHTML code for the CAPTCHA
 function generateCaptchaCode ($code, $type, $DATA, $uid) {
        return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '" />';
 }
 
-// "Getter" for language
-function getLanguage () {
-       // Set default return value to default language from config
-       $ret = constant('DEFAULT_LANG');
-
-       // Init variable
-       $lang = '';
-
-       // Is the variable set
-       if (REQUEST_ISSET_GET(('mx_lang'))) {
-               // Accept only first 2 chars
-               $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
-       } elseif (isset($GLOBALS['cache_array']['language'])) {
-               // Use cached
-               $ret = $GLOBALS['cache_array']['language'];
-       } elseif (!empty($lang)) {
-               // Check if main language file does exist
-               if (isFileReadable(constant('PATH').'inc/language/'.$lang.'.php')) {
-                       // Okay found, so let's update cookies
-                       setLanguage($lang);
-               }
-       } elseif (!isSessionVariableSet('mx_lang')) {
-               // Return stored value from cookie
-               $ret = getSession('mx_lang');
-
-               // Fixes a warning before the session has the mx_lang constant
-               if (empty($ret)) $ret = constant('DEFAULT_LANG');
-       }
-
-       // Cache entry
-       $GLOBALS['cache_array']['language'] = $ret;
-
-       // Return value
-       return $ret;
-}
-
-// "Setter" for language
-function setLanguage ($lang) {
-       // Accept only first 2 chars!
-       $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
-
-       // Set cookie
-       setSession('mx_lang', $lang);
-}
-
 // Loads an email template and compiles it
 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
        global $DATA, $_CONFIG;
@@ -836,12 +783,12 @@ function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
                        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
                        // Load nickname
                        $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
-                               array(bigintval($UID)), __FUNCTION__, __LINE__);
+                       array(bigintval($UID)), __FUNCTION__, __LINE__);
                } else {
                        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
                        /// Load normal data
                        $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
-                               array(bigintval($UID)), __FUNCTION__, __LINE__);
+                       array(bigintval($UID)), __FUNCTION__, __LINE__);
                }
 
                // Fetch and merge data
@@ -935,7 +882,7 @@ function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
        return COMPILE_CODE($newContent);
 }
 
-// Generates a timestamp (wrapper for mktime())
+// Generates a timestamp (some wrapper for mktime())
 function makeTime ($H, $M, $S, $stamp) {
        // Extract day, month and year from given timestamp
        $day   = date('d', $stamp);
@@ -947,7 +894,7 @@ function makeTime ($H, $M, $S, $stamp) {
 }
 
 // Redirects to an URL and if neccessarry extends it with own base URL
-function redirectToUrl ($URL, $addUrlData=true) {
+function redirectToUrl ($URL) {
        // Compile out URI codes
        $URL = compileUriCode($URL);
 
@@ -958,7 +905,7 @@ function redirectToUrl ($URL, $addUrlData=true) {
        } // END - if
 
        // Three different debug ways...
-       //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
+       /* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
        //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
        //* DEBUG: */ die($URL);
 
@@ -979,9 +926,6 @@ function redirectToUrl ($URL, $addUrlData=true) {
                clearOutputBuffer();
        } // END - if
 
-       // Add some data to URL if cookies are not accepted
-       if ((!isBooleanConstantAndTrue('__COOKIES')) && ($addUrlData === true)) $URL = addUrlData($URL);
-
        // Secure the URL against bad things such als HTML insertions and so on...
        $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
 
@@ -992,7 +936,7 @@ function redirectToUrl ($URL, $addUrlData=true) {
        } elseif (!headers_sent()) {
                // Load URL when headers are not sent
                //* DEBUG: */ debug_report_bug("URL={$URL}");
-               header ('Location: '.str_replace('&amp;', '&', $URL));
+               sendHeader('Location: '.str_replace('&amp;', '&', $URL));
        } else {
                // Output error message
                loadInclude('inc/header.php');
@@ -1005,7 +949,7 @@ function redirectToUrl ($URL, $addUrlData=true) {
 }
 
 // Wrapper for redirectToUrl but URL comes from a configuration entry
-function LOAD_CONFIGURED_URL ($configEntry) {
+function redirectToConfiguredUrl ($configEntry) {
        // Get the URL
        $URL = getConfig($configEntry);
 
@@ -1171,98 +1115,98 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
        }
 
        switch ($type) {
-       case "day": // Day
-               for ($idx = 1; $idx < 32; $idx++) {
-                       $OUT .= "<option value=\"".$idx."\"";
-                       if ($default == $idx) $OUT .= ' selected="selected"';
-                       $OUT .= ">".$idx."</option>\n";
-               } // END - for
-               break;
+               case "day": // Day
+                       for ($idx = 1; $idx < 32; $idx++) {
+                               $OUT .= "<option value=\"".$idx."\"";
+                               if ($default == $idx) $OUT .= ' selected="selected"';
+                               $OUT .= ">".$idx."</option>\n";
+                       } // END - for
+                       break;
 
-       case "month": // Month
-               foreach ($GLOBALS['month_descr'] as $month => $descr) {
-                       $OUT .= "<option value=\"".$month."\"";
-                       if ($default == $month) $OUT .= ' selected="selected"';
-                       $OUT .= ">".$descr."</option>\n";
-               } // END - for
-               break;
+               case "month": // Month
+                       foreach ($GLOBALS['month_descr'] as $month => $descr) {
+                               $OUT .= "<option value=\"".$month."\"";
+                               if ($default == $month) $OUT .= ' selected="selected"';
+                               $OUT .= ">".$descr."</option>\n";
+                       } // END - for
+                       break;
 
-       case "year": // Year
-               // Get current year
-               $year = date('Y', time());
+               case "year": // Year
+                       // Get current year
+                       $year = date('Y', time());
 
-               // Use configured min age or fixed?
-               if (GET_EXT_VERSION('other') >= '0.2.1') {
-                       // Configured
-                       $startYear = $year - getConfig('min_age');
-               } else {
-                       // Fixed 16 years
-                       $startYear = $year - 16;
-               }
+                       // Use configured min age or fixed?
+                       if (GET_EXT_VERSION('other') >= '0.2.1') {
+                               // Configured
+                               $startYear = $year - getConfig('min_age');
+                       } else {
+                               // Fixed 16 years
+                               $startYear = $year - 16;
+                       }
+
+                       // Calculate earliest year (100 years old people can still enter Internet???)
+                       $minYear = $year - 100;
+
+                       // Check if the default value is larger than minimum and bigger than actual year
+                       if (($default > $minYear) && ($default >= $year)) {
+                               for ($idx = $year; $idx < ($year + 11); $idx++) {
+                                       $OUT .= "<option value=\"".$idx."\"";
+                                       if ($default == $idx) $OUT .= ' selected="selected"';
+                                       $OUT .= ">".$idx."</option>\n";
+                               } // END - for
+                       } elseif ($default == -1) {
+                               // Current year minus 1
+                               for ($idx = $startYear; $idx <= ($year + 1); $idx++)
+                               {
+                                       $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
+                               }
+                       } else {
+                               // Get current year and subtract the configured minimum age
+                               $OUT .= "<option value=\"".($minYear - 1)."\">&lt;".$minYear."</option>\n";
+                               // Calculate earliest year depending on extension version
+                               if (GET_EXT_VERSION('other') >= '0.2.1') {
+                                       // Use configured minimum age
+                                       $year = date('Y', time()) - getConfig('min_age');
+                               } else {
+                                       // Use fixed 16 years age
+                                       $year = date('Y', time()) - 16;
+                               }
 
-               // Calculate earliest year (100 years old people can still enter Internet???)
-               $minYear = $year - 100;
+                               // Construct year selection list
+                               for ($idx = $minYear; $idx <= $year; $idx++) {
+                                       $OUT .= "<option value=\"".$idx."\"";
+                                       if ($default == $idx) $OUT .= ' selected="selected"';
+                                       $OUT .= ">".$idx."</option>\n";
+                               } // END - for
+                       }
+                       break;
 
-               // Check if the default value is larger than minimum and bigger than actual year
-               if (($default > $minYear) && ($default >= $year)) {
-                       for ($idx = $year; $idx < ($year + 11); $idx++) {
+               case "sec":
+               case "min":
+                       for ($idx = 0; $idx < 60; $idx+=5) {
+                               if (strlen($idx) == 1) $idx = '0'.$idx;
                                $OUT .= "<option value=\"".$idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
                                $OUT .= ">".$idx."</option>\n";
                        } // END - for
-               } elseif ($default == -1) {
-                       // Current year minus 1
-                       for ($idx = $startYear; $idx <= ($year + 1); $idx++)
-                       {
-                               $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
-                       }
-               } else {
-                       // Get current year and subtract the configured minimum age
-                       $OUT .= "<option value=\"".($minYear - 1)."\">&lt;".$minYear."</option>\n";
-                       // Calculate earliest year depending on extension version
-                       if (GET_EXT_VERSION('other') >= '0.2.1') {
-                               // Use configured minimum age
-                               $year = date('Y', time()) - getConfig('min_age');
-                       } else {
-                               // Use fixed 16 years age
-                               $year = date('Y', time()) - 16;
-                       }
+                       break;
 
-                       // Construct year selection list
-                       for ($idx = $minYear; $idx <= $year; $idx++) {
+               case "hour":
+                       for ($idx = 0; $idx < 24; $idx++) {
+                               if (strlen($idx) == 1) $idx = '0'.$idx;
                                $OUT .= "<option value=\"".$idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
                                $OUT .= ">".$idx."</option>\n";
                        } // END - for
-               }
-               break;
-
-       case "sec":
-       case "min":
-               for ($idx = 0; $idx < 60; $idx+=5) {
-                       if (strlen($idx) == 1) $idx = '0'.$idx;
-                       $OUT .= "<option value=\"".$idx."\"";
-                       if ($default == $idx) $OUT .= ' selected="selected"';
-                       $OUT .= ">".$idx."</option>\n";
-               } // END - for
-               break;
-
-       case "hour":
-               for ($idx = 0; $idx < 24; $idx++) {
-                       if (strlen($idx) == 1) $idx = '0'.$idx;
-                       $OUT .= "<option value=\"".$idx."\"";
-                       if ($default == $idx) $OUT .= ' selected="selected"';
-                       $OUT .= ">".$idx."</option>\n";
-               } // END - for
-               break;
-
-       case 'yn':
-               $OUT .= "<option value=\"Y\"";
-               if ($default == 'Y') $OUT .= ' selected="selected"';
-               $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
-               if ($default == 'N') $OUT .= ' selected="selected"';
-               $OUT .= ">{--NO--}</option>\n";
-               break;
+                       break;
+
+               case 'yn':
+                       $OUT .= "<option value=\"Y\"";
+                       if ($default == 'Y') $OUT .= ' selected="selected"';
+                       $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
+                       if ($default == 'N') $OUT .= ' selected="selected"';
+                       $OUT .= ">{--NO--}</option>\n";
+                       break;
        }
        $OUT .= "    </select>\n";
        return $OUT;
@@ -1278,40 +1222,40 @@ function generateRandomCodde ($length, $code, $uid, $DATA = '') {
        if (!defined('_MAX')) define('_MAX', 15235);
 
        // Build server string
-       $server = $_SERVER['PHP_SELF'].constant('ENCRYPT_SEPERATOR').detectUserAgent().constant('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').constant('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH')."inc/databases.php");
+       $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH').'inc/databases.php');
 
        // Build key string
-       $keys = constant('SITE_KEY').constant('ENCRYPT_SEPERATOR').constant('DATE_KEY');
-       if (isConfigEntrySet('secret_key'))  $keys .= constant('ENCRYPT_SEPERATOR').getConfig('secret_key');
-       if (isConfigEntrySet('file_hash'))   $keys .= constant('ENCRYPT_SEPERATOR').getConfig('file_hash');
-       $keys .= constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
-       if (isConfigEntrySet('master_salt')) $keys .= constant('ENCRYPT_SEPERATOR').getConfig('master_salt');
+       $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
+       if (isConfigEntrySet('secret_key'))  $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
+       if (isConfigEntrySet('file_hash'))   $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
+       $keys .= getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
+       if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
 
        // Build string from misc data
-       $data   = $code.constant('ENCRYPT_SEPERATOR').$uid.constant('ENCRYPT_SEPERATOR').$DATA;
+       $data   = $code.getConfig('ENCRYPT_SEPERATOR').$uid.getConfig('ENCRYPT_SEPERATOR').$DATA;
 
        // Add more additional data
-       if (isSessionVariableSet('u_hash'))         $data .= constant('ENCRYPT_SEPERATOR').getSession('u_hash');
-       if (isUserIdSet())                          $data .= constant('ENCRYPT_SEPERATOR').getUserId();
-       if (isSessionVariableSet('mxchange_theme')) $data .= constant('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
-       if (isSessionVariableSet('mx_lang'))        $data .= constant('ENCRYPT_SEPERATOR').getLanguage();
-       if (isset($GLOBALS['refid']))               $data .= constant('ENCRYPT_SEPERATOR').$GLOBALS['refid'];
+       if (isSessionVariableSet('u_hash'))         $data .= getConfig('ENCRYPT_SEPERATOR').getSession('u_hash');
+       if (isUserIdSet())                          $data .= getConfig('ENCRYPT_SEPERATOR').getUserId();
+       if (isSessionVariableSet('mxchange_theme')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
+       if (isSessionVariableSet('mx_lang'))        $data .= getConfig('ENCRYPT_SEPERATOR').getLanguage();
+       if (isset($GLOBALS['refid']))               $data .= getConfig('ENCRYPT_SEPERATOR').$GLOBALS['refid'];
 
        // Calculate number for generating the code
-       $a = $code + constant('_ADD') - 1;
+       $a = $code + getConfig('_ADD') - 1;
 
        if (isConfigEntrySet('master_hash')) {
                // Generate hash with master salt from modula of number with the prime number and other data
-               $saltedHash = generateHash(($a % constant('_PRIME')).constant('ENCRYPT_SEPERATOR').$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a, getConfig('master_salt'));
+               $saltedHash = generateHash(($a % getConfig('_PRIME')).getConfig('ENCRYPT_SEPERATOR').$server.getConfig('ENCRYPT_SEPERATOR').$keys.getConfig('ENCRYPT_SEPERATOR').$data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').$a, getConfig('master_salt'));
 
                // Create number from hash
-               $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
+               $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $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 % constant('_PRIME')).constant('ENCRYPT_SEPERATOR').$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a, substr(sha1(constant('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, 8));
 
                // Create number from hash
-               $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
+               $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
        }
 
        // At least 10 numbers shall be secure enought!
@@ -1361,15 +1305,15 @@ function GENERATE_IMAGE ($img_code, $headerSent=true) {
                // Switch image type
                switch (getConfig('img_type'))
                {
-               case "jpg":
-                       // Okay, load image and hide all errors
-                       $image = @imagecreatefromjpeg($img);
-                       break;
+                       case 'jpg':
+                               // Okay, load image and hide all errors
+                               $image = @imagecreatefromjpeg($img);
+                               break;
 
-               case "png":
-                       // Okay, load image and hide all errors
-                       $image = @imagecreatefrompng($img);
-                       break;
+                       case 'png':
+                               // Okay, load image and hide all errors
+                               $image = @imagecreatefrompng($img);
+                               break;
                }
        } else {
                // Exit function here
@@ -1384,19 +1328,19 @@ function GENERATE_IMAGE ($img_code, $headerSent=true) {
        imagestring($image, 5, 14, 2, $img_code, $text_color);
 
        // Return to browser
-       header ("Content-Type: image/".getConfig('img_type'));
+       sendHeader('Content-Type: image/' . getConfig('img_type'));
 
        // Output image with matching image factory
        switch (getConfig('img_type')) {
-               case "jpg": imagejpeg($image); break;
-               case "png": imagepng($image);  break;
+               case 'jpg': imagejpeg($image); break;
+               case 'png': imagepng($image);  break;
        }
 
        // Remove image from memory
        imagedestroy($image);
 }
 // Create selection box or array of splitted timestamp
-function createTimeSelections ($timestamp, $prefix = '', $display = '', $align="center", $return_array=false) {
+function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
        // Calculate 2-seconds timestamp
        $stamp = round($timestamp);
        //* DEBUG: */ print("*".$stamp.'/'.$timestamp."*<br />");
@@ -1507,7 +1451,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align="
                        $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."\"";
+                               $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
                                if ($idx == $M) $OUT .= ' selected="selected"';
                                $OUT .= ">".$idx."</option>\n";
                        }
@@ -1628,11 +1572,11 @@ function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
 
        // Check which admin shall receive this mail
        $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
-               array($template), __FUNCTION__, __LINE__);
+       array($template), __FUNCTION__, __LINE__);
        if (SQL_NUMROWS($result) == 0) {
                // Create new entry (to all admins)
                SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
-                       array($template), __FUNCTION__, __LINE__);
+               array($template), __FUNCTION__, __LINE__);
        } else {
                // Load admin IDs...
                // @TODO This can be, somehow, rewritten
@@ -1648,27 +1592,27 @@ function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
                $result = false;
 
                // "implode" IDs and query string
-               $aid = implode(",", $adminIds);
-               if ($aid == "-1") {
+               $aid = implode(',', $adminIds);
+               if ($aid == '-1') {
                        if (EXT_IS_ACTIVE('events')) {
                                // Add line to user events
                                EVENTS_ADD_LINE($subj, $msg, $UID);
                        } else {
                                // Log error for debug
                                DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
-                                       $template,
-                                       $subj,
-                                       $UID
+                               $template,
+                               $subj,
+                               $UID
                                ));
                        }
                } elseif ($aid == '0') {
                        // Select all email adresses
                        $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
-                               __FUNCTION__, __LINE__);
+                       __FUNCTION__, __LINE__);
                } else {
                        // If Admin-ID is not "to-all" select
                        $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
-                               array($aid), __FUNCTION__, __LINE__);
+                       array($aid), __FUNCTION__, __LINE__);
                }
        }
 
@@ -1719,7 +1663,7 @@ function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
        $NAV = '';
        for ($page = 1; $page <= $PAGES; $page++) {
                // Is the page currently selected or shall we generate a link to it?
-               if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == "1"))) {
+               if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
                        // Is currently selected, so only highlight it
                        $NAV .= "<strong>-";
                } else {
@@ -1733,7 +1677,7 @@ function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
                        $NAV .= "\">";
                }
                $NAV .= $page;
-               if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == "1"))) {
+               if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
                        // Is currently selected, so only highlight it
                        $NAV .= "-</strong>";
                } else {
@@ -1901,7 +1845,7 @@ function sendRawRequest ($host, $request) {
                // Use login data to proxy? (username at least!)
                if (getConfig('proxy_username') != '') {
                        // Add it as well
-                       $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).constant('ENCRYPT_SEPERATOR').COMPILE_CODE(getConfig('proxy_password')));
+                       $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).getConfig('ENCRYPT_SEPERATOR').COMPILE_CODE(getConfig('proxy_password')));
                        $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
                } // END - if
 
@@ -1974,22 +1918,22 @@ function sendRawRequest ($host, $request) {
 }
 
 // Taken from www.php.net eregi() user comments
-function VALIDATE_EMAIL ($email) {
+function isEmailValid ($email) {
        // Compile email
        $email = COMPILE_CODE($email);
 
        // Check first part of email address
-       $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
+       $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
 
        //  Check domain
-       $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
+       $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
 
        // Generate pattern
-       $regex = '^'.$first.'@'.$domain.'$';
+       $regex = '@^' . $first . '\@' . $domain . '$@iU';
 
        // Return check result
-       // @TODO eregi() should be rewritten here
-       return eregi($regex, $email);
+       // @NOTE altered the regex-pattern and added modificator i (match both upper and lower case letters) and U (PCRE_UNGREEDY) to work with preg_match the same way as eregi
+       return preg_match($regex, $email);
 }
 
 // Function taken from user comments on www.php.net / function eregi()
@@ -2010,7 +1954,7 @@ function isUrlValid ($URL, $compile=true) {
 
        // If not installed, perform a simple test. Just make it sure there is always a http:// or
        // https:// in front of the URLs
-       return isUrlValid($URL);
+       return isUrlValidSimple($URL);
 }
 
 // Generate a list of administrative links to a given userid
@@ -2059,7 +2003,7 @@ function generateMemberEmailLink ($email, $table = 'admins') {
        if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
                // Create email link for contacting admin in guest area
                $EMAIL = adminsCreateEmailLink($email);
-               } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
+       } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
                // Create email link for contacting a member within admin area (or later in other areas, too?)
                $EMAIL = USER_generateMemberEmailLink($email);
        } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
@@ -2091,19 +2035,19 @@ function generateHash ($plainText, $salt = '') {
        // When the salt is empty build a new one, else use the first x configured characters as the salt
        if (empty($salt)) {
                // Build server string (inc/databases.php is no longer updated with every commit)
-               $server = $_SERVER['PHP_SELF'].constant('ENCRYPT_SEPERATOR').detectUserAgent().constant('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').constant('ENCRYPT_SEPERATOR').detectRemoteAddr();
+               $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
 
                // Build key string
-               $keys   = constant('SITE_KEY').constant('ENCRYPT_SEPERATOR').constant('DATE_KEY').constant('ENCRYPT_SEPERATOR').getConfig('secret_key').constant('ENCRYPT_SEPERATOR').getConfig('file_hash').constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).constant('ENCRYPT_SEPERATOR').getConfig('master_salt');
+               $keys   = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key').getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash').getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
 
                // Additional data
-               $data = $plainText.constant('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).constant('ENCRYPT_SEPERATOR').time();
+               $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
 
                // Calculate number for generating the code
-               $a = time() + constant('_ADD') - 1;
+               $a = time() + getConfig('_ADD') - 1;
 
                // Generate SHA1 sum from modula of number and the prime number
-               $sha1 = sha1(($a % constant('_PRIME')).$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a);
+               $sha1 = sha1(($a % getConfig('_PRIME')).$server.getConfig('ENCRYPT_SEPERATOR').$keys.getConfig('ENCRYPT_SEPERATOR').$data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').$a);
                //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
                $sha1 = scrambleString($sha1);
                //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
@@ -2203,31 +2147,6 @@ function genScrambleString ($len) {
        return $scrambleString;
 }
 
-// Append data like session ID or referal ID to the given URL which would
-// normally be stored in cookies
-function addUrlData ($URL) {
-       // Init add
-       $add = '';
-
-       // Determine URL binder
-       $BIND = '?';
-       if (strpos($URL, '?') !== false) $BIND = '&amp;';
-
-       if ((!defined('__COOKIES')) || ((!constant('__COOKIES')))) {
-               // Cookies are not accepted
-               if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
-                       // Cookie found in URL
-                       $add .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
-               } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
-                       // Not found! So let's set default here
-                       $add .= $BIND."refid=".getConfig('def_refid');
-               }
-       } // END - if
-
-       // Add all together and return it
-       return $URL . $add;
-}
-
 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
 function generatePassString ($passHash) {
        // Return vanilla password hash
@@ -2242,9 +2161,9 @@ function generatePassString ($passHash) {
                        $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
                        $mod = dechex($idx);
                        if ($part1 > $part2) {
-                               $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
+                               $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
                        } elseif ($part2 > $part1) {
-                               $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
+                               $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
                        }
                        $mod = substr(round($mod), 0, 4);
                        $mod = str_repeat('0', 4-strlen($mod)).$mod;
@@ -2253,7 +2172,7 @@ function generatePassString ($passHash) {
                        $newHash .= $mod;
                } // END - for
 
-               //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
+               //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).')');
                $ret = generateHash($newHash, getConfig('master_salt'));
                //* DEBUG: */ print($ret."<br />\n");
        } else {
@@ -2283,20 +2202,26 @@ function fixDeletedCookies ($cookies) {
 
 // Output error messages in a fasioned way and die...
 function app_die ($F, $L, $msg) {
-       // Load header
-       loadIncludeOnce('inc/header.php');
+       // Check if Script is already dieing and not let it kill itself another 1000 times
+       if (!isset($GLOBALS['app_died'])) {
+               // Make sure, that the script realy realy diese here and now
+               $GLOBALS['app_died'] = true;
 
-       // Prepare message for output
-       $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
+               // Load header
+               loadIncludeOnce('inc/header.php');
 
-       // Load the message template
-       LOAD_TEMPLATE('admin_settings_saved', false, $msg);
+               // Prepare message for output
+               $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
 
-       // Load footer
-       loadIncludeOnce('inc/footer.php');
+               // Load the message template
+               LOAD_TEMPLATE('admin_settings_saved', false, $msg);
 
-       // Exit explicitly
-       shutdown();
+               // Load footer
+               loadIncludeOnce('inc/footer.php');
+       } else {
+               // Script tried to kill itself twice
+               debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $msg . ', file/function=' . $F . ', line=' . $L);
+       }
 }
 
 // Display parsing time and number of SQL queries in footer
@@ -2363,31 +2288,6 @@ function isApacheModuleLoaded ($apacheModule) {
        return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
 }
 
-// "Getter" for language strings
-// @TODO Rewrite all language constants to this function.
-function getMessage ($messageId) {
-       // Default is not found!
-       $return = '!'.$messageId.'!';
-
-       // Is the language string found?
-       if (isset($GLOBALS['msg'][strtolower($messageId)])) {
-               // Language array element found in small_letters
-               $return = $GLOBALS['msg'][$messageId];
-       } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
-               // @DEPRECATED Language array element found in BIG_LETTERS
-               $return = $GLOBALS['msg'][$messageId];
-       } elseif (defined($messageId)) {
-               // @DEPRECATED Deprecated constant found
-               $return = constant($messageId);
-       } else {
-               // Missing language constant
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
-       }
-
-       // Return the string
-       return $return;
-}
-
 // Get current theme name
 function getCurrentTheme() {
        // The default theme is 'default'... ;-)
@@ -2460,7 +2360,7 @@ function getThemeId ($name) {
        } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
                // Check if current theme is already imported or not
                $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
-                       array($name), __FUNCTION__, __LINE__);
+               array($name), __FUNCTION__, __LINE__);
 
                // Entry found?
                if (SQL_NUMROWS($result) == 1) {
@@ -2476,60 +2376,6 @@ function getThemeId ($name) {
        return $id;
 }
 
-// Read a given file
-function readFromFile ($FQFN, $sqlPrepare = false) {
-       // Load the file
-       if (function_exists('file_get_contents')) {
-               // Use new function
-               $content = file_get_contents($FQFN);
-       } else {
-               // Fall-back to implode-file chain
-               $content = implode('', file($FQFN));
-       }
-
-       // Prepare SQL queries?
-       if ($sqlPrepare === true) {
-               // Remove some unwanted chars
-               $content = str_replace("\r", '', $content);
-               $content = str_replace("\n\n", "\n", $content);
-       } // END - if
-
-       // Return the content
-       return $content;
-}
-
-// Writes content to a file
-function writeToFile ($FQFN, $content) {
-       // Is the file writeable?
-       if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
-               // Not writeable!
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
-
-               // Failed! :(
-               return false;
-       } // END - if
-
-       // By default all is failed...
-       $return = false;
-
-       // Is the function there?
-       if (function_exists('file_put_contents')) {
-               // Write it directly
-               $return = file_put_contents($FQFN, $content);
-       } else {
-               // Write it with fopen
-               $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
-               fwrite($fp, $content);
-               fclose($fp);
-
-               // Set CHMOD rights
-               $return = chmod($FQFN, 0644);
-       }
-
-       // Return status
-       return $return;
-}
-
 // Generates an error code from given account status
 function generateErrorCodeFromUserStatus ($status) {
        // Default error code if unknown account status
@@ -2551,21 +2397,12 @@ function generateErrorCodeFromUserStatus ($status) {
        return $errorCode;
 }
 
-// Clears the output buffer. This function does *NOT* backup sent content.
-function clearOutputBuffer () {
-       // Trigger an error on failure
-       if (!ob_end_clean()) {
-               // Failed!
-               debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
-       } // END - if
-}
-
 // Function to search for the last modifified file
 function searchDirsRecursive ($dir, &$last_changed) {
        // Get dir as array
        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
        // 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
+       // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
        $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
        $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
@@ -2578,7 +2415,7 @@ function searchDirsRecursive ($dir, &$last_changed) {
                // Is it a file and readable?
                //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
                if (isDirectory($FQFN)) {
-                        // $FQFN is a directory so also crawl into this directory
+                       // $FQFN is a directory so also crawl into this directory
                        $newDir = $d;
                        if (!empty($dir)) $newDir = $dir . '/'. $d;
                        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
@@ -2606,8 +2443,8 @@ function getActualVersion ($type = 'Revision') {
                // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
                if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
                if (!isset($GLOBALS['cache_array']['revision'][$type])
-                       || count($GLOBALS['cache_array']['revision']) < 3
-                       || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
+               || count($GLOBALS['cache_array']['revision']) < 3
+               || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
 
                // Is the cache file outdated/invalid?
                if ($new === true){
@@ -2707,9 +2544,9 @@ function getArrayFromActualVersion () {
 
        // at least 3 keyword-Tags are needed for propper values
        if ($res && $res >= 3
-               && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
-               && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
-               && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
+       && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
+       && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
+       && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
                // Prepare content witch need special treadment
 
                // Prepare timestamp for date
@@ -2737,35 +2574,6 @@ function getArrayFromActualVersion () {
        return $akt_vers;
 }
 
-
-// Loads an include file and logs any missing files for debug purposes
-function loadInclude ($INC) {
-       // Add the path. This is why we need a trailing slash in config.php
-       $FQFN = constant('PATH') . $INC;
-
-       // Is the include file there?
-       if (!isIncludeReadable($INC)) {
-               // Not there so log it
-               debug_report_bug(sprintf("Include file %s not found.", $INC));
-               return false;
-       } // END - if
-
-       // Try to load it
-       require($FQFN);
-}
-
-// Loads an include file once
-function loadIncludeOnce ($INC) {
-       // Is it not loaded?
-       if (!isset($GLOBALS['load_once'][$INC])) {
-               // Then try to load it
-               loadInclude($INC);
-
-               // And mark it as loaded
-               $GLOBALS['load_once'][$INC] = "loaded";
-       } // END - if
-}
-
 // Back-ported from the new ship-simu engine. :-)
 function debug_get_printable_backtrace () {
        // Init variable
@@ -2777,7 +2585,7 @@ function debug_get_printable_backtrace () {
                if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
                if (!isset($trace['line'])) $trace['line'] = __LINE__;
                if (!isset($trace['args'])) $trace['args'] = array();
-               $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span></li>\n";
+               $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function'].'('.count($trace['args']).")</span></li>\n";
        } // END - foreach
 
        // Close it
@@ -2795,7 +2603,7 @@ function debug_report_bug ($message = '') {
        if (!empty($message)) {
                // Use and log it
                $debug = sprintf("Note: %s<br />\n",
-                       $message
+               $message
                );
 
                // @TODO Add a little more infos here
@@ -2805,7 +2613,7 @@ function debug_report_bug ($message = '') {
        // Add output
        $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
        $debug .= debug_get_printable_backtrace();
-       $debug .= "</pre>Request-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
+       $debug .= "</pre>\nRequest-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
        $debug .= "Thank you for finding bugs.";
 
        // And abort here
@@ -2841,8 +2649,8 @@ function convertCodeToMessage ($code) {
                        break;
 
                case getCode('EXTENSION_PROBLEM'):
-                       if (REQUEST_ISSET_GET(('ext'))) {
-                               $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
+                       if (REQUEST_ISSET_GET('ext')) {
+                               $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET('ext'));
                        } else {
                                $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
                        }
@@ -2896,29 +2704,6 @@ function generateAdminLink ($aid) {
        return $admin;
 }
 
-// Checks wether an include file (non-FQFN better) is readable
-function isIncludeReadable ($INC) {
-       // Construct FQFN
-       $FQFN = constant('PATH') . $INC;
-
-       // Is it readable?
-       return isFileReadable($FQFN);
-}
-
-// Encode strings
-// @TODO Implement $compress
-function encodeString ($str, $compress=true) {
-       $str = urlencode(base64_encode(compileUriCode($str)));
-       return $str;
-}
-
-// Decode strings encoded with encodeString()
-// @TODO Implement $decompress
-function decodeString ($str, $decompress=true) {
-       $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
-       return $str;
-}
-
 // Compile characters which are allowed in URLs
 function compileUriCode ($code, $simple=true) {
        // Compile constants
@@ -2926,15 +2711,15 @@ function compileUriCode ($code, $simple=true) {
 
        // Compile QUOT and other non-HTML codes
        $code = str_replace('{DOT}', '.',
-               str_replace('{SLASH}', '/',
-               str_replace('{QUOT}', "'",
-               str_replace('{DOLLAR}', '$',
-               str_replace('{OPEN_ANCHOR}', '(',
-               str_replace('{CLOSE_ANCHOR}', ')',
-               str_replace('{OPEN_SQR}', '[',
-               str_replace('{CLOSE_SQR}', ']',
-               str_replace('{PER}', '%',
-               $code
+       str_replace('{SLASH}', '/',
+       str_replace('{QUOT}', "'",
+       str_replace('{DOLLAR}', '$',
+       str_replace('{OPEN_ANCHOR}', '(',
+       str_replace('{CLOSE_ANCHOR}', ')',
+       str_replace('{OPEN_SQR}', '[',
+       str_replace('{CLOSE_SQR}', ']',
+       str_replace('{PER}', '%',
+       $code
        )))))))));
 
        // Return compiled code
@@ -2942,7 +2727,7 @@ function compileUriCode ($code, $simple=true) {
 }
 
 // Function taken from user comments on www.php.net / function eregi()
-function isUrlValid ($url) {
+function isUrlValidSimple ($url) {
        // Prepare URL
        $url = strip_tags(str_replace("\\", '', compileUriCode(urldecode($url))));
 
@@ -3008,21 +2793,6 @@ function isUrlValid ($url) {
        return $reg;
 }
 
-// Smartly adds slashes
-function smartAddSlashes ($unquoted) {
-       $unquoted = str_replace("\\", '', $unquoted);
-       return addslashes($unquoted);
-}
-
-// Decode entities in a nicer way
-function decodeEntities ($str) {
-       // Decode the entities to UTF-8 now
-       $decodedString = html_entity_decode($str, ENT_NOQUOTES, "UTF-8");
-
-       // Return decoded string
-       return $decodedString;
-}
-
 // Wtites data to a config.php-style file
 // @TODO Rewrite this function to use readFromFile() and writeToFile()
 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
@@ -3034,16 +2804,16 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
 
        // Is the file there and read-/write-able?
        if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
-               $search = "CFG: ".$comment;
-               $tmp = $FQFN.".tmp";
+               $search = 'CFG: ' . $comment;
+               $tmp = $FQFN . '.tmp';
 
                // Open the source file
-               $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
+               $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . "<br />\n");
 
                // Is the resource valid?
                if (is_resource($fp)) {
                        // Open temporary file
-                       $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
+                       $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . "<br />\n");
 
                        // Is the resource again valid?
                        if (is_resource($fp_tmp)) {
@@ -3056,7 +2826,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
                                        if ($next > -1) {
                                                if ($next === $seek) {
                                                        $next = -1;
-                                                       $line = $prefix . $DATA . $suffix."\n";
+                                                       $line = $prefix . $DATA . $suffix . "\n";
                                                } else {
                                                        $next++;
                                                }
@@ -3064,31 +2834,31 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
 
                                        // Write to temp file
                                        fputs($fp_tmp, $line);
-                               }
+                               } // END - while
 
                                // Close temp file
                                fclose($fp_tmp);
 
                                // Finished writing tmp file
                                $done = true;
-                       }
+                       } // END - if
 
                        // Close source file
                        fclose($fp);
 
-                       if (($done) && ($found)) {
+                       if (($done === true) && ($found === true)) {
                                // Copy back tmp file and delete tmp :-)
-                               copy($tmp, $FQFN);
-                               return unlink($tmp);
-                       } elseif (!$found) {
-                               OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
+                               copyFileVerified($tmp, $FQFN, 0644);
+                               return removeFile($tmp);
+                       } elseif ($found === false) {
+                               OUTPUT_HTML('<strong>CHANGE:</strong> 404!');
                        } else {
-                               OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
+                               OUTPUT_HTML('<strong>TMP:</strong> UNDONE!');
                        }
                }
        } else {
                // File not found, not readable or writeable
-               OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
+               OUTPUT_HTML('<strong>404:</strong> ' . $FQFN . '<br />');
        }
 
        // An error was detected!
@@ -3106,26 +2876,6 @@ function sendAdminNotification ($subject, $templateName, $content=array(), $uid
        }
 }
 
-// Merges an array together but only if both are arrays
-function merge_array ($array1, $array2) {
-       // Are both an array?
-       if ((is_array($array1)) && (is_array($array2))) {
-               // Merge all together
-               return array_merge($array1, $array2);
-       } elseif (is_array($array1)) {
-               // Return left array
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
-               return $array1;
-       } elseif (is_array($array2)) {
-               // Return right array
-               DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
-               return $array2;
-       }
-
-       // Both are not arrays
-       debug_report_bug(__FUNCTION__.": No arrays provided!");
-}
-
 // Debug message logger
 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
        // Is debug mode enabled?
@@ -3152,7 +2902,7 @@ function runResetIncludes () {
        SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
 
        // Update database
-       if (!defined('DEBUG_RESET')) updateConfiguration('last_update', time());
+       if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
 
        // Is the config entry set?
        if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
@@ -3165,7 +2915,7 @@ function runResetIncludes () {
                        MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
 
                        // Update config
-                       if (!defined('DEBUG_WEEKLY')) updateConfiguration('last_week', $currWeek);
+                       if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
                } // END - if
 
                // Create current month mark
@@ -3177,7 +2927,7 @@ function runResetIncludes () {
                        MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
 
                        // Update config
-                       if (!defined('DEBUG_MONTHLY')) updateConfiguration('last_month', $currMonth);
+                       if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
                } // END - if
        } // END - if
 
@@ -3218,12 +2968,6 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
        return $ret;
 }
 
-// Check if given FQFN is a readable file
-function isFileReadable ($FQFN) {
-       // Check all...
-       return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
-}
-
 // Converts timestamp selections into a timestamp
 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
        // Init test variable
@@ -3294,7 +3038,7 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
                        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
                        $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
@@ -3372,8 +3116,8 @@ function determineRealRemoteAddress () {
        }
 
        // This strips out the real address from proxy output
-       if (strstr($address, ",")){
-               $addressArray = explode(",", $address);
+       if (strstr($address, ',')){
+               $addressArray = explode(',', $address);
                $address = $addressArray[0];
        } // END - if
 
@@ -3381,66 +3125,6 @@ function determineRealRemoteAddress () {
        return $address;
 }
 
-// "Getter" for remote IP number
-function detectRemoteAddr () {
-       // Get remote ip from environment
-       $remoteAddr = determineRealRemoteAddress();
-
-       // Is removeip installed?
-       if (EXT_IS_ACTIVE('removeip')) {
-               // Then anonymize it
-               $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
-       } // END - if
-
-       // Return it
-       return $remoteAddr;
-}
-
-// "Getter" for remote hostname
-function detectRemoteHostname () {
-       // Get remote ip from environment
-       $remoteHost = getenv('REMOTE_HOST');
-
-       // Is removeip installed?
-       if (EXT_IS_ACTIVE('removeip')) {
-               // Then anonymize it
-               $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
-       } // END - if
-
-       // Return it
-       return $remoteHost;
-}
-
-// "Getter" for user agent
-function detectUserAgent () {
-       // Get remote ip from environment
-       $userAgent = getenv('HTTP_USER_AGENT');
-
-       // Is removeip installed?
-       if (EXT_IS_ACTIVE('removeip')) {
-               // Then anonymize it
-               $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
-       } // END - if
-
-       // Return it
-       return $userAgent;
-}
-
-// "Getter" for referer
-function detectReferer () {
-       // Get remote ip from environment
-       $referer = getenv('HTTP_REFERER');
-
-       // Is removeip installed?
-       if (EXT_IS_ACTIVE('removeip')) {
-               // Then anonymize it
-               $referer = GET_ANONYMOUS_REFERER($referer);
-       } // END - if
-
-       // Return it
-       return $referer;
-}
-
 // Adds a bonus mail to the queue
 // This is a high-level function!
 function addNewBonusMail ($data, $mode = '', $output=true) {
@@ -3454,15 +3138,15 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
        if (!empty($RECEIVER)) {
                // Add bonus mail to queue
                addBonusMailToQueue(
-                       $data['subject'],
-                       $data['text'],
-                       $RECEIVER,
-                       $data['points'],
-                       $data['seconds'],
-                       $data['url'],
-                       $data['cat'],
-                       $mode,
-                       $data['receiver']
+               $data['subject'],
+               $data['text'],
+               $RECEIVER,
+               $data['points'],
+               $data['seconds'],
+               $data['url'],
+               $data['cat'],
+               $mode,
+               $data['receiver']
                );
 
                // Mail inserted into bonus pool
@@ -3499,7 +3183,7 @@ function DETERMINE_REFID () {
                $GLOBALS['refid'] = getConfig(('def_refid'));
        } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
                // Select a random user which has confirmed enougth mails
-               $GLOBALS['refid'] = SELECT_RANDOM_REFID();
+               $GLOBALS['refid'] = determineRandomReferalId();
        } else {
                // No default ID when sql_patches is not installed or none set
                $GLOBALS['refid'] = 0;
@@ -3515,23 +3199,6 @@ function DETERMINE_REFID () {
        return $GLOBALS['refid'];
 }
 
-// Check wether we are installing
-function isInstalling () {
-       $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
-       //* DEBUG: */ var_dump($installing);
-       return $installing;
-}
-
-// Check wether this script is installed
-function isInstalled () {
-       return isBooleanConstantAndTrue('mxchange_installed');
-}
-
-// Check wether an admin is registered
-function isAdminRegistered () {
-       return isBooleanConstantAndTrue('admin_registered');
-}
-
 // Enables the reset mode. Only call this function if you really want the
 // reset to be run!
 function enableResetMode () {
@@ -3542,23 +3209,6 @@ function enableResetMode () {
        runFilterChain('reset_enabled');
 }
 
-// Checks wether the reset mode is active
-function isResetModeEnabled () {
-       // Now simply check it
-       return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
-}
-
-// Checks wether the debug mode is enabled
-function isDebugModeEnabled () {
-       // Simply check it
-       return isBooleanConstantAndTrue('DEBUG_MODE');
-}
-
-// Checks wether the cache instance is valid
-function isCacheInstanceValid () {
-       return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
-}
-
 // Our shutdown-function
 function shutdown () {
        // Call the filter chain 'shutdown'
@@ -3601,35 +3251,45 @@ function isUserIdSet () {
        return (isset($GLOBALS['userid']));
 }
 
-// Checks wether the given FQFN is a directory and not .,.. or .svn
-function isDirectory ($FQFN) {
-       // Generate baseName
-       $baseName = basename($FQFN);
-
-       // Check it
-       $isDirectory = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != ".svn"));
-
-       // Return the result
-       return $isDirectory;
-}
-
 // Handle message codes from URL
 function handleCodeMessage () {
-       if (REQUEST_ISSET_GET(('msg'))) {
+       if (REQUEST_ISSET_GET('msg')) {
                // Default extension is "unknown"
-               $ext = "unknown";
+               $ext = 'unknown';
 
                // Is extension given?
-               if (REQUEST_ISSET_GET(('ext'))) $ext = REQUEST_GET(('ext'));
+               if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
 
                // Convert the 'msg' parameter from URL to a human-readable message
                $msg = convertCodeToMessage(REQUEST_GET('msg'));
 
                // Load message template
-               LOAD_TEMPLATE("message", false, $msg);
+               LOAD_TEMPLATE('message', false, $msg);
        } // END - if
 }
 
+// Setter for extra title
+function setExtraTitle ($extraTitle) {
+       $GLOBALS['extra_title'] = $extraTitle;
+}
+
+// Getter for extra title
+function getExtraTitle () {
+       // Is the extra title set?
+       if (!isExtraTitleSet()) {
+               // No, then abort here
+               debug_report_bug('extra_title is not set!');
+       } // END - if
+
+       // Return it
+       return $GLOBALS['extra_title'];
+}
+
+// Checks if the extra title is set
+function isExtraTitleSet () {
+       return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
+}
+
 //////////////////////////////////////////////////
 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
 //////////////////////////////////////////////////