]> git.mxchange.org Git - mailer.git/blobdiff - inc/functions.php
Constants rewritten (internal TODO)
[mailer.git] / inc / functions.php
index 10b4d02d329c05dc548ad0e5d24520cf9cafd306..361b71180b06a5c4ac1e1adf9bb2fa1fb5e276fd 100644 (file)
@@ -44,7 +44,11 @@ if (!defined('__SECURITY')) {
 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
 function OUTPUT_HTML ($HTML, $newLine = true) {
        // Some global variables
-       global $OUTPUT;
+       global $OUTPUT, $username;
+
+       // Prepare IP number and User Agent
+       $REMOTE_ADDR     = detectRemoteAddr();
+       $HTTP_USER_AGENT = detectUserAgent();
 
        // Do we have HTML-Code here?
        if (!empty($HTML)) {
@@ -58,7 +62,7 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
                                        outputRawCode($HTML);
 
                                        // That's why you don't need any \n at the end of your HTML code... :-)
-                                       if ($newLine) echo "\n";
+                                       if ($newLine) print("\n");
                                } else {
                                        // Render mode for old or lame servers...
                                        $OUTPUT .= $HTML;
@@ -74,22 +78,22 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
 
                                // The same as above... ^
                                outputRawCode($HTML);
-                               if ($newLine) echo "\n";
+                               if ($newLine) print("\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--}");
+                               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?
                if (headers_sent()) {
                        // Log this error
-                       DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
+                       DEBUG_LOG(__FUNCTION__, __LINE__, 'Headers already sent! We need debug backtrace here.');
 
                        // Trigger an user error
-                       debug_report_bug("Headers are already sent!");
+                       debug_report_bug('Headers are already sent!');
                } // END - if
 
                // Output cached HTML code
@@ -120,7 +124,11 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
 
                // Compile and run finished rendered HTML code
                while (strpos($OUTPUT, '{!') > 0) {
+                       // Replace _MYSQL_PREFIX
+                       $OUTPUT = str_replace('{!_MYSQL_PREFIX!}', getConfig('_MYSQL_PREFIX'), $OUTPUT);
+
                        // Prepare the content and eval() it...
+                       $content = array();
                        $newContent = '';
                        $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
                        eval($eval);
@@ -128,7 +136,7 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
                        // Was that eval okay?
                        if (empty($newContent)) {
                                // Something went wrong!
-                               app_die(__FUNCTION__, __LINE__, "Evaluation error:<pre>".htmlentities($eval)."</pre>");
+                               app_die(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . htmlentities($eval) . '</pre>');
                        } // END - if
                        $OUTPUT = $newContent;
                } // END - while
@@ -155,7 +163,7 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
 // Output the raw HTML code
 function outputRawCode ($HTML) {
        // Output stripped HTML code to avoid broken JavaScript code, etc.
-       echo stripslashes(stripslashes($HTML));
+       print(stripslashes(stripslashes($HTML)));
 
        // Flush the output if only constant('_OB_CACHING') is not 'on'
        if (constant('_OB_CACHING') != 'on') {
@@ -211,31 +219,33 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
        // @TODO Remove this sanity-check if all is fine
        if (!is_bool($return)) debug_report_bug('return is not bool (' . gettype($return) . ')');
 
+       // Prepare IP number and User Agent
+       $REMOTE_ADDR     = detectRemoteAddr();
+       $HTTP_USER_AGENT = detectUserAgent();
+
        // Add more variables which you want to use in your template files
        global $DATA, $username;
 
-       // Get whole config array
-       $_CONFIG = getConfigArray();
-
        // Make all template names lowercase
        $template = strtolower($template);
 
        // Count the template load
        incrementConfigEntry('num_templates');
 
-       // Prepare IP number and User Agent
-       $REMOTE_ADDR     = detectRemoteAddr();
-       if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
-       $HTTP_USER_AGENT = detectUserAgent();
-
        // Init some data
        $ret = '';
        if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
 
+       // Generate date/time string
+       $date_time = generateDateTime(time(), '1');
+
+       // Is content an array
+       if (is_array($content)) $content['date_time'] = $date_time;
+
        // @DEPRECATED Try to rewrite the if() condition
        if ($template == 'member_support_form') {
                // Support request of a member
-               $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
+               $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?
@@ -247,24 +257,21 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
                        $content['gender'] = translateGender($content['gender']);
                } else {
                        // @DEPRECATED
-                       // @TODO Fine all templates which are using these direct variables and rewrite them.
+                       // @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);
-                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
+                       DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array [%s], template=%s.", gettype($content), $template));
                }
 
                // Free result
                SQL_FREERESULT($result);
        } // END - if
 
-       // Generate date/time string
-       $date_time = generateDateTime(time(), '1');
-
        // Base directory
-       $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
+       $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
        $mode = '';
 
        // Check for admin/guest/member templates
@@ -286,13 +293,16 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
        } elseif (strpos($template, 'la_') > -1) {
                // 'Logical-area' template found
                $mode = 'la/';
+       } elseif (strpos($template, 'js_') > -1) {
+               // JavaScript template found
+               $mode = 'js/';
        } else {
                // Test for extension
                $test = substr($template, 0, strpos($template, '_'));
                if (EXT_IS_ACTIVE($test)) {
                        // Set extra path to extension's name
-                       $mode = $test.'/';
-               }
+                       $mode = $test . '/';
+               } // END - if
        }
 
        ////////////////////////
@@ -333,16 +343,23 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
                // Do we have to compile the code?
                $ret = '';
                if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
-                       // Okay, compile it!
-                       $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
-                       eval($tmpl_file);
+                       // Compile it
+                       $eval = "\$ret = \"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
+                       eval($eval);
+                       // NEW WAY: $ret = str_replace("\$content", "\$GLOBALS[compile][".$template."]", $tmpl_file);
+                       // NEW WAY: $ret = str_replace("\$DATA", "\$GLOBALS[data][".$template."]", $ret);
+                       // NEW WAY: $GLOBALS['compile'][$template] = $content;
+                       // NEW WAY: $GLOBALS['data'][$template] = $DATA;
                } else {
                        // Simply return loaded code
                        $ret = $tmpl_file;
                }
 
-               // Add surrounding HTML comments to help finding bugs faster
-               $ret = "<!-- Template " . $template . " - Start -->\n" . $ret . "<!-- Template " . $template . " - End -->\n";
+               // Normal HTML output?
+               if ($GLOBALS['output_mode'] == 0) {
+                       // Add surrounding HTML comments to help finding bugs faster
+                       $ret = "<!-- Template " . $template . " - Start -->\n" . $ret . "<!-- Template " . $template . " - End -->\n";
+               } // END - if
        } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
                // Only admins shall see this warning or when installation mode is active
                $ret = "<br /><span class=\"guest_failed\">{--TEMPLATE_404--}</span><br />
