EOL for HTTP request moved to config, errno and err_desc initialized (was absend)
[mailer.git] / inc / functions.php
index 7262baf0b705d1fad031146fbf42b482dcdac4dc..637412fc66ae8626244eebb5df5c42150225fc59 100644 (file)
@@ -51,37 +51,36 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
                // Yes, so we handle it as you have configured
                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.", getConfig('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)) {
                // Headers already sent?
@@ -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)) {
@@ -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...
@@ -549,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;
 }
@@ -636,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
@@ -673,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
@@ -710,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;
 }
@@ -731,51 +730,6 @@ 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 = getConfig('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);
-               } // END - if
-       } 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 = getConfig('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;
@@ -829,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
@@ -951,7 +905,7 @@ function redirectToUrl ($URL) {
        } // 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);
 
@@ -1161,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;
+                       // 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;
+                               }
 
-               // 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++) {
+                               // 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;
+
+               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;
@@ -1351,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
@@ -1497,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";
                        }
@@ -1618,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
@@ -1646,19 +1600,19 @@ function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $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__);
                }
        }
 
@@ -1799,17 +1753,17 @@ function sendGetRequest ($script) {
        $host = extractHostnameFromUrl($script);
 
        // Generate GET request header
-       $request  = "GET /" . trim($script) . " HTTP/1.1\r\n";
-       $request .= "Host: " . $host . "\r\n";
-       $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
+       $request  = "GET /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
+       $request .= "Host: " . $host . getConfig('HTTP_EOL');
+       $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
        if (defined('FULL_VERSION')) {
-               $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
+               $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
        } else {
-               $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
+               $request .= "User-Agent: " . constant('TITLE') . "/?.?.?" . getConfig('HTTP_EOL');
        }
-       $request .= "Content-Type: text/plain\r\n";
-       $request .= "Cache-Control: no-cache\r\n";
-       $request .= "Connection: Close\r\n\r\n";
+       $request .= "Content-Type: text/plain" . getConfig('HTTP_EOL');
+       $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
+       $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
 
        // Send the raw request
        $response = sendRawRequest($host, $request);
@@ -1837,14 +1791,14 @@ function sendPostRequest ($script, $postData) {
        $data = http_build_query($postData, '','&');
 
        // Generate POST request header
-       $request  = "POST /" . trim($script) . " HTTP/1.1\r\n";
-       $request .= "Host: " . $host . "\r\n";
-       $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
-       $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
-       $request .= "Content-type: application/x-www-form-urlencoded\r\n";
-       $request .= "Content-length: " . strlen($data) . "\r\n";
-       $request .= "Cache-Control: no-cache\r\n";
-       $request .= "Connection: Close\r\n\r\n";
+       $request  = "POST /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
+       $request .= "Host: " . $host . getConfig('HTTP_EOL');
+       $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
+       $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
+       $request .= "Content-type: application/x-www-form-urlencoded" . getConfig('HTTP_EOL');
+       $request .= "Content-length: " . strlen($data) . getConfig('HTTP_EOL');
+       $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
+       $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
        $request .= $data;
 
        // Send the raw request
@@ -1856,6 +1810,9 @@ function sendPostRequest ($script, $postData) {
 
 // Sends a raw request to another host
 function sendRawRequest ($host, $request) {
+       // Init errno and errdesc with 'all fine' values
+       $errno = 0; $errdesc = '';
+
        // Initialize array
        $response = array('', '', '');
 
@@ -1885,18 +1842,18 @@ function sendRawRequest ($host, $request) {
        // Do we use proxy?
        if ($useProxy) {
                // Generate CONNECT request header
-               $proxyTunnel  = "CONNECT ".$host.":80 HTTP/1.1\r\n";
-               $proxyTunnel .= "Host: ".$host."\r\n";
+               $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(COMPILE_CODE(getConfig('proxy_username')).getConfig('ENCRYPT_SEPERATOR').COMPILE_CODE(getConfig('proxy_password')));
-                       $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
+                       $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
                } // END - if
 
                // Add last new-line
-               $proxyTunnel .= "\r\n";
+               $proxyTunnel .= getConfig('HTTP_EOL');
                //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
 
                // Write request
@@ -1964,22 +1921,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()
@@ -2049,7 +2006,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')) {
@@ -2248,20 +2205,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
@@ -2328,31 +2291,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'... ;-)
@@ -2425,7 +2363,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) {
@@ -2467,7 +2405,7 @@ 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";
@@ -2480,7 +2418,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";
@@ -2508,8 +2446,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){
@@ -2609,9 +2547,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
@@ -2668,7 +2606,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
@@ -2676,7 +2614,7 @@ function debug_report_bug ($message = '') {
        } // END - if
 
        // Add output
-       $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
+       $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>inc/cache/debug.log</strong> in your report (you cannot attach files!):<pre>";
        $debug .= debug_get_printable_backtrace();
        $debug .= "</pre>\nRequest-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
        $debug .= "Thank you for finding bugs.";
@@ -2776,15 +2714,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
@@ -2869,16 +2807,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)) {
@@ -2891,7 +2829,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++;
                                                }
@@ -2899,31 +2837,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!
@@ -3203,15 +3141,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