Proper cache hit counting fixed
[mailer.git] / inc / wrapper-functions.php
index b76f513d39a06a91a60111ec4535c8be4051ab0b..48db9bbc05b706263abad490660594bfce5b9fb4 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /************************************************************************
- * MXChange v0.2.1                                    Start: 04/04/2009 *
- * ===============                              Last change: 04/04/2009 *
+ * Mailer v0.2.1-FINAL                                Start: 04/04/2009 *
+ * ===================                          Last change: 04/04/2009 *
  *                                                                      *
  * -------------------------------------------------------------------- *
  * File              : wrapper-functions.php                            *
@@ -18,6 +18,7 @@
  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
  * For more information visit: http://www.mxchange.org                  *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -42,31 +43,27 @@ if (!defined('__SECURITY')) {
 } // END - if
 
 // Read a given file
-function readFromFile ($FQFN, $sqlPrepare = false) {
+function readFromFile ($FQFN) {
        // Sanity-check if file is there (should be there, but just to make it sure)
        if (!isFileReadable($FQFN)) {
                // This should not happen
                debug_report_bug(__FUNCTION__.': File ' . basename($FQFN) . ' is not readable!');
        } // END - if
 
-       // Load the file
-       if (function_exists('file_get_contents')) {
-               // Use new function
-               $content = file_get_contents($FQFN);
-       } else {
-               // Fall-back to implode-file chain
-               $content = implode('', file($FQFN));
-       }
-
-       // Prepare SQL queries?
-       if ($sqlPrepare === true) {
-               // Remove some unwanted chars
-               $content = str_replace("\r", '', $content);
-               $content = str_replace("\n\n", "\n", $content);
+       // Is it cached?
+       if (!isset($GLOBALS['file_content'][$FQFN])) {
+               // Load the file
+               if (function_exists('file_get_contents')) {
+                       // Use new function
+                       $GLOBALS['file_content'][$FQFN] = file_get_contents($FQFN);
+               } else {
+                       // Fall-back to implode-file chain
+                       $GLOBALS['file_content'][$FQFN] = implode('', file($FQFN));
+               }
        } // END - if
 
        // Return the content
-       return $content;
+       return $GLOBALS['file_content'][$FQFN];
 }
 
 // Writes content to a file
@@ -110,6 +107,9 @@ function writeToFile ($FQFN, $content, $aquireLock = false) {
        // Mark it as readable
        $GLOBALS['file_readable'][$FQFN] = true;
 
+       // Remember content in cache
+       $GLOBALS['file_content'][$FQFN] = $content;
+
        // Return status
        return changeMode($FQFN, 0644);
 }
@@ -137,25 +137,10 @@ function decodeString ($str, $decompress = true) {
        return $str;
 }
 
-// Smartly adds slashes
-function smartAddSlashes ($unquoted) {
-       // Do we have cache?
-       if (!isset($GLOBALS['smart_addslashes'][$unquoted])) {
-               // Remove slashe
-               $unquoted = str_replace("\\", '', $unquoted);
-
-               // Put it in cache and add slashes
-               $GLOBALS['smart_addslashes'][$unquoted] = addslashes($unquoted);
-       } // END - if
-
-       // Return result
-       return $GLOBALS['smart_addslashes'][$unquoted];
-}
-
 // Decode entities in a nicer way
-function decodeEntities ($str) {
+function decodeEntities ($str, $quote = ENT_NOQUOTES) {
        // Decode the entities to UTF-8 now
-       $decodedString = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
+       $decodedString = html_entity_decode($str, $quote, 'UTF-8');
 
        // Return decoded string
        return $decodedString;
@@ -185,7 +170,13 @@ function isFileReadable ($FQFN) {
        if (!isset($GLOBALS['file_readable'][$FQFN])) {
                // Check all...
                $GLOBALS['file_readable'][$FQFN] = ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
-       } // END - if
+
+               // Debug message
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CHECK! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
+       } else {
+               // Cache used
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'file=' . basename($FQFN) . ' - CACHE! (' . intval($GLOBALS['file_readable'][$FQFN]) . ')');
+       }
 
        // Return result
        return $GLOBALS['file_readable'][$FQFN];
@@ -237,12 +228,12 @@ function detectRemoteHostname () {
 }
 
 // "Getter" for user agent
-function detectUserAgent () {
+function detectUserAgent ($alwaysReal = false) {
        // Get remote ip from environment
        $userAgent = getenv('HTTP_USER_AGENT');
 
        // Is removeip installed?
-       if (isExtensionActive('removeip')) {
+       if ((isExtensionActive('removeip')) && ($alwaysReal === false)) {
                // Then anonymize it
                $userAgent = getAnonymousUserAgent($userAgent);
        } // END - if
@@ -266,16 +257,33 @@ function detectReferer () {
        return $referer;
 }
 
+// "Getter" for request URI
+function detectRequestUri () {
+       // Return it
+       return (getenv('REQUEST_URI'));
+}
+
+// "Getter" for query string
+function detectQueryString () {
+       return str_replace('&', '&amp;', (getenv('QUERY_STRING')));
+}
+
+// "Getter" for SERVER_NAME
+function detectServerName () {
+       // Return it
+       return (getenv('SERVER_NAME'));
+}
+
 // Check wether we are installing
 function isInstalling () {
        // Determine wether we are installing
-       if (!isset($GLOBALS['mxchange_installing'])) {
+       if (!isset($GLOBALS['mailer_installing'])) {
                // Check URL (css.php/js.php need this)
-               $GLOBALS['mxchange_installing'] = isGetRequestElementSet('installing');
+               $GLOBALS['mailer_installing'] = isGetRequestParameterSet('installing');
        } // END - if
 
        // Return result
-       return $GLOBALS['mxchange_installing'];
+       return $GLOBALS['mailer_installing'];
 }
 
 // Check wether this script is installed
@@ -318,7 +326,14 @@ function isInstalled () {
 
 // Check wether an admin is registered
 function isAdminRegistered () {
-       return ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
+       // Is cache set?
+       if (!isset($GLOBALS['is_admin_registered'])) {
+               // Simply check it
+               $GLOBALS['is_admin_registered'] = ((isConfigEntrySet('ADMIN_REGISTERED')) && (getConfig('ADMIN_REGISTERED') == 'Y'));
+       } // END - if
+
+       // Return it
+       return $GLOBALS['is_admin_registered'];
 }
 
 // Checks wether the reset mode is active
@@ -329,14 +344,38 @@ function isResetModeEnabled () {
 
 // Checks wether the debug mode is enabled
 function isDebugModeEnabled () {
-       // Simply check it
-       return ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
+       // Is cache set?
+       if (!isset($GLOBALS['is_debugmode_enabled'])) {
+               // Simply check it
+               $GLOBALS['is_debugmode_enabled'] = ((isConfigEntrySet('DEBUG_MODE')) && (getConfig('DEBUG_MODE') == 'Y'));
+       } // END - if
+
+       // Return it
+       return $GLOBALS['is_debugmode_enabled'];
+}
+
+// Checks wether SQL debugging is enabled
+function isSqlDebuggingEnabled () {
+       // Is cache set?
+       if (!isset($GLOBALS['is_sql_debug_enabled'])) {
+               // Determine if SQL debugging is enabled
+               $GLOBALS['is_sql_debug_enabled'] = ((isConfigEntrySet('DEBUG_SQL')) && (getConfig('DEBUG_SQL') == 'Y'));
+       } // END - if
+
+       // Return it
+       return $GLOBALS['is_sql_debug_enabled'];
 }
 
 // Checks wether we shall debug regular expressions
-function isDebugRegExpressionEnabled () {
-       // Simply check it
-       return ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
+function isDebugRegularExpressionEnabled () {
+       // Is cache set?
+       if (!isset($GLOBALS['is_regular_exp_debug_enabled'])) {
+               // Simply check it
+               $GLOBALS['is_regular_exp_debug_enabled'] = ((isConfigEntrySet('DEBUG_REGEX')) && (getConfig('DEBUG_REGEX') == 'Y'));
+       } // END - if
+
+       // Return it
+       return $GLOBALS['is_regular_exp_debug_enabled'];
 }
 
 // Checks wether the cache instance is valid
@@ -388,14 +427,28 @@ function copyFileVerified ($source, $dest, $chmod = '') {
 // Wrapper function for header()
 // Send a header but checks before if we can do so
 function sendHeader ($header) {
+       // Send the header
+       //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
+       $GLOBALS['header'][] = trim($header);
+}
+
+// Flushes all headers
+function flushHeaders () {
        // Is the header already sent?
        if (headers_sent()) {
                // Then abort here
                debug_report_bug('Headers already sent!');
        } // END - if
 
-       // Send the header
-       header(trim($header));
+       // Flush all headers if found
+       if ((isset($GLOBALS['header'])) && (is_array($GLOBALS['header']))) {
+               foreach ($GLOBALS['header'] as $header) {
+                       header($header);
+               } // END - foreach
+       } // END - if
+
+       // Mark them as flushed
+       $GLOBALS['header'] = array();
 }
 
 // Wrapper function for chmod()
@@ -428,8 +481,15 @@ function removeFile ($FQFN) {
 }
 
 // Wrapper for $_POST['sel']
-function countPostSelection () {
-       return countSelection(postRequestElement('sel'));
+function countPostSelection ($element = 'sel') {
+       // Is it set?
+       if (isPostRequestParameterSet($element)) {
+               // Return counted elements
+               return countSelection(postRequestParameter($element));
+       } else {
+               // Return zero if not found
+               return 0;
+       }
 }
 
 // Checks wether the config-local.php is loaded
@@ -443,15 +503,15 @@ function isNicknameUsed ($userid) {
        $isUsed = false;
 
        // Is the cache there
-       if (isset($GLOBALS['cache_probe_nicknames'][$userid])) {
+       if (isset($GLOBALS['is_nickname_used'][$userid])) {
                // Then use it
-               $isUsed = $GLOBALS['cache_probe_nicknames'][$userid];
+               $isUsed = $GLOBALS['is_nickname_used'][$userid];
        } else {
                // Determine it
-               $isUsed = ((isExtensionActive('nickname')) && (('' . round($userid) . '') != $userid));
+               $isUsed = (('' . round($userid) . '') != $userid);
 
                // And write it to the cache
-               $GLOBALS['cache_probe_nicknames'][$userid] = $isUsed;
+               $GLOBALS['is_nickname_used'][$userid] = $isUsed;
        }
 
        // Return the result
@@ -490,7 +550,7 @@ function setWhatFromConfig ($configEntry) {
 // Checks wether what is set and optionally aborts on miss
 function isWhatSet ($strict =  false) {
        // Check for it
-       $isset = (isset($GLOBALS['what']));
+       $isset = isset($GLOBALS['what']);
 
        // Should we abort here?
        if (($strict === true) && ($isset === false)) {
@@ -525,7 +585,7 @@ function setAction ($newAction) {
 // Checks wether action is set and optionally aborts on miss
 function isActionSet ($strict =  false) {
        // Check for it
-       $isset = (isset($GLOBALS['action']));
+       $isset = ((isset($GLOBALS['action'])) && (!empty($GLOBALS['action'])));
 
        // Should we abort here?
        if (($strict === true) && ($isset === false)) {
@@ -566,14 +626,11 @@ function isModuleSet ($strict =  false) {
        // Should we abort here?
        if (($strict === true) && ($isset === false)) {
                // Output backtrace
-               print 'Module not set!<pre>';
-               debug_print_backtrace();
-               die('</pre');
                debug_report_bug('module is empty.');
        } // END - if
 
        // Return it
-       return $isset;
+       return (($isset === true) && ($GLOBALS['module'] != 'unknown')) ;
 }
 
 // Getter for 'output_mode' value
@@ -640,21 +697,48 @@ function addPointsDirectly ($subject, $userid, $points) {
 // Wrapper function to redirect from member-only modules to index
 function redirectToIndexMemberOnlyModule () {
        // Do the redirect here
-       redirectToUrl('modules.php?module=index&amp;code=' . getCode('MODULE_MEM_ONLY') . '&amp;mod=' . getModule());
+       redirectToUrl('modules.php?module=index&code=' . getCode('MODULE_MEM_ONLY') . '&mod=' . getModule());
+}
+
+// Wrapper function to redirect to current URL
+function redirectToRequestUri () {
+       redirectToUrl(basename(detectRequestUri()));
+}
+
+// Wrapper function to redirect to de-refered URL
+function redirectToDereferedUrl ($URL) {
+       // Redirect to to
+       redirectToUrl(generateDerefererUrl($URL));
 }
 
 // Wrapper function for checking if extension is installed and newer or same version
 function isExtensionInstalledAndNewer ($ext_name, $version) {
+       // Is an cache entry found?
+       if (!isset($GLOBALS['ext_installed_newer'][$ext_name][$version])) {
+               $GLOBALS['ext_installed_newer'][$ext_name][$version] = ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
+       } else {
+               // Cache hits should be incremented twice
+               incrementStatsEntry('cache_hits', 2);
+       }
+
        // Return it
-       //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=&gt;'.$version.'<br />';
-       return ((isExtensionInstalled($ext_name)) && (getExtensionVersion($ext_name) >= $version));
+       //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'=&gt;'.$version.':'.intval($GLOBALS['ext_installed_newer'][$ext_name][$version]).'<br />';
+       return $GLOBALS['ext_installed_newer'][$ext_name][$version];
 }
 
 // Wrapper function for checking if extension is installed and older than given version
 function isExtensionInstalledAndOlder ($ext_name, $version) {
+       // Is an cache entry found?
+       if (!isset($GLOBALS['ext_installed_older'][$ext_name][$version])) {
+               $GLOBALS['ext_installed_older'][$ext_name][$version] = ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
+       } else {
+               // Cache hits should be incremented twice
+               incrementStatsEntry('cache_hits', 2);
+       }
+
        // Return it
-       //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'&lt;'.$version.'<br />';
-       return ((isExtensionInstalled($ext_name)) && (isExtensionOlder($ext_name, $version)));
+       //* DEBUG: */ print __FUNCTION__.':'.$ext_name.'&lt;'.$version.':'.intval($GLOBALS['ext_installed_older'][$ext_name][$version]).'<br />';
+       return $GLOBALS['ext_installed_older'][$ext_name][$version];
 }
 
 // Set username