@@ -377,22 +394,24 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
 
 // Send mail out to an email address
 function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
+       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />");
 
        // Compile subject line (for POINTS constant etc.)
        $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
        eval($eval);
 
        // Set from header
-       if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
+       if ((!eregi('@', $toEmail)) && ($toEmail > 0)) {
                // Value detected, is the message extension installed?
-               if (EXT_IS_ACTIVE("msg")) {
+               // @TODO Extension 'msg' does not exist
+               if (EXT_IS_ACTIVE('msg')) {
                        ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
                        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: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
+                       $result_email = SQL_QUERY_ESC("SELECT `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
+                               array(bigintval($toEmail)), __FUNCTION__, __LINE__);
+                       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />");
 
                        // Does the user exist?
                        if (SQL_NUMROWS($result_email)) {
@@ -400,7 +419,7 @@ function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '')
                                list($toEmail) = SQL_FETCHROW($result_email);
                        } else {
                                // Set webmaster
-                               $toEmail = constant('WEBMASTER');
+                               $toEmail = getConfig('WEBMASTER');
                        }
 
                        // Free result
@@ -408,9 +427,9 @@ function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '')
                }
        } elseif ($toEmail == '0') {
                // Is the webmaster!
-               $toEmail = constant('WEBMASTER');
+               $toEmail = getConfig('WEBMASTER');
        }
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
+       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />");
 
        // Check for PHPMailer or debug-mode
        if (!checkPhpMailerUsage()) {
@@ -458,7 +477,7 @@ Message : " . $message."
                sendRawEmail($toEmail, $subject, $message, $mailHeader);
        } elseif ($HTML == 'N') {
                // Problem found!
-               sendRawEmail(constant('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
+               sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
        }
 }
 
@@ -479,7 +498,7 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
 
                // get new instance
                $mail = new PHPMailer();
-               $mail->PluginDir  = sprintf("%sinc/phpmailer/", constant('PATH'));
+               $mail->PluginDir  = sprintf("%sinc/phpmailer/", getConfig('PATH'));
 
                $mail->IsSMTP();
                $mail->SMTPAuth   = true;
@@ -488,11 +507,11 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
                $mail->Username   = getConfig('SMTP_USER');
                $mail->Password   = getConfig('SMTP_PASSWORD');
                if (empty($from)) {
-                       $mail->From = constant('WEBMASTER');
+                       $mail->From = getConfig('WEBMASTER');
                } else {
                        $mail->From = $from;
                }
-               $mail->FromName   = constant('MAIN_TITLE');
+               $mail->FromName   = getConfig('MAIN_TITLE');
                $mail->Subject    = $subject;
                if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($message) != $message)) {
                        $mail->Body       = $message;
@@ -503,9 +522,9 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
                        $mail->Body       = decodeEntities($message);
                }
                $mail->AddAddress($toEmail, '');
