Default refid is always fallback now, or 0 if sql_patches is absend
[mailer.git] / inc / functions.php
index fb13419c1ab5b3aed1f4d96f4aa8cde13824bc17..5f9e1229ade302b33056d1ada5faeb8d7d17c4b0 100644 (file)
@@ -238,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?
@@ -250,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
@@ -799,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
@@ -1954,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);
 }
 
@@ -2027,10 +2026,10 @@ function generateEmailLink ($email, $table = 'admins') {
                $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 = generateEmailLink($email, 'user_data');
+               $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 = generateEmailLink($email, 'sponsor_data');
+               $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
        }
 
        // Shall I close the link when there is no admin?
@@ -2434,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";
@@ -2560,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);
@@ -2752,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));
 
@@ -2929,8 +2934,8 @@ function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
                $message = str_replace("\r", '', str_replace("\n", '', $message));
 
                // 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");
+               $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
 }
@@ -3135,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!)
@@ -3201,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!");
        }
 }
 
@@ -3223,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;
@@ -3403,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 //
 //////////////////////////////////////////////////