Default refid is always fallback now, or 0 if sql_patches is absend
[mailer.git] / inc / functions.php
index 71538ea79815e23daf5961754171266df50ce86d..5f9e1229ade302b33056d1ada5faeb8d7d17c4b0 100644 (file)
@@ -114,12 +114,15 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
                sendHeader('Connection: Close');
 
                // Extension 'rewrite' installed?
-               if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != '1') && ($GLOBALS['output_mode'] != '-1')) {
+               if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
                        $OUTPUT = rewriteLinksInCode($OUTPUT);
                } // END - if
 
                // 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...
                        $newContent = '';
                        $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
@@ -128,7 +131,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
@@ -137,7 +140,7 @@ function OUTPUT_HTML ($HTML, $newLine = true) {
                outputRawCode($OUTPUT);
        } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
                // Rewrite links when rewrite extension is active
-               if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != '1') && ($GLOBALS['output_mode'] != '-1')) {
+               if ((EXT_IS_ACTIVE('rewrite')) && (getOutputMode() != '1') && (getOutputMode() != '-1')) {
                        $OUTPUT = rewriteLinksInCode($OUTPUT);
                } // END - if
 
@@ -208,6 +211,9 @@ function getTotalFatalErrors () {
 
 // Load a template file and return it's content (only it's name; do not use ' or ")
 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) . ')');
+
        // Add more variables which you want to use in your template files
        global $DATA, $username;
 
@@ -232,7 +238,7 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
        // @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?
@@ -244,13 +250,13 @@ 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
@@ -283,13 +289,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
        }
 
        ////////////////////////
@@ -297,13 +306,13 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
        ////////////////////////
        $FQFN = $basePath . $mode . $template . '.tpl';
 
-       if ((!empty($GLOBALS['what'])) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
+       if ((isWhatSet()) && ((strpos($template, '_header') > 0) || (strpos($template, '_footer') > 0)) && (($mode == 'guest/') || ($mode == 'member/') || ($mode == 'admin/'))) {
                // Select what depended header/footer template file for admin/guest/member area
                $file2 = sprintf("%s%s%s_%s.tpl",
                        $basePath,
                        $mode,
                        $template,
-                       SQL_ESCAPE($GLOBALS['what'])
+                       getWhat()
                );
 
                // Probe for it...
@@ -338,8 +347,11 @@ function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
                        $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 />
@@ -381,14 +393,16 @@ function sendEmail ($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '')
        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__);
+                       $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";
 
                        // Does the user exist?
@@ -511,16 +525,16 @@ function sendRawEmail ($toEmail, $subject, $message, $from) {
 }
 
 // Generate a password in a specified length or use default password length
-function generatePassword ($LEN = 0) {
+function generatePassword ($length = 0) {
        // Auto-fix invalid length of zero
-       if ($LEN == 0) $LEN = getConfig('pass_len');
+       if ($length == 0) $length = getConfig('pass_len');
 
        // Initialize array with all allowed chars
-       $ABC = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/');
+       $ABC = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/,.');
 
        // Start creating password
        $PASS = '';
-       for ($i = 0; $i < $LEN; $i++) {
+       for ($i = 0; $i < $length; $i++) {
                $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
        } // END - for
 
@@ -732,7 +746,10 @@ function generateCaptchaCode ($code, $type, $DATA, $uid) {
 
 // Loads an email template and compiles it
 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
-       global $DATA, $_CONFIG;
+       global $DATA;
+
+       // Our configuration is kept non-global here
+       $_CONFIG = getConfigArray();
 
        // Make sure all template names are lowercase!
        $template = strtolower($template);
@@ -782,13 +799,13 @@ function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
                if (EXT_IS_ACTIVE('nickname')) {
                        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
                        // Load nickname
-                       $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
-                       array(bigintval($UID)), __FUNCTION__, __LINE__);
+                       $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";
                        /// 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
@@ -926,11 +943,11 @@ function redirectToUrl ($URL) {
                clearOutputBuffer();
        } // END - if
 
-       // Secure the URL against bad things such als HTML insertions and so on...
-       $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
-
        // Simple probe for bots/spiders from search engines
        if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
+               // Secure the URL against bad things such als HTML insertions and so on...
+               $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
+
                // Output new location link as anchor
                OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
        } elseif (!headers_sent()) {
@@ -1228,7 +1245,7 @@ function generateRandomCode ($length, $code, $uid, $DATA = '') {
        $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
@@ -1280,9 +1297,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
@@ -1406,7 +1423,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";
                }
 
@@ -1446,7 +1463,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++)
@@ -1668,7 +1685,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=" . $GLOBALS['what']."&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'));
@@ -1937,7 +1954,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);
 }
 
@@ -2000,20 +2016,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?
@@ -2043,7 +2059,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();
@@ -2215,9 +2231,12 @@ function app_die ($F, $L, $message) {
                // Load header
                loadIncludeOnce('inc/header.php');
 
-               // Prepare message for output
+               // Rewrite message for output
                $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
 
+               // Better log this message away
+               DEBUG_LOG($F, $L, $message);
+
                // Load the message template
                LOAD_TEMPLATE('admin_settings_saved', false, $message);
 
@@ -2314,7 +2333,7 @@ function getCurrentTheme() {
                        // Fix it to default
                        $ret = 'default';
                } // END - if
-       } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
+       } 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'));
 
@@ -2383,6 +2402,12 @@ 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.');
+       } // END - if
+
        // Default error code if unknown account status
        $errorCode = getCode('UNKNOWN_STATUS');
 