@@ -664,6 +748,13 @@ function setUsername ($userName) {
 
 // Get username
 function getUsername () {
+       // User name set?
+       if (!isset($GLOBALS['username'])) {
+               // No, so it has to be a guest
+               $GLOBALS['username'] = getMessage('USERNAME_GUEST');
+       } // END - if
+
+       // Return it
        return $GLOBALS['username'];
 }
 
@@ -681,16 +772,14 @@ function isInstallationPhase () {
 
 // Checks wether the extension demo is actuve and the admin login is demo (password needs to be demo, too!)
 function isDemoModeActive () {
-       return ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
-}
-
-// Wrapper function to redirect to de-refered URL
-function redirectToDereferedUrl ($URL) {
-       // De-refer the URL
-       $URL = generateDerefererUrl($URL);
+       // Is cache set?
+       if (!isset($GLOBALS['demo_mode_active'])) {
+               // Simply check it
+               $GLOBALS['demo_mode_active'] = ((isExtensionActive('demo')) && (getSession('admin_login') == 'demo'));
+       } // END - if
 
-       // Redirect to to
-       redirectToUrl($URL);
+       // Return it
+       return $GLOBALS['demo_mode_active'];
 }
 
 // Getter for PHP caching value
@@ -700,6 +789,28 @@ function getPhpCaching () {
 
 // Checks wether the admin hash is set
 function isAdminHashSet ($admin) {
+       /**
+        * @TODO Do we really need this check? If yes, try to fix this:
+        * 1.:functions.php:2504, debug_get_mailable_backtrace(0)
+        * 2.:wrapper-functions.php:744, debug_report_bug(1)
+        * 3.:mysql-manager.php:728, isAdminHashSet(1)
+        * 4.:filters.php:384, isAdmin(0)
+        * 5.:debug_get_mailable_backtrace:2457, FILTER_DETERMINE_USERNAME(1)
+        * 6.:filter-functions.php:280, call_user_func_array(2)
+        * 7.:load_cache.php:74, runFilterChain(1)
+        * 8.:inc-functions.php:131, include(1)
+        * 9.:inc-functions.php:145, loadInclude(1)
+        * 10.:mysql-connect.php:104, loadIncludeOnce(1)
+        * 11.:inc-functions.php:131, include(1)
+        * 12.:inc-functions.php:145, loadInclude(1)
+        * 13.:config-global.php:106, loadIncludeOnce(1)
+        * 14.:js.php:57, require(1)
+        */
+       if (!isset($GLOBALS['cache_array']['admin'])) {
+               debug_report_bug('Cache not set.');
+       } // END - if
+
+       // Check for admin hash
        return isset($GLOBALS['cache_array']['admin']['password'][$admin]);
 }
 
@@ -708,5 +819,127 @@ function setAdminHash ($admin, $hash) {
        $GLOBALS['cache_array']['admin']['password'][$admin] = $hash;
 }
 
+// Init user data array
+function initUserData () {
+       // User id should not be zero
+       if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
+
+       // Init the user
+       $GLOBALS['user_data'][getCurrentUserId()] = array();
+}
+
+// Getter for user data
+function getUserData ($column) {
+       // User id should not be zero
+       if (getCurrentUserId() < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
+
+       // Return the value
+       return $GLOBALS['user_data'][getCurrentUserId()][$column];
+}
+
+// Geter for whole user data array
+function getUserDataArray () {
+       // Get user id
+       $uid = getCurrentUserId();
+
+       // User id should not be zero
+       if ($uid < 1) debug_report_bug(__FUNCTION__.': User id is zero.');
+
+       // Get the whole array if found
+       if (isset($GLOBALS['user_data'][$uid])) {
+               // Found, so return it
+               return $GLOBALS['user_data'][$uid];
+       } else {
+               // Return empty array
+               return array();
+       }
+}
+
+// Checks if the user data is valid, this may indicate that the user has logged
+// in, but you should use isMember() if you want to find that out.
+function isUserDataValid () {
+       // User id should not be zero so abort here
+       if (!isCurrentUserIdSet()) return false;
+
+       // Is it cached?
+       if (!isset($GLOBALS['is_userdata_valid'][getCurrentUserId()])) {
+               // Determine it
+               $GLOBALS['is_userdata_valid'][getCurrentUserId()] = ((isset($GLOBALS['user_data'][getCurrentUserId()])) && (count($GLOBALS['user_data'][getCurrentUserId()]) > 1));
+       } // END - if
+
+       // Return the result
+       return $GLOBALS['is_userdata_valid'][getCurrentUserId()];
+}
+
+// Setter for current userid
+function setCurrentUserId ($userid) {
+       // Set userid
+       $GLOBALS['current_userid'] = bigintval($userid);
+
+       // Unset it to re-determine the actual state
+       unset($GLOBALS['is_userdata_valid'][$userid]);
+}
+
+// Getter for current userid
+function getCurrentUserId () {
+       // Userid must be set before it can be used
+       if (!isCurrentUserIdSet()) {
+               // Not set
+               debug_report_bug('User id is not set.');
+       } // END - if
+
+       // Return the userid
+       return $GLOBALS['current_userid'];
+}
+
+// Checks if current userid is set
+function isCurrentUserIdSet () {
+       return ((isset($GLOBALS['current_userid'])) && ($GLOBALS['current_userid'] > 0));
+}
+
+// Checks wether we are debugging template cache
+function isDebuggingTemplateCache () {
+       return (getConfig('DEBUG_TEMPLATE_CACHE') == 'Y');
+}
+
+// Wrapper for fetchUserData() and getUserData() calls
+function getFetchedUserData ($keyColumn, $userid, $valueColumn) {
+       // Is it cached?
+       if (!isset($GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn])) {
+               // Default is 'guest'
+               $data = getMessage('USERNAME_GUEST');
+
+               // Can we fetch the user data?
+               if (($userid > 0) && (fetchUserData($userid, $keyColumn))) {
+                       // Now get the data back
+                       $data = getUserData($valueColumn);
+               } // END - if
+
+               // Cache it
+               $GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn] = $data;
+       } // END - if
+
+       // Return it
+       return $GLOBALS['user_data_cache'][$userid][$keyColumn][$valueColumn];
+}
+
+// Wrapper for strpos() to ease porting from deprecated ereg() function
+function isInString ($needle, $haystack) {
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'needle=' . $needle . ', haystack=' . $haystack . ', returned=' . intval(strpos($haystack, $needle) !== false));
+       return (strpos($haystack, $needle) !== false);
+}
+
+// Wrapper for strpos() to ease porting from deprecated eregi() function
+// This function is case-insensitive
+function isInStringIgnoreCase ($needle, $haystack) {
+       return (isInString(strtolower($needle), strtolower($haystack)));
+}
+
+// Wrapper to check for if fatal errors where detected
+function ifFatalErrorsDetected () {
+       // Just call the inner function
+       return (getTotalFatalErrors() > 0);
+}
+
 // [EOF]
 ?>