-               $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
-               $mail->AddCustomHeader('Errors-To:' . constant('WEBMASTER'));
-               $mail->AddCustomHeader('X-Loop:' . constant('WEBMASTER'));
+               $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
+               $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
+               $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
                $mail->Send();
        } else {
                // Use legacy mail() command
@@ -699,7 +718,7 @@ function translateUserStatus ($status) {
 // Generates an URL for the dereferer
 function DEREFERER ($URL) {
        // Don't de-refer our own links!
-       if (substr($URL, 0, strlen(constant('URL'))) != constant('URL')) {
+       if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
                // De-refer this link
                $URL = 'modules.php?module=loader&amp;url=' . encodeString(compileUriCode($URL));
        } // END - if
@@ -711,7 +730,7 @@ function DEREFERER ($URL) {
 // Generates an URL for the frametester
 function FRAMETESTER ($URL) {
        // Prepare frametester URL
-       $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&amp;url=%s",
+       $frametesterUrl = sprintf("{?URL?}/modules.php?module=frametester&amp;url=%s",
        encodeString(compileUriCode($URL))
        );
        return $frametesterUrl;
@@ -730,7 +749,7 @@ function countSelection ($array) {
 
 // Generate XHTML code for the CAPTCHA
 function generateCaptchaCode ($code, $type, $DATA, $uid) {
-       return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '" />';
+       return '<IMG border="0" alt="Code" src="{?URL?}/mailid_top.php?uid=' . $uid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '" />';
 }
 
 // Loads an email template and compiles it
@@ -751,7 +770,7 @@ function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
        $HTTP_USER_AGENT = detectUserAgent();
 
        // Default admin
-       $ADMIN = constant('MAIN_TITLE');
+       $ADMIN = getConfig('MAIN_TITLE');
 
        // Is the admin logged in?
        if (IS_ADMIN()) {
@@ -763,7 +782,7 @@ function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
        } // END - if
 
        // Neutral email address is default
-       $email = constant('WEBMASTER');
+       $email = getConfig('WEBMASTER');
 
        // Expiration in a nice output format
        // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
@@ -782,25 +801,25 @@ function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
        } // END - if
 
        // Load user's data
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
+       //* DEBUG: */ OUTPUT_HTML(__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 (EXT_IS_ACTIVE('nickname')) {
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
+                       //* DEBUG: */ OUTPUT_HTML(__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__);
+                       $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__);
                } else {
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
+                       //* DEBUG: */ OUTPUT_HTML(__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__);
+                       $result = SQL_QUERY_ESC("SELECT `surname`, `family`, `gender`, `email` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
+                               array(bigintval($UID)), __FUNCTION__, __LINE__);
                }
 
                // Fetch and merge data
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
+               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />");
                $content = merge_array($content, SQL_FETCHARRAY($result));
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
+               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />");
 
                // Free result
                SQL_FREERESULT($result);
@@ -816,7 +835,7 @@ function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
        $DATA['email'] = $email;
 
        // Base directory
-       $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
+       $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
 
        // Check for admin/guest/member templates
        if (strpos($template, 'admin_') > -1) {
@@ -907,7 +926,7 @@ function redirectToUrl ($URL) {
        // Check if http(s):// is there
        if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
                // Make all URLs full-qualified
-               $URL = constant('URL') . '/' . $URL;
+               $URL = getConfig('URL') . '/' . $URL;
        } // END - if
 
        // Three different debug ways...
@@ -919,7 +938,7 @@ function redirectToUrl ($URL) {
        $rel = ' rel="external"';
 
        // Do we have internal or external URL?
-       if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
+       if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
                // Own (=internal) URL
                $rel = '';
        } // END - if
@@ -987,11 +1006,11 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
        if ($constants === true) {
                // BEFORE 0.2.1 : Language and data constants
                // WITH 0.2.1+  : Only language constants
-               $code = str_replace('{--','".', str_replace('--}','."', $code));
+               $code = str_replace('{--', "\".getMessage('", str_replace('--}', "').\"", $code));
 
                // BEFORE 0.2.1 : Not used
                // WITH 0.2.1+  : Data constants
-               $code = str_replace('{!','".', str_replace("!}", '."', $code));
+               $code = str_replace('{!', "\".constant('", str_replace("!}", "').\"", $code));
        } // END - if
 
        // Compile QUOT and other non-HTML codes
@@ -1004,7 +1023,7 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
        if ($simple) $code = str_replace("'", '{QUOT}', $code);
 
        // Find $content[bla][blub] entries
-       preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
+       preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
 
        // Are some matches found?
        if ((count($matches) > 0) && (count($matches[0]) > 0)) {
@@ -1020,35 +1039,50 @@ function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true)
                                $test = substr($found, 0, strlen($match));
 
                                // Does this entry exist?
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
+                               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />");
                                if ($test == $match) {
                                        // Match found!
-                                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
+                                       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />");
                                        $fuzzyFound = true;
                                        break;
                                } // END - if
                        } // END - foreach
 
                        // Skip this entry?
-                       if ($fuzzyFound) continue;
+                       if ($fuzzyFound === true) continue;
 
                        // Take all string elements
                        if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
                                // Replace it in the code
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
-                               $newMatch = str_replace("[" . $matches[4][$key]."]", "['" . $matches[4][$key]."']", $match);
+                               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />");
+                               $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
                                $code = str_replace($match, "\"." . $newMatch.".\"", $code);
-                               $matchesFound[$key."_" . $matches[4][$key]] = 1;
+                               $matchesFound[$key . '_' . $matches[4][$key]] = 1;
                                $matchesFound[$match] = 1;
                        } elseif (!isset($matchesFound[$match])) {
                                // Not yet replaced!
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
+                               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />");
                                $code = str_replace($match, "\"." . $match.".\"", $code);
                                $matchesFound[$match] = 1;
                        }
                } // END - foreach
        } // END - if
 