@@ -2408,14 +2433,14 @@ function searchDirsRecursive ($dir, &$last_changed) {
        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir."<br />\n";
        // Does it match what we are looking for? (We skip a lot files already!)
        // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
-       $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
-       $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
+       $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
+       $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
        //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
 
        // Walk through all entries
        foreach ($ds as $d) {
                // Generate proper FQFN
-               $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
+               $FQFN = str_replace('//', '/', constant('PATH') . $dir. '/'. $d);
 
                // Is it a file and readable?
                //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
@@ -2446,25 +2471,40 @@ function getActualVersion ($type = 'Revision') {
 
        if (EXT_IS_ACTIVE('cache')) {
                // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
-               if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
-               if (!isset($GLOBALS['cache_array']['revision'][$type])
-               || count($GLOBALS['cache_array']['revision']) < 3
-               || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
+               if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') {
+                       // Force rebuild by URL parameter
+                       $new = true;
+               } elseif ((
+                       !isset($GLOBALS['cache_array']['revision'][$type])
+               ) || (
+                       count($GLOBALS['cache_array']['revision']) < 3
+               ) || (
+                       !$GLOBALS['cache_instance']->loadCacheFile('revision')
+               )) {
+                       // Out-dated cache
+                       $new = true;
+               } // END - if
 
                // Is the cache file outdated/invalid?
-               if ($new === true){
-                       $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
+               if ($new === true) {
+                       // Reload the cache file
+                       $GLOBALS['cache_instance']->loadCacheFile('revision');
+
+                       // Destroy cache file
+                       $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']);
 
                        // Reload load_cach-revison.php
                        loadInclude('inc/loader/load_cache-revision.php');
+
+                       // Abort here
+                       return;
                } // END - if
 
                // Return found value
                return $GLOBALS['cache_array']['revision'][$type][0];
-
        } else {
                // Old Version without ext-cache active (deprecated ?)
 
@@ -2473,7 +2513,7 @@ function getActualVersion ($type = 'Revision') {
 
                // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
                if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
-                       // Has changed!
+                       // Forced rebuild of .revision file
                        $new = true;
                } else {
                        // Check for revision file
@@ -2519,13 +2559,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);
@@ -2616,7 +2662,7 @@ function debug_report_bug ($message = '') {
        } // END - if
 
        // Add output
-       $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>inc/cache/debug.log</strong> in your report (you cannot attach files!):<pre>";
+       $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>inc/cache/debug.log</strong> in your report (you can now attach files):<pre>";
        $debug .= debug_get_printable_backtrace();
        $debug .= "</pre>\nRequest-URI: " . $_SERVER['REQUEST_URI']."<br />\n";
        $debug .= "Thank you for finding bugs.";
@@ -2628,8 +2674,9 @@ function debug_report_bug ($message = '') {
 
 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
 function generateSeed () {
-       list($usec, $sec) = explode(" ", microtime());
-       return ((float)$sec + (float)$usec);
+       list($usec, $sec) = explode(' ', microtime());
+       $microTime = (((float)$sec + (float)$usec)) * 100000;
+       return $microTime;
 }
 
 // Converts a message code to a human-readable message
@@ -2694,7 +2741,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');
@@ -2710,7 +2757,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));
 
@@ -2811,12 +2858,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)) {
@@ -2833,7 +2880,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
                                                } else {
                                                        $next++;
                                                }
-                                       }
+                                       } // END - if
 
                                        // Write to temp file
                                        fputs($fp_tmp, $line);
@@ -2886,9 +2933,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())."|" . $GLOBALS['module']."|".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(constant('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
 }
@@ -2898,7 +2945,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
@@ -3093,7 +3140,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!)
@@ -3159,7 +3206,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!");
        }
 }
 
@@ -3181,12 +3228,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;
@@ -3257,7 +3304,7 @@ function isUserIdSet () {
 // Handle message codes from URL
 function handleCodeMessage () {
        if (REQUEST_ISSET_GET('msg')) {
-               // Default extension is "unknown"
+               // Default extension is 'unknown'
                $ext = 'unknown';
 
                // Is extension given?
@@ -3361,6 +3408,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(constant('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: */ print 'excluded=' . $baseFile . '<br />';
+                       continue;
+               } // END - if
+
+               // Construct include filename and FQFN
+               $fileName = $baseDir . '/' . $baseFile;
+               $FQFN = constant('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: */ print 'baseDir:' . $baseDir . '<br />';
+                       //* DEBUG: */ print 'baseFile:' . $baseFile . '<br />';
+                       //* DEBUG: */ print '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 //
 //////////////////////////////////////////////////