Typo 'referral'->'referal' fixed, more 'empty version' fixed
[mailer.git] / inc / functions.php
index 0048109565812153f65ca8df08c1c64097237ab6..7b691f4bfe5e4686c0423e3512f2cfe9aa8e1e40 100644 (file)
@@ -116,7 +116,7 @@ function outputHtml ($htmlCode, $newLine = true) {
                sendHeader('Content-language: ' . getLanguage());
 
                // Extension 'rewrite' installed?
-               if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
+               if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
@@ -148,7 +148,7 @@ function outputHtml ($htmlCode, $newLine = true) {
                outputRawCode($GLOBALS['output']);
        } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
                // Rewrite links when rewrite extension is active
-               if ((isExtensionActive('rewrite')) && (getOutputMode() != '1')) {
+               if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
                        $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
                } // END - if
 
@@ -241,39 +241,11 @@ function loadTemplate ($template, $return=false, $content=array()) {
                if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
 
                // Generate date/time string
-               $date_time = generateDateTime(time(), '1');
+               $date_time = generateDateTime(time(), 1);
 
                // Is content an array
                if (is_array($content)) $content['date_time'] = $date_time;
 
-               // @DEPRECATED Try to rewrite the if() condition
-               if ($template == 'member_support_form') {
-                       // Support request of a member
-                       $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(getUserId()), __FUNCTION__, __LINE__);
-
-                       // Is content an array?
-                       if (is_array($content)) {
-                               // Merge data
-                               $content = merge_array($content, SQL_FETCHARRAY($result));
-
-                               // Translate gender
-                               $content['gender'] = translateGender($content['gender']);
-                       } else {
-                               // @DEPRECATED
-                               // @TODO Find all templates which are using these direct variables and rewrite them.
-                               // @TODO After this step is done, this else-block is history
-                               list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
-
-                               // Translate gender
-                               $gender = translateGender($gender);
-                               logDebugMessage(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
-                       }
-
-                       // Free result
-                       SQL_FREERESULT($result);
-               } // END - if
-
                // Base directory
                $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
                $mode = '';
@@ -353,7 +325,7 @@ function loadTemplate ($template, $return=false, $content=array()) {
                        $ret = '';
                        if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false)) {
                                // Normal HTML output?
-                               if ($GLOBALS['output_mode'] == 0) {
+                               if (getOutputMode() == 0) {
                                        // Add surrounding HTML comments to help finding bugs faster
                                        $ret = "<!-- Template " . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . "<!-- Template " . $template . " - End -->\n";
 
@@ -410,7 +382,7 @@ function loadTemplate ($template, $return=false, $content=array()) {
 }
 
 // Loads an email template and compiles it
-function loadEmailTemplate ($template, $content = array(), $UID = '0') {
+function loadEmailTemplate ($template, $content = array(), $UID = 0) {
        global $DATA;
 
        // Our configuration is kept non-global here
@@ -458,28 +430,25 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        } // END - if
 
        // Load user's data
-       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />");
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content).'<br />');
        if (($UID > 0) && (is_array($content))) {
                // If nickname extension is installed, fetch nickname as well
-               if (isExtensionActive('nickname')) {
+               if (isNicknameUsed($UID)) {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />");
-                       // Load nickname
-                       $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email`, `nickname` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(bigintval($UID)), __FUNCTION__, __LINE__);
+                       // Load by nickname
+                       fetchUserData($UID, 'nickname');
                } else {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />");
-                       /// Load normal data
-                       $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(bigintval($UID)), __FUNCTION__, __LINE__);
+                       /// Load by userid
+                       fetchUserData($UID);
                }
 
-               // Fetch and merge data
+               // Merge data if valid
                //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
-               $content = merge_array($content, SQL_FETCHARRAY($result));
+               if (isUserDataValid()) {
+                       $content = merge_array($content, getUserDataArray());
+               } // END - if
                //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
-
-               // Free result
-               SQL_FREERESULT($result);
        } // END - if
 
        // Translate M to male or F to female if present
@@ -527,10 +496,9 @@ function loadEmailTemplate ($template, $content = array(), $UID = '0') {
        if (isFileReadable($FQFN)) {
                // The local file does exists so we load it. :)
                $GLOBALS['tpl_content'] = readFromFile($FQFN);
-               $GLOBALS['tpl_content'] = SQL_ESCAPE($GLOBALS['tpl_content']);
 
                // Run code
-               $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode($GLOBALS['tpl_content'])."\");";
+               $GLOBALS['tpl_content'] = "\$newContent = decodeEntities(\"".compileCode(smartAddSlashes($GLOBALS['tpl_content']))."\");";
                eval($GLOBALS['tpl_content']);
        } elseif (!empty($template)) {
                // Template file not found!
@@ -583,22 +551,14 @@ function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '
                        ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
                        return;
                } else {
-                       // Load email address
-                       $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
-                               array(bigintval($toEmail)), __FUNCTION__, __LINE__);
-                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
-
                        // Does the user exist?
-                       if (SQL_NUMROWS($result_email)) {
-                               // Load email address
-                               list($toEmail) = SQL_FETCHROW($result_email);
+                       if (fetchUserData($toEmail)) {
+                               // Get the email
+                               $toEmail = getUserData('email');
                        } else {
                                // Set webmaster
                                $toEmail = getConfig('WEBMASTER');
                        }
-
-                       // Free result
-                       SQL_FREERESULT($result_email);
                }
        } elseif ($toEmail == '0') {
                // Is the webmaster!
@@ -636,12 +596,12 @@ function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '
        if (empty($isHtml)) $isHtml = 'N';
        if (isDebugModeEnabled()) {
                // In debug mode we want to display the mail instead of sending it away so we can debug this part
-               outputHtml("<pre>
-".htmlentities(trim($mailHeader))."
-To      : " . $toEmail."
-Subject : " . $subject."
-Message : " . $message."
-</pre>\n");
+               outputHtml('<pre>
+Headers : ' . str_replace('<', '&lt', str_replace('>', '&gt;', htmlentities(trim($mailHeader)))) . '
+To      : ' . $toEmail . '
+Subject : ' . $subject . '
+Message : ' . $message . '
+</pre>');
        } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
                // Send mail as HTML away
                sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
@@ -671,6 +631,11 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
 
                // get new instance
                $mail = new PHPMailer();
+
+               // Set charset to UTF-8
+               $mail->CharSet('UTF-8');
+
+               // Path for PHPMailer
                $mail->PluginDir  = sprintf("%sinc/phpmailer/", getConfig('PATH'));
 
                $mail->IsSMTP();
@@ -731,7 +696,7 @@ function generatePassword ($length = 0) {
 }
 
 // Generates a human-readable timestamp from the Uni* stamp
-function generateDateTime ($time, $mode = '0') {
+function generateDateTime ($time, $mode = 0) {
        // Filter out numbers
        $time = bigintval($time);
 
@@ -744,10 +709,10 @@ function generateDateTime ($time, $mode = '0') {
        switch (getLanguage()) {
                case 'de': // German date / time format
                        switch ($mode) {
-                               case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
-                               case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
-                               case '2': $ret = date('d.m.Y|H:i', $time); break;
-                               case '3': $ret = date('d.m.Y', $time); break;
+                               case 0: $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
+                               case 1: $ret = strtolower(date('d.m.Y - H:i', $time)); break;
+                               case 2: $ret = date('d.m.Y|H:i', $time); break;
+                               case 3: $ret = date('d.m.Y', $time); break;
                                default:
                                        logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
                                        break;
@@ -756,10 +721,10 @@ function generateDateTime ($time, $mode = '0') {
 
                default: // Default is the US date / time format!
                        switch ($mode) {
-                               case '0': $ret = date('r', $time); break;
-                               case '1': $ret = date('Y-m-d - g:i A', $time); break;
-                               case '2': $ret = date('y-m-d|H:i', $time); break;
-                               case '3': $ret = date('y-m-d', $time); break;
+                               case 0: $ret = date('r', $time); break;
+                               case 1: $ret = date('Y-m-d - g:i A', $time); break;
+                               case 2: $ret = date('y-m-d|H:i', $time); break;
+                               case 3: $ret = date('y-m-d', $time); break;
                                default:
                                        logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
                                        break;
@@ -808,7 +773,7 @@ function translatePoolType ($type) {
 // Translates the american decimal dot into a german comma
 function translateComma ($dotted, $cut = true, $max = 0) {
        // Default is 3 you can change this in admin area "Misc -> Misc Options"
-       if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
+       if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
 
        // Use from config is default
        $maxComma = getConfig('max_comma');
@@ -958,8 +923,8 @@ function makeTime ($hours, $minutes, $seconds, $stamp) {
 
 // Redirects to an URL and if neccessarry extends it with own base URL
 function redirectToUrl ($URL) {
-       // Compile out URI codes
-       $URL = compileUriCode($URL);
+       // Compile out codes
+       eval('$URL = "' . compileCode($URL) . '";');
 
        // Check if http(s):// is there
        if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
@@ -969,7 +934,7 @@ function redirectToUrl ($URL) {
 
        // Three different debug ways...
        //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $URL);
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
        //* DEBUG: */ die($URL);
 
        // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
@@ -1165,7 +1130,7 @@ function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums =
 }
 
 //
-function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
+function addSelectionBox ($type, $default, $prefix = '', $id = 0) {
        $OUT = '';
 
        if ($type == 'yn') {
@@ -1250,7 +1215,7 @@ function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
                case 'sec':
                case 'min':
                        for ($idx = 0; $idx < 60; $idx+=5) {
-                               if (strlen($idx) == 1) $idx = '0' . $idx;
+                               if (strlen($idx) == 1) $idx = 0 . $idx;
                                $OUT .= "<option value=\"" . $idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1259,7 +1224,7 @@ function addSelectionBox ($type, $default, $prefix = '', $id = '0') {
 
                case 'hour':
                        for ($idx = 0; $idx < 24; $idx++) {
-                               if (strlen($idx) == 1) $idx = '0' . $idx;
+                               if (strlen($idx) == 1) $idx = 0 . $idx;
                                $OUT .= "<option value=\"" . $idx."\"";
                                if ($default == $idx) $OUT .= ' selected="selected"';
                                $OUT .= ">" . $idx."</option>\n";
@@ -1308,7 +1273,7 @@ function generateRandomCode ($length, $code, $userid, $DATA = '') {
        // Calculate number for generating the code
        $a = $code + getConfig('_ADD') - 1;
 
-       if (isConfigEntrySet('master_hash')) {
+       if (isConfigEntrySet('master_salt')) {
                // Generate hash with master salt from modula of number with the prime number and other data
                $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
 
@@ -1316,7 +1281,7 @@ function generateRandomCode ($length, $code, $userid, $DATA = '') {
                $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
        } else {
                // Generate hash with "hash of site key" from modula of number with the prime number and other data
-               $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, 8));
+               $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
 
                // Create number from hash
                $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
@@ -1662,7 +1627,7 @@ function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=fals
        $NAV = '';
        for ($page = 1; $page <= $PAGES; $page++) {
                // Is the page currently selected or shall we generate a link to it?
-               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
+               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
                        // Is currently selected, so only highlight it
                        $NAV .= '<strong>-';
                } else {
@@ -1676,7 +1641,7 @@ function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=fals
                        $NAV .= '">';
                }
                $NAV .= $page;
-               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == '1'))) {
+               if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
                        // Is currently selected, so only highlight it
                        $NAV .= '-</strong>';
                } else {
@@ -1725,7 +1690,7 @@ function extractHostnameFromUrl (&$script) {
        if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
 
        // Generate relative URL
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />");
+       //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
        if (substr(strtolower($script), 0, 7) == 'http://') {
                // But only if http:// is in front!
                $script = substr($script, (strlen($url) + 7));
@@ -1734,7 +1699,7 @@ function extractHostnameFromUrl (&$script) {
                $script = substr($script, (strlen($url) + 8));
        }
 
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />");
+       //* DEBUG: */ print("SCRIPT=" . $script.'<br />');
        if (substr($script, 0, 1) == '/') $script = substr($script, 1);
 
        // Return host name
@@ -1742,10 +1707,25 @@ function extractHostnameFromUrl (&$script) {
 }
 
 // Send a GET request
-function sendGetRequest ($script) {
+function sendGetRequest ($script, $data = array()) {
        // Extract host name from script
        $host = extractHostnameFromUrl($script);
 
+       // Add data
+       $scriptData = http_build_query($data, '', '&');
+
+       // Do we have a question-mark in the script?
+       if (strpos($script, '?') === false) {
+               // No, so first char must be question mark
+               $scriptData = '?' . $scriptData;
+       } else {
+               // Ok, add &
+               $scriptData = '&' . $scriptData;
+       }
+
+       // Add script data
+       $script .= $scriptData;
+
        // Generate GET request header
        $request  = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
        $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
@@ -1782,7 +1762,7 @@ function sendPostRequest ($script, $postData) {
        $host = extractHostnameFromUrl($script);
 
        // Construct request
-       $data = http_build_query($postData, '','&');
+       $data = http_build_query($postData, '', '&');
 
        // Generate POST request header
        $request  = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
@@ -1820,7 +1800,7 @@ function sendRawRequest ($host, $request) {
        } // END - if
 
        // Open connection
-       //* DEBUG: */ die("SCRIPT=" . $script."<br />");
+       //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
        if ($useProxy === true) {
                // Connect to host through proxy connection
                $fp = @fsockopen(compileCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
@@ -1938,11 +1918,11 @@ function isEmailValid ($email) {
 function isUrlValid ($URL, $compile=true) {
        // Trim URL a little
        $URL = trim(urldecode($URL));
-       //* DEBUG: */ outputHtml($URL."<br />");
+       //* DEBUG: */ outputHtml($URL.'<br />');
 
        // Compile some chars out...
        if ($compile === true) $URL = compileUriCode($URL, false, false, false);
-       //* DEBUG: */ outputHtml($URL."<br />");
+       //* DEBUG: */ outputHtml($URL.'<br />');
 
        // Check for the extension filter
        if (isExtensionActive('filter')) {
@@ -2021,7 +2001,7 @@ function generateEmailLink ($email, $table = 'admins') {
 // Generate a hash for extra-security for all passwords
 function generateHash ($plainText, $salt = '') {
        // Is the required extension 'sql_patches' there and a salt is not given?
-       if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches'))) && (empty($salt))) {
+       if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
                // Extension sql_patches is missing/outdated so we hash the plain text with MD5
                return md5($plainText);
        } // END - if
@@ -2059,8 +2039,15 @@ function generateHash ($plainText, $salt = '') {
                //* DEBUG: */ outputHtml($salt." (".strlen($salt).")<br />");
        } else {
                // Use given salt
+               //* DEBUG: */ print 'salt=' . $salt . '<br />';
                $salt = substr($salt, 0, getConfig('salt_length'));
-               //* DEBUG: */ outputHtml("GIVEN={$salt}<br />");
+               //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
+
+               // Sanity check on salt
+               if (strlen($salt) != getConfig('salt_length')) {
+                       // Not the same!
+                       debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
+               } // END - if
        }
 
        // Return hash
@@ -2153,7 +2140,7 @@ function generatePassString ($passHash) {
        $ret = $passHash;
 
        // Is a secret key and master salt already initialized?
-       if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
+       if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
                // Only calculate when the secret key is generated
                $newHash = ''; $start = 9;
                for ($idx = 0; $idx < 10; $idx++) {
@@ -2165,16 +2152,17 @@ function generatePassString ($passHash) {
                        } elseif ($part2 > $part1) {
                                $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
                        }
-                       $mod = substr(round($mod), 0, 4);
-                       $mod = str_repeat('0', 4-strlen($mod)) . $mod;
-                       //* DEBUG: */ outputHtml("*" . $start.'=' . $mod."*<br />");
+                       $mod = substr($mod, 0, 4);
+                       //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
+                       $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
+                       //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
                        $start += 4;
                        $newHash .= $mod;
                } // END - for
 
-               //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
+               //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
                $ret = generateHash($newHash, getConfig('master_salt'));
-               //* DEBUG: */ print($ret."<br />");
+               //* DEBUG: */ print('ret='.$ret.'<br />');
        } else {
                // Hash it simple
                //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
@@ -2295,7 +2283,7 @@ function getCurrentTheme () {
        $ret = 'default';
 
        // Load default theme if not empty from configuration
-       if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
+       if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
 
        if (!isSessionVariableSet('mxchange_theme')) {
                // Set default theme
@@ -2378,11 +2366,11 @@ function getThemeId ($name) {
 }
 
 // Generates an error code from given account status
-function generateErrorCodeFromUserStatus ($status) {
-       // @TODO The status should never be empty
-       if (empty($status)) {
-               // Something really bad happend here
-               debug_report_bug(__FUNCTION__ . ': status is empty.');
+function generateErrorCodeFromUserStatus ($status='') {
+       // If no status is provided, use the default, cached
+       if ((empty($status)) && (isMember())) {
+               // Get user status
+               $status = getUserData('status');
        } // END - if
 
        // Default error code if unknown account status
@@ -2407,12 +2395,12 @@ function generateErrorCodeFromUserStatus ($status) {
 // Function to search for the last modifified file
 function searchDirsRecursive ($dir, &$last_changed) {
        // Get dir as array
-       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />");
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
        // Does it match what we are looking for? (We skip a lot files already!)
        // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
        $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
        $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
-       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
+       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
 
        // Walk through all entries
        foreach ($ds as $d) {
@@ -2425,7 +2413,7 @@ function searchDirsRecursive ($dir, &$last_changed) {
                        // $FQFN is a directory so also crawl into this directory
                        $newDir = $d;
                        if (!empty($dir)) $newDir = $dir . '/'. $d;
-                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
+                       //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
                        searchDirsRecursive($newDir, $last_changed);
                } elseif (isFileReadable($FQFN)) {
                        // $FQFN is a filename and no directory
@@ -2604,6 +2592,17 @@ function debug_get_printable_backtrace () {
 
 // Output a debug backtrace to the user
 function debug_report_bug ($message = '') {
+       // Is this already called?
+       if (isset($GLOBALS[__FUNCTION__])) {
+               // Other backtrace
+               print 'Message:'.$message.'<br />Backtrace:<pre>';
+               debug_print_backtrace();
+               die('</pre>');
+       } // END - if
+
+       // Set this function as called
+       $GLOBALS[__FUNCTION__] = true;
+
        // Init message
        $debug = '';
 
@@ -2661,7 +2660,7 @@ function getMessageFromErrorCode ($code) {
                case getCode('OVERLENGTH')       : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
                case getCode('URL_FOUND')        : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
                case getCode('SUBJ_URL')         : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
-               case getCode('BLIST_URL')        : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), '0'); break;
+               case getCode('BLIST_URL')        : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
                case getCode('NO_RECS_LEFT')     : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
                case getCode('INVALID_TAGS')     : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
                case getCode('MORE_POINTS')      : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
@@ -2692,7 +2691,7 @@ function getMessageFromErrorCode ($code) {
 
                        // Load timestamp from last order
                        list($timestamp) = SQL_FETCHROW($result);
-                       $timestamp = generateDateTime($timestamp, '1');
+                       $timestamp = generateDateTime($timestamp, 1);
 
                        // Free memory
                        SQL_FREERESULT($result);
@@ -2829,7 +2828,7 @@ function isUrlValidSimple ($url) {
                        // @TODO Are these convertions still required?
                        $pat = str_replace('.', "&#92;&#46;", $pat);
                        $pat = str_replace('@', "&#92;&#64;", $pat);
-                       //* DEBUG: */ outputHtml($key."=&nbsp;" . $pat . "<br />");
+                       //* DEBUG: */ outputHtml($key."=&nbsp;" . $pat . '<br />');
                } // END - if
 
                // Check if expression matches
@@ -2919,8 +2918,8 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
        return false;
 }
 // Send notification to admin
-function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
-       if (getExtensionVersion('admins') >= '0.4.1') {
+function sendAdminNotification ($subject, $templateName, $content=array(), $userid = 0) {
+       if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
                // Send new way
                sendAdminsEmails($subject, $templateName, $content, $userid);
        } else {
@@ -2939,7 +2938,7 @@ function logDebugMessage ($funcFile, $line, $message, $force=true) {
 
                // Log this message away, we better don't call app_die() here to prevent an endless loop
                $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
-               fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
+               fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
                fclose($fp);
        } // END - if
 }
@@ -2980,6 +2979,7 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
 // Converts timestamp selections into a timestamp
 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
        // Init test variable
+       $skip  = false;
        $test2 = '';
 
        // Get last three chars
@@ -2992,21 +2992,20 @@ function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
                if ((isset($postData[$test.'_ye'])) && (isset($postData[$test.'_mo'])) && (isset($postData[$test.'_we'])) && (isset($postData[$test.'_da'])) && (isset($postData[$test.'_ho'])) && (isset($postData[$test.'_mi'])) && (isset($postData[$test.'_se'])) && ($test != $test2)) {
                        // Generate timestamp
                        $postData[$test] = createTimestampFromSelections($test, $postData);
-                       $DATA[] = sprintf("%s='%s'", $test, $postData[$test]);
+                       $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
+                       $GLOBALS['skip_config'][$test] = true;
 
                        // Remove data from array
                        foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
-                               unset($postData[$test.'_' . $rem]);
+                               unset($postData[$test . '_' . $rem]);
                        } // END - foreach
 
                        // Skip adding
-                       unset($id); $skip = true; $test2 = $test;
+                       unset($id);
+                       $skip = true;
+                       $test2 = $test;
                } // END - if
-       } else {
-               // Process this entry
-               $skip = false;
-               $test2 = '';
-       }
+       } // END - if
 }
 
 // Reverts the german decimal comma into Computer decimal dot
@@ -3047,7 +3046,7 @@ function handleLoginFailtures ($accessLevel) {
                        //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
                        $content = array(
                                'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
-                               'last_failure'   => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), '2')
+                               'last_failure'   => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
                        );
 
                        // Load template
@@ -3155,8 +3154,8 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
 
 // Determines referal id and sets it
 function determineReferalId () {
-       // Skip this in non-html-mode
-       if (getOutputMode() != '0') return false;
+       // Skip this in non-html-mode and outside ref.php
+       if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
 
        // Check if refid is set
        if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
@@ -3183,12 +3182,30 @@ function determineReferalId () {
                // Set default refid as refid in URL
                $GLOBALS['refid'] = getConfig('def_refid');
        } else {
-               // No default ID when sql_patches is not installed or none set
+               // No default id when sql_patches is not installed or none set
                $GLOBALS['refid'] = 0;
        }
 
        // Set cookie when default refid > 0
-       if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
+       if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == 0) && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
+               // Default is not found
+               $found = false;
+
+               // Do we have nickname or userid set?
+               if (isNicknameUsed($GLOBALS['refid'])) {
+                       // Nickname in URL, so load the id
+                       $found = fetchUserData($GLOBALS['refid'], 'nickname');
+               } elseif ($GLOBALS['refid'] > 0) {
+                       // Direct userid entered
+                       $found = fetchUserData($GLOBALS['refid']);
+               }
+
+               // Is the record valid?
+               if (($found === false) || (!isUserDataValid())) {
+                       // No, then reset referal id
+                       $GLOBALS['refid'] = getConfig('def_refid');
+               } // END - if
+
                // Set cookie
                setSession('refid', $GLOBALS['refid']);
        } // END - if
@@ -3225,6 +3242,10 @@ function shutdown () {
 
 // Setter for userid
 function setUserId ($userid) {
+       // We should not set userid to zero
+       if ($userid == 0) debug_report_bug('Userid should not be set zero.');
+
+       // Set it secured
        $GLOBALS['userid'] = bigintval($userid);
 }
 
@@ -3377,7 +3398,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
                // Exclude '.', '..' and entries in $excludeArray automatically
                if (in_array($baseFile, $excludeArray, true))  {
                        // Exclude them
-                       //* DEBUG: */ outputHtml('excluded=' . $baseFile . "<br />");
+                       //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
                        continue;
                } // END - if
 
@@ -3391,9 +3412,9 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $ad
                // Check if the base filename matches an exclusion pattern and if the pattern is not empty
                if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
                        // These Lines are only for debugging!!
-                       //* DEBUG: */ outputHtml('baseDir:' . $baseDir . "<br />");
-                       //* DEBUG: */ outputHtml('baseFile:' . $baseFile . "<br />");
-                       //* DEBUG: */ outputHtml('FQFN:' . $FQFN . "<br />");
+                       //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
+                       //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
+                       //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
 
                        // Exclude this one
                        continue;
@@ -3476,8 +3497,25 @@ function mapModuleToTable ($moduleName) {
 
 // Add SQL debug data to array for later output
 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
-       // Don't execute anything here if we don't need
-       if (getConfig('display_debug_sqls') != 'Y') return;
+       // Already executed?
+       if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
+               // Then abort here, we don't need to profile a query twice
+               return;
+       } // END - if
+
+       // Remeber this as profiled (or not, but we don't care here)
+       $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
+
+       // Do we have cache?
+       if (!isset($GLOBALS['debug_sql_available'])) {
+               // Check it and cache it in $GLOBALS
+               $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
+       } // END - if
+       
+       // Don't execute anything here if we don't need or ext-other is missing
+       if ($GLOBALS['debug_sql_available'] === false) {
+               return;
+       } // END - if
 
        // Generate record
        $record = array(
@@ -3502,7 +3540,7 @@ function initCacheInstance () {
        $GLOBALS['cache_instance'] = new CacheSystem();
        if ($GLOBALS['cache_instance']->getStatus() != 'done') {
                // Failed to initialize cache sustem
-               addFatalMessage(__FILE__, __LINE__, "(<font color=\"#0000aa\">".__LINE__."</font>): ".getMessage('CACHE_CANNOT_INITIALIZE'));
+               addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
        } // END - if
 }
 
@@ -3521,111 +3559,87 @@ function getMessageFromIndexedArray ($message, $pos, $array) {
        return $ret;
 }
 
-// Handles fatal errors
-function handleFatalErrors () {
-       // Do we have errors to handle and right output mode?
-       if ((getTotalFatalErrors() == 0) || (getOutputMode() != 0)) {
-               // Abort executing here
-               return false;
-       } // END - if
-
-       // Set content type
-       setContentType('text/html');
-
-       // Load config here
-       loadIncludeOnce('inc/load_config.php');
-
-       // Set unset variable
-       if (empty($check)) $check = '';
-
-       // Default is none
-       $content = '';
-
-       // Installation phase or regular mode?
-       if ((isInstallationPhase())) {
-               // While we are installing ouput other header than while it is installed... :-)
-               $OUT = '';
-               foreach (getFatalArray() as $key => $value) {
-                       // Prepare content for the template
-                       $content = array(
-                               'key'   => ($key + 1),
-                               'value' => $value
-                       );
-
-                       // Load row template
-                       $OUT .= loadTemplate('install_fatal_row', true, $content);
-               }
-
-               // Load main template
-               $content = loadTemplate('install_fatal_table', true, $OUT);
-       } elseif (isInstalled()) {
-               // Display all runtime fatal errors
-               $OUT = '';
-               foreach (getFatalArray() as $key => $value) {
-                       // Prepare content for the template
-                       $content = array(
-                               'key'   => ($key + 1),
-                               'value' => $value
-                       );
+// Print code with line numbers
+function linenumberCode ($code)    {
+       if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
+       $count_lines = count($codeE);
 
-                       // Load row template
-                       $OUT .= loadTemplate('runtime_fatal_row', true, $content);
+       $r = 'Line | Code:<br />';
+       foreach($codeE as $line => $c) {
+               $r .= '<div class="line"><span class="linenum">';
+               if ($count_lines == 1) {
+                       $r .= 1;
+               } else {
+                       $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
                }
+               $r .= '</span>|';
 
-               // Load main template
-               $content = loadTemplate('runtime_fatal_table', true, $OUT);
+               // Add code
+               $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
        }
 
-       // Message to regular users (non-admin)
-       $CORR = getMessage('FATAL_REPORT_ERRORS');
-
-       // PHP warnings fixed
-       if ($check == 'done') {
-               if (isAdmin()) $CORR = getMessage('FATAL_CORRECT_ERRORS');
-       } // END - if
+       return '<div class="code">' . $r . '</div>';
+}
 
-       // Remember all in array
-       $content = array(
-               'rows' => $content,
-               'corr' => $CORR
-       );
+// Convert ';' to ', ' for e.g. receiver list
+function convertReceivers ($old) {
+       return str_replace(';', ', ', $old);
+}
 
-       // Load footer
-       loadIncludeOnce('inc/header.php');
+// Determines the right page title
+function determinePageTitle () {
+       // Config and database connection valid?
+       if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+               // Init title
+               $TITLE = '';
 
-       // Load main template
-       loadTemplate('fatal_errors', false, $content);
+               // Title decoration enabled?
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
 
-       // Delete all to prevent double-display
-       initFatalMessages();
+               // Do we have some extra title?
+               if (isExtraTitleSet()) {
+                       // Then prepent it
+                       $TITLE .= getExtraTitle() . ' by ';
+               } // END - if
 
-       // Load footer
-       loadIncludeOnce('inc/footer.php');
+               // Add main title
+               $TITLE .= getConfig('MAIN_TITLE');
 
-       // Abort here
-       shutdown();
-}
-
-// Print code with line numbers
-function linenumberCode ($code)    {
-       if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
-       $count_lines = count($codeE);
+               // Add title of module? (middle decoration will also be added!)
+               if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
+                       $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
+               } // END - if
 
-       $r = "Line | Code:<br />";
-       foreach($codeE as $line => $c) {
-               $r .= "<div class=\"line\"><span class=\"linenum\">";
-               if ($count_lines == 1) {
-                       $r .= '1';
-               } else {
-                       $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
-               }
-               $r .= "</span>|";
+               // Add title from what file
+               $mode = '';
+               if (getModule() == 'login') $mode = 'member';
+               elseif (getModule() == 'index') $mode = 'guest';
+               if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
+
+               // Add title decorations? (right)
+               if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
+
+               // Remember title in constant for the template
+               $pageTitle = $TITLE;
+       } elseif ((isInstalled()) && (isAdminRegistered())) {
+               // Installed, admin registered but no ext-sql_patches
+               $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
+       } elseif ((isInstalled()) && (!isAdminRegistered())) {
+               // Installed but no admin registered
+               $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
+       } elseif ((!isInstalled()) || (!isAdminRegistered())) {
+               // Installation mode
+               $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
+       } else {
+               // Configuration not found!
+               $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
 
-               // Add code
-               $r .= "<span class=\"linetext\">" . htmlentities($c) . "</span></div>";
+               // Do not add the fatal message in installation mode
+               if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
        }
 
-       return "<div class=\"code\">" . $r . "</div>\n";
+       // Return title
+       return $pageTitle;
 }
 
 //////////////////////////////////////////////////
@@ -3641,5 +3655,29 @@ if (!function_exists('html_entity_decode')) {
        }
 } // END - if
 
+if (!function_exists('http_build_query')) {
+       // Taken from documentation on www.php.net, credits to Marco K. (Germany)
+       function http_build_query($data, $prefix='', $sep='', $key='') {
+               $ret = array();
+               foreach ((array)$data as $k => $v) {
+                       if (is_int($k) && $prefix != null) {
+                               $k = urlencode($prefix . $k);
+                       } // END - if
+
+                       if ((!empty($key)) || ($key === 0))  $k = $key.'['.urlencode($k).']';
+
+                       if (is_array($v) || is_object($v)) {
+                               array_push($ret, http_build_query($v, '', $sep, $k));
+                       } else {
+                               array_push($ret, $k.'='.urlencode($v));
+                       }
+               } // END - foreach
+
+               if (empty($sep)) $sep = ini_get('arg_separator.output');
+
+               return implode($sep, $ret);
+       }
+}// // END - if
+
 // [EOF]
 ?>