+       // Compile {?some_var?} to getConfig('some_var')
+       preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
+
+       // Some entries found?
+       if ((count($matches) > 0) && (count($matches[0]) > 0)) {
+               // Replace all matches
+               foreach ($matches[0] as $key => $match) {
+                       // Replace it
+                       //* DEBUG: */ if ($key == 0) { print '<pre>'; debug_print_backtrace(); print '</pre>'; }
+                       //* DEBUG: */ print htmlentities($match).'['.strlen($match).']='.$matches[1][$key].'='.getConfig($matches[1][$key]).' (key='.$key.',len='.strlen($code).')<br />';
+                       $code = str_replace($match, getConfig($matches[1][$key]), $code);
+                       //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die('<pre>'.htmlentities($code).'</pre>');
+               } // END - foreach
+       } // END - if
+
        // Return compiled code
        return $code;
 }
@@ -1223,18 +1257,14 @@ function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
 // Optional   : $DATA
 //
 function generateRandomCode ($length, $code, $uid, $DATA = '') {
-       // Fix missing _MAX constant
-       // @TODO Rewrite this unnice code
-       if (!defined('_MAX')) define('_MAX', 15235);
-
        // Build server string
-       $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH').'inc/databases.php');
+       $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(getConfig('PATH').'inc/databases.php');
 
        // Build key string
        $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
        if (isConfigEntrySet('secret_key'))  $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
        if (isConfigEntrySet('file_hash'))   $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
-       $keys .= getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
+       $keys .= getConfig('ENCRYPT_SEPERATOR') . date("d-m-Y (l-F-T)", getConfig('patch_ctime'));
        if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
 
        // Build string from misc data
@@ -1255,13 +1285,13 @@ function generateRandomCode ($length, $code, $uid, $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'));
 
                // Create number from hash
-               $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
+               $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
        } else {
                // Generate hash with "hash of site key" from modula of number with the prime number and other data
                $saltedHash = generateHash(($a % getConfig('_PRIME')).getConfig('ENCRYPT_SEPERATOR') . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, 8));
 
                // Create number from hash
-               $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
+               $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
        }
 
        // At least 10 numbers shall be secure enought!
@@ -1286,9 +1316,9 @@ function bigintval ($num, $castValue = true) {
 
        // Has the whole value changed?
        // @TODO Remove this if() block if all is working fine
-       if ("" . $ret."" != '' . $num."") {
+       if ('' . $ret . '' != '' . $num . '') {
                // Log the values
-               debug_report_bug("{$ret}<>{$num}");
+               //debug_report_bug("{$ret}<>{$num}");
        } // END - if
 
        // Return result
@@ -1302,11 +1332,11 @@ function GENERATE_IMAGE ($img_code, $headerSent=true) {
                return;
        } elseif (!$headerSent) {
                // Return in an HTML code code
-               return "<img src=\"{!URL!}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
+               return "<img src=\"{?URL?}/img.php?code=" . $img_code."\" alt=\"Image\" />\n";
        }
 
        // Load image
-       $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
+       $img = sprintf("%s/theme/%s/images/code_bg.%s", getConfig('PATH'), getCurrentTheme(), getConfig('img_type'));
        if (isFileReadable($img)) {
                // Switch image type
                switch (getConfig('img_type'))
@@ -1362,25 +1392,25 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
 
        // First of all years...
        $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
-       //* DEBUG: */ print("Y={$Y}<br />\n");
+       //* DEBUG: */ print("Y={$Y}<br />");
        // Next months...
        $M = abs(floor($timestamp / 2628000 - $Y * 12));
-       //* DEBUG: */ print("M={$M}<br />\n");
+       //* DEBUG: */ print("M={$M}<br />");
        // Next weeks
        $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
-       //* DEBUG: */ print("W={$W}<br />\n");
+       //* DEBUG: */ print("W={$W}<br />");
        // Next days...
        $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
-       //* DEBUG: */ print("D={$D}<br />\n");
+       //* DEBUG: */ print("D={$D}<br />");
        // Next hours...
        $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
-       //* DEBUG: */ print("h={$h}<br />\n");
+       //* DEBUG: */ print("h={$h}<br />");
        // Next minutes..
        $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
-       //* DEBUG: */ print("m={$m}<br />\n");
+       //* DEBUG: */ print("m={$m}<br />");
        // And at last seconds...
        $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
-       //* DEBUG: */ print("s={$s}<br />\n");
+       //* DEBUG: */ print("s={$s}<br />");
 
        // Is seconds zero and time is < 60 seconds?
        if (($s == 0) && ($timestamp < 60)) {
@@ -1412,7 +1442,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
                }
 
-               if (ereg("M", $display) || (empty($display))) {
+               if (ereg('M', $display) || (empty($display))) {
                        $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
                }
 
@@ -1452,7 +1482,7 @@ function createTimeSelections ($timestamp, $prefix = '', $display = '', $align =
                        $OUT .= "<INPUT type=\"hidden\" name=\"" . $prefix."_ye\" value=\"0\" />\n";
                }
 
-               if (ereg("M", $display) || (empty($display))) {
+               if (ereg('M', $display) || (empty($display))) {
                        // Generate month selection
                        $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"" . $prefix."_mo\" size=\"1\">\n";
                        for ($idx = 0; $idx <= 11; $idx++)
@@ -1674,7 +1704,7 @@ function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
                        $NAV .= "<strong>-";
                } else {
                        // Open anchor tag and add base URL
-                       $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&amp;what=" . getWhat()."&amp;page=" . $page."&amp;offset=" . $offset;
+                       $NAV .= "<a href=\"{?URL?}/modules.php?module=admin&amp;what=" . getWhat()."&amp;page=" . $page."&amp;offset=" . $offset;
 
                        // Add userid when we shall show all mails from a single member
                        if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&amp;uid=".bigintval(REQUEST_GET('uid'));
@@ -1718,7 +1748,7 @@ function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
 // Extract host from script name
 function extractHostnameFromUrl (&$script) {
        // Use default SERVER_URL by default... ;) So?
-       $url = constant('SERVER_URL');
+       $url = getConfig('SERVER_URL');
 
        // Is this URL valid?
        if (substr($script, 0, 7) == 'http://') {
@@ -1734,7 +1764,7 @@ function extractHostnameFromUrl (&$script) {
        if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
 
        // Generate relative URL
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
+       //* 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));
@@ -1743,7 +1773,7 @@ function extractHostnameFromUrl (&$script) {
                $script = substr($script, (strlen($url) + 8));
        }
 
-       //* DEBUG: */ print("SCRIPT=" . $script."<br />\n");
+       //* DEBUG: */ print("SCRIPT=" . $script."<br />");
        if (substr($script, 0, 1) == '/') $script = substr($script, 1);
 
        // Return host name
@@ -1761,11 +1791,11 @@ function sendGetRequest ($script) {
        // Generate GET request header
        $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') . getConfig('HTTP_EOL');
+       $request .= "Referer: " . getConfig('URL') . "/admin.php" . getConfig('HTTP_EOL');
+       if (isConfigEntrySet('FULL_VERSION')) {
+               $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
        } else {
-               $request .= "User-Agent: " . constant('TITLE') . "/?.?.?" . getConfig('HTTP_EOL');
+               $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
        }
        $request .= "Content-Type: text/plain" . getConfig('HTTP_EOL');
        $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
@@ -1799,8 +1829,8 @@ function sendPostRequest ($script, $postData) {
        // Generate POST request header
        $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 .= "Referer: " . getConfig('URL') . "/admin.php" . getConfig('HTTP_EOL');
+       $request .= "User-Agent: " . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
        $request .= "Content-type: application/x-www-form-urlencoded" . getConfig('HTTP_EOL');
        $request .= "Content-length: " . strlen($data) . getConfig('HTTP_EOL');
        $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
@@ -1832,7 +1862,7 @@ function sendRawRequest ($host, $request) {
        } // END - if
 
        // Open connection
-       //* DEBUG: */ die("SCRIPT=" . $script."<br />\n");
+       //* DEBUG: */ die("SCRIPT=" . $script."<br />");
        if ($useProxy === true) {
                // Connect to host through proxy connection
                $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
@@ -1943,7 +1973,6 @@ function isEmailValid ($email) {
        $regex = '@^' . $first . '\@' . $domain . '$@iU';
 
        // Return check result
-       // @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);
 }
 
@@ -1951,11 +1980,11 @@ function isEmailValid ($email) {
 function isUrlValid ($URL, $compile=true) {
        // Trim URL a little
        $URL = trim(urldecode($URL));
-       //* DEBUG: */ echo $URL."<br />";
+       //* DEBUG: */ OUTPUT_HTML($URL."<br />");
 
        // Compile some chars out...
        if ($compile === true) $URL = compileUriCode($URL, false, false, false);
-       //* DEBUG: */ echo $URL."<br />";
+       //* DEBUG: */ OUTPUT_HTML($URL."<br />");
 
        // Check for the extension filter
        if (EXT_IS_ACTIVE('filter')) {
@@ -1977,8 +2006,8 @@ function generateMemberAdminActionLinks ($uid, $status = '') {
        $eval = "\$OUT = \"[&nbsp;";
 
        foreach ($TARGETS as $tar) {
-               $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&amp;what=" . $tar."&amp;uid=" . $uid."\\\" title=\\\"{--ADMIN_LINK_";
-               //* DEBUG: */ echo "*" . $tar.'/' . $status."*<br />\n";
+               $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{?URL?}/modules.php?module=admin&amp;what=" . $tar."&amp;uid=" . $uid."\\\" title=\\\"{--ADMIN_LINK_";
+               //* DEBUG: */ OUTPUT_HTML("*" . $tar.'/' . $status."*<br />");
                if (($tar == "lock_user") && ($status == 'LOCKED')) {
                        // Locked accounts shall be unlocked
                        $eval .= "UNLOCK_USER";
@@ -2006,20 +2035,20 @@ function generateMemberAdminActionLinks ($uid, $status = '') {
 }
 
 // Generate an email link
-function generateMemberEmailLink ($email, $table = 'admins') {
+function generateEmailLink ($email, $table = 'admins') {
        // Default email link (INSECURE! Spammer can read this by harvester programs)
        $EMAIL = 'mailto:' . $email;
 
        // Check for several extensions
        if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
                // Create email link for contacting admin in guest area
-               $EMAIL = adminsCreateEmailLink($email);
+               $EMAIL = generateAdminEmailLink($email);
        } 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);
+               $EMAIL = generateUserEmailLink($email, 'admin');
        } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
                // Create email link to contact sponsor within admin area (or like the link above?)
-               $EMAIL = SPONSOR_generateMemberEmailLink($email);
+               $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
        }
 
        // Shall I close the link when there is no admin?
@@ -2049,7 +2078,7 @@ function generateHash ($plainText, $salt = '') {
                $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
 
                // Build key string
-               $keys   = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key').getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash').getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
+               $keys   = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key').getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash').getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig('patch_ctime')).getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
 
                // Additional data
                $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
@@ -2059,19 +2088,19 @@ function generateHash ($plainText, $salt = '') {
 
                // Generate SHA1 sum from modula of number and the prime number
                $sha1 = sha1(($a % getConfig('_PRIME')) . $server.getConfig('ENCRYPT_SEPERATOR') . $keys.getConfig('ENCRYPT_SEPERATOR') . $data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR') . $a);
-               //* DEBUG: */ echo "SHA1=" . $sha1." (".strlen($sha1).")<br />";
+               //* DEBUG: */ OUTPUT_HTML("SHA1=" . $sha1." (".strlen($sha1).")<br />");
                $sha1 = scrambleString($sha1);
-               //* DEBUG: */ echo "Scrambled=" . $sha1." (".strlen($sha1).")<br />";
+               //* DEBUG: */ OUTPUT_HTML("Scrambled=" . $sha1." (".strlen($sha1).")<br />");
                //* DEBUG: */ $sha1b = descrambleString($sha1);
-               //* DEBUG: */ echo "Descrambled=" . $sha1b." (".strlen($sha1b).")<br />";
+               //* DEBUG: */ OUTPUT_HTML("Descrambled=" . $sha1b." (".strlen($sha1b).")<br />");
 
                // Generate the password salt string
                $salt = substr($sha1, 0, getConfig('salt_length'));
-               //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
+               //* DEBUG: */ OUTPUT_HTML($salt." (".strlen($salt).")<br />");
        } else {
                // Use given salt
                $salt = substr($salt, 0, getConfig('salt_length'));
-               //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
+               //* DEBUG: */ OUTPUT_HTML("GIVEN={$salt}<br />");
        }
 
        // Return hash
@@ -2096,7 +2125,7 @@ function scrambleString($str) {
        }
 
        // Scramble string here
-       //* DEBUG: */ echo "***Original=" . $str."***<br />";
+       //* DEBUG: */ OUTPUT_HTML("***Original=" . $str."***<br />");
        for ($idx = 0; $idx < strlen($str); $idx++) {
                // Get char on scrambled position
                $char = substr($str, $scrambleNums[$idx], 1);
@@ -2106,7 +2135,7 @@ function scrambleString($str) {
        } // END - for
 
        // Return scrambled string
-       //* DEBUG: */ echo "***Scrambled=" . $scrambled."***<br />";
+       //* DEBUG: */ OUTPUT_HTML("***Scrambled=" . $scrambled."***<br />");
        return $scrambled;
 }
 
@@ -2122,15 +2151,15 @@ function descrambleString($str) {
        if (count($scrambleNums) != 40) return $str;
 
        // Begin descrambling
-       $orig = str_repeat(" ", 40);
-       //* DEBUG: */ echo "+++Scrambled=" . $str."+++<br />";
+       $orig = str_repeat(' ', 40);
+       //* DEBUG: */ OUTPUT_HTML("+++Scrambled=" . $str."+++<br />");
        for ($idx = 0; $idx < 40; $idx++) {
                $char = substr($str, $idx, 1);
                $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
        } // END - for
 
        // Return scrambled string
-       //* DEBUG: */ echo "+++Original=" . $orig."+++<br />";
+       //* DEBUG: */ OUTPUT_HTML("+++Original=" . $orig."+++<br />");
        return $orig;
 }
 
@@ -2178,19 +2207,19 @@ function generatePassString ($passHash) {
                        }
                        $mod = substr(round($mod), 0, 4);
                        $mod = str_repeat('0', 4-strlen($mod)) . $mod;
-                       //* DEBUG: */ echo "*" . $start.'=' . $mod."*<br />";
+                       //* DEBUG: */ OUTPUT_HTML("*" . $start.'=' . $mod."*<br />");
                        $start += 4;
                        $newHash .= $mod;
                } // END - for
 
                //* DEBUG: */ print($passHash."<br />" . $newHash." (".strlen($newHash).')');
                $ret = generateHash($newHash, getConfig('master_salt'));
-               //* DEBUG: */ print($ret."<br />\n");
+               //* DEBUG: */ print($ret."<br />");
        } else {
                // Hash it simple
-               //* DEBUG: */ echo "--" . $passHash."--<br />\n";
+               //* DEBUG: */ OUTPUT_HTML("--" . $passHash."--<br />");
                $ret = md5($passHash);
-               //* DEBUG: */ echo "++" . $ret."++<br />\n";
+               //* DEBUG: */ OUTPUT_HTML("++" . $ret."++<br />");
        }
 
        // Return result
@@ -2276,14 +2305,14 @@ function isBooleanConstantAndTrue ($constName) { // : Boolean
        // In cache?
        if (isset($GLOBALS['cache_array']['const'][$constName])) {
                // Use cache
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />\n";
+               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
                $res = ($GLOBALS['cache_array']['const'][$constName] === true);
        } else {
                // Check constant
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />\n";
+               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
                if (defined($constName)) {
                        // Found!
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />\n";
+                       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
                        $res = (constant($constName) === true);
                } // END - if
 
@@ -2325,13 +2354,13 @@ function getCurrentTheme() {
                } // END - if
        } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
                // Prepare FQFN for checking
-               $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
+               $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), REQUEST_GET('theme'));
 
                // Installation mode active
                if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
                        // Set cookie from URL data
                        setSession('mxchange_theme', REQUEST_GET('theme'));
-               } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
+               } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
                        // Set cookie from posted data
                        setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
                }
@@ -2420,33 +2449,33 @@ function generateErrorCodeFromUserStatus ($status) {
 // Function to search for the last modifified file
 function searchDirsRecursive ($dir, &$last_changed) {
        // Get dir as array
-       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />\n";
+       //* DEBUG: */ OUTPUT_HTML(__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|\.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";
+       $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
+       $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
+       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />");
 
        // Walk through all entries
        foreach ($ds as $d) {
                // Generate proper FQFN
-               $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
+               $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
 
                // Is it a file and readable?
-               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
+               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
                if (isDirectory($FQFN)) {
                        // $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";
+                       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir."<br />");
                        searchDirsRecursive($newDir, $last_changed);
                } elseif (isFileReadable($FQFN)) {
                        // $FQFN is a filename and no directory
                        $time = filemtime($FQFN);
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />\n";
+                       //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
                        if ($last_changed['time'] < $time) {
                                // This file is newer as the file before
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
+                               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
                                $last_changed['path_name'] = $FQFN;
                                $last_changed['time'] = $time;
                        } // END - if
@@ -2476,9 +2505,12 @@ function getActualVersion ($type = 'Revision') {
                } // END - if
 
                // Is the cache file outdated/invalid?
-               if ($new === true){
+               if ($new === true) {
+                       // Reload the cache file
+                       $GLOBALS['cache_instance']->loadCacheFile('revision');
+
                        // Destroy cache file
-                       $GLOBALS['cache_instance']->destroyCacheFile();
+                       $GLOBALS['cache_instance']->destroyCacheFile(false, true);
 
                        // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
                        unset($GLOBALS['cache_array']['revision']);
@@ -2496,7 +2528,7 @@ function getActualVersion ($type = 'Revision') {
                // Old Version without ext-cache active (deprecated ?)
 
                // FQFN of revision file
-               $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
+               $FQFN = sprintf("%sinc/cache/.revision", getConfig('PATH'));
 
                // 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')) {
@@ -2546,13 +2578,19 @@ function getSearchFor () {
 // @TODO Please describe this function
 function getArrayFromActualVersion () {
        // Init variables
-       $next_dir = ''; // Directory to start with search
+       $next_dir = '';
+
+       // Directory to start with search
        $last_changed = array(
                'path_name' => '',
                'time'      => 0
        );
-       $akt_vers = array(); // Init return array
-       $res = 0; // Init value for counting the founded keywords
+
+       // Init return array
+       $akt_vers = array();
+
+       // Init value for counting the founded keywords
+       $res = 0;
 
        // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
        searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
@@ -2635,7 +2673,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
@@ -2722,7 +2760,7 @@ function generateAdminLink ($aid) {
                        // Is the extension there?
                        if (EXT_IS_ACTIVE('admins')) {
                                // Admin found
-                               $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">" . $login."</a>";
+                               $admin = "<a href=\"".generateEmailLink(getAdminEmail($aid), 'admins')."\">" . $login."</a>";
                        } else {
                                // Extension not found
                                $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
@@ -2738,7 +2776,7 @@ function generateAdminLink ($aid) {
 }
 
 // Compile characters which are allowed in URLs
-function compileUriCode ($code, $simple=true) {
+function compileUriCode ($code, $simple = true) {
        // Compile constants
        if (!$simple) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
 
@@ -2810,7 +2848,7 @@ function isUrlValidSimple ($url) {
                        // @TODO Are these convertions still required?
                        $pat = str_replace('.', "&#92;&#46;", $pat);
                        $pat = str_replace('@', "&#92;&#64;", $pat);
-                       echo $key."=&nbsp;" . $pat . "<br />";
+                       //* DEBUG: */ OUTPUT_HTML($key."=&nbsp;" . $pat . "<br />");
                } // END - if
 
                // Check if expression matches
@@ -2839,12 +2877,12 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
                $tmp = $FQFN . '.tmp';
 
                // Open the source file
-               $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . "<br />\n");
+               $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . '<br />');
 
                // Is the resource valid?
                if (is_resource($fp)) {
                        // Open temporary file
-                       $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . "<br />\n");
+                       $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . '<br />');
 
                        // Is the resource again valid?
                        if (is_resource($fp_tmp)) {
@@ -2861,7 +2899,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
                                                } else {
                                                        $next++;
                                                }
-                                       }
+                                       } // END - if
 
                                        // Write to temp file
                                        fputs($fp_tmp, $line);
@@ -2914,9 +2952,9 @@ function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
                // Remove CRLF
                $message = str_replace("\r", '', str_replace("\n", '', $message));
 
-               // Log this message away
-               $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
-               fwrite($fp, date("d.m.Y|H:i:s", time())."|" . getModule()."|".basename($funcFile)."|" . $line."|".strip_tags($message)."\n");
+               // Log this message away, we better don't call app_die() here to prevent an endless loop
+               $fp = fopen(getConfig('PATH') . 'inc/cache/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 . '|' . strip_tags($message) . "\n");
                fclose($fp);
        } // END - if
 }
@@ -2926,7 +2964,7 @@ function runResetIncludes () {
        // Is the reset set or old sql_patches?
        if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
                // Then abort here
-               DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
+               DEBUG_LOG(__FUNCTION__, __LINE__, 'Cannot run reset! Please report this bug. Thanks');
        } // END - if
 
        // Get more daily reset scripts
@@ -3066,7 +3104,7 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
                // Ignore zero values
                if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
                        // Non-guest has login failures found, get both data and prepare it for template
-                       //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
+                       //* DEBUG: */ OUTPUT_HTML(__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')
@@ -3103,7 +3141,7 @@ function rebuildCacheFiles ($cache, $inc = '') {
                        // Is the include there?
                        if (isIncludeReadable($INC)) {
                                // And rebuild it from scratch
-                               //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
+                               //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
                                loadInclude($INC);
                        } else {
                                // Include not found!
@@ -3121,7 +3159,7 @@ function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
                return false;
        } elseif (!isCacheInstanceValid()) {
                // No cache instance!
-               DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
+               DEBUG_LOG(__FUNCTION__, __LINE__, 'No cache instance found.');
                return false;
        } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
                // Caching disabled (currently experiemental!)
@@ -3187,7 +3225,7 @@ function addNewBonusMail ($data, $mode = '', $output=true) {
                LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
        } else {
                // Debug log
-               DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
+               DEBUG_LOG(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
        }
 }
 
@@ -3209,12 +3247,12 @@ function DETERMINE_REFID () {
        } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
                // Set session refid als global
                $GLOBALS['refid'] = bigintval(getSession('refid'));
-       } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
-               // Set default refid as refid in URL
-               $GLOBALS['refid'] = getConfig(('def_refid'));
        } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
                // Select a random user which has confirmed enougth mails
                $GLOBALS['refid'] = determineRandomReferalId();
+       } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
+               // Set default refid as refid in URL
+               $GLOBALS['refid'] = getConfig('def_refid');
        } else {
                // No default ID when sql_patches is not installed or none set
                $GLOBALS['refid'] = 0;
@@ -3389,6 +3427,113 @@ function generateExtensionInactiveNotInstalledMessage ($ext_name) {
        return $message;
 }
 
+// Reads a directory recursively by default and searches for files not matching
+// an exclusion pattern. You can now keep the exclusion pattern empty for reading
+// a whole directory.
+function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
+       // Add default entries we should exclude
+       $excludeArray[] = '.';
+       $excludeArray[] = '..';
+       $excludeArray[] = '.svn';
+       $excludeArray[] = '.htaccess';
+
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
+       // Init includes
+       $files = array();
+
+       // Open directory
+       $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
+
+       // Read all entries
+       while ($baseFile = readdir($dirPointer)) {
+               // Exclude '.', '..' and entries in $excludeArray automatically
+               if (in_array($baseFile, $excludeArray, true))  {
+                       // Exclude them
+                       //* DEBUG: */ OUTPUT_HTML('excluded=' . $baseFile . "<br />");
+                       continue;
+               } // END - if
+
+               // Construct include filename and FQFN
+               $fileName = $baseDir . '/' . $baseFile;
+               $FQFN = getConfig('PATH') . $fileName;
+
+               // Remove double slashes
+               $FQFN = str_replace('//', '/', $FQFN);
+
+               // 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: */ OUTPUT_HTML('baseDir:' . $baseDir . "<br />");
+                       //* DEBUG: */ OUTPUT_HTML('baseFile:' . $baseFile . "<br />");
+                       //* DEBUG: */ OUTPUT_HTML('FQFN:' . $FQFN . "<br />");
+
+                       // Exclude this one
+                       continue;
+               } // END - if
+
+               // Skip also files with non-matching prefix genericly
+               if (($recursive === true) && (isDirectory($FQFN))) {
+                       // Is a redirectory so read it as well
+                       $files = merge_array($files, getArrayFromDirectory ($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
+
+                       // And skip further processing
+                       continue;
+               } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
+                       // Skip this file
+                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
+                       continue;
+               } elseif (!isFileReadable($FQFN)) {
+                       // Not readable so skip it
+                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
+                       continue;
+               }
+
+               // Is the file a PHP script or other?
+               //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
+               if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
+                       // Is this a valid include file?
+                       if ($extension == '.php') {
+                               // Remove both for extension name
+                               $extName = substr($baseFile, strlen($prefix), -4);
+
+                               // Try to find it
+                               $extId = GET_EXT_ID($extName);
+
+                               // Is the extension valid and active?
+                               if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
+                                       // Then add this file
+                                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
+                                       $files[] = $fileName;
+                               } elseif ($extId == 0) {
+                                       // Add non-extension files as well
+                                       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
+                                       if ($addBaseDir === true) {
+                                               $files[] = $fileName;
+                                       } else {
+                                               $files[] = $baseFile;
+                                       }
+                               }
+                       } else {
+                               // We found .php file but should not search for them, why?
+                               debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
+                       }
+               } else {
+                       // Other, generic file found
+                       $files[] = $fileName;
+               }
+       } // END - while
+
+       // Close directory
+       closedir($dirPointer);
+
+       // Sort array
+       asort($files);
+
+       // Return array with include files
+       //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, '- Left!');
+       return $files;
+}
+
 //////////////////////////////////////////////////
 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
 //////////////////////////////////////////////////