Renamed ifSqlHasZeroNums() to ifSqlHasZeroNumRows() and improved some queries.
[mailer.git] / inc / functions.php
index 3ee3d3b1ae1cb86fc6b745d4c96b40b5460094dd..a240205c2816c7bfa2355f19448b205e4ff41496 100644 (file)
  * -------------------------------------------------------------------- *
  * Kurzbeschreibung  : Viele Nicht-Datenbank-Funktionen                 *
  * -------------------------------------------------------------------- *
- * $Revision::                                                        $ *
- * $Date::                                                            $ *
- * $Tag:: 0.2.1-FINAL                                                 $ *
- * $Author::                                                          $ *
- * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2015 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -439,7 +434,7 @@ function makeTime ($hours, $minutes, $seconds, $stamp) {
 }
 
 // Redirects to an URL and if neccessarry extends it with own base URL
-function redirectToUrl ($url, $allowSpider = TRUE) {
+function redirectToUrl ($url, $allowSpider = TRUE, $compileCode = TRUE) {
        // Is the output mode -2?
        if (isAjaxOutputMode()) {
                // This is always (!) an AJAX request and shall not be redirected
@@ -451,8 +446,11 @@ function redirectToUrl ($url, $allowSpider = TRUE) {
                $url = substr($url, 6, -2);
        } // END - if
 
-       // Compile out codes
-       eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
+       // Compile codes out?
+       if ($compileCode === TRUE) {
+               // Compile out codes
+               eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
+       } // END - if
 
        // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
        $rel = ' rel="external"';
@@ -466,17 +464,23 @@ function redirectToUrl ($url, $allowSpider = TRUE) {
        // Three different ways to debug...
        //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
-       //* DEBUG: */ die($url);
+       //* DEBUG-DIE: */ die(__METHOD__ . ':url=' . $url . '<br />compileCode=' . intval($compileCode));
 
        // We should not sent a redirect if headers are already sent
        if (!headers_sent()) {
+               // Compile again?
+               if ($compileCode === TRUE) {
+                       // Do final compilation
+                       $url = doFinalCompilation(str_replace('&amp;', '&', $url), FALSE);
+               } // END - if
+
                // Load URL when headers are not sent
-               sendRawRedirect(doFinalCompilation(str_replace('&amp;', '&', $url), FALSE));
+               sendRawRedirect($url);
        } else {
                // Output error message
-               loadInclude('inc/header.php');
+               loadPageHeader();
                loadTemplate('redirect_url', FALSE, str_replace('&amp;', '&', $url));
-               loadInclude('inc/footer.php');
+               loadPageFooter();
        }
 
        // Shut the mailer down here
@@ -541,7 +545,7 @@ function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums
 //
 function generateRandomCode ($length, $code, $userid, $extraData = '') {
        // Build server string
-       $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
+       $server = $_SERVER['REQUEST_URI'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
 
        // Build key string
        $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
@@ -551,7 +555,7 @@ function generateRandomCode ($length, $code, $userid, $extraData = '') {
        if (isConfigEntrySet('file_hash')) {
                $keys .= getEncryptSeparator() . getFileHash();
        } // END - if
-       $keys .= getEncryptSeparator() . getDateFromRepository();
+
        if (isConfigEntrySet('master_salt')) {
                $keys .= getEncryptSeparator() . getMasterSalt();
        } // END - if
@@ -777,10 +781,10 @@ function generateHash ($plainText, $salt = '', $hash = TRUE) {
        // When the salt is empty build a new one, else use the first x configured characters as the salt
        if (empty($salt)) {
                // Build server string for more entropy
-               $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
+               $server = $_SERVER['REQUEST_URI'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
 
                // Build key string
-               $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
+               $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getMasterSalt();
 
                // Is the secret_key config entry set?
                if (isConfigEntrySet('secret_key')) {
@@ -837,14 +841,17 @@ function scrambleString ($str) {
        if (strlen($str) > 40) {
                // The string is to long
                return $str;
-       } elseif (strlen($str) == 40) {
+       } elseif ((strlen($str) == 40) && (getPassScramble() != '')) {
                // From database
-               $scrambleNums = explode(':', getPassScramble());
+               $scramble = getPassScramble();
        } else {
                // Generate new numbers
-               $scrambleNums = explode(':', genScrambleString(strlen($str)));
+               $scramble = genScrambleString(strlen($str));
        }
 
+       // Convert it into an array
+       $scrambleNums = explode(':', $scramble);
+
        // Assert on both lengths
        assert(strlen($str) == count($scrambleNums));
 
@@ -1801,12 +1808,12 @@ function isExtraTitleSet () {
  *
  * @param      $baseDir                        Relative base directory to PATH to scan from
  * @param      $prefix                         Prefix for all positive matches (which files should be found)
- * @param      $fileIncludeDirs        whether to include directories in the final output array
- * @param      $addBaseDir                     whether to add $baseDir to all array entries
+ * @param      $fileIncludeDirs        Whether to include directories in the final output array
+ * @param      $addBaseDir                     Whether to add $baseDir to all array entries
  * @param      $excludeArray           Excluded files and directories, these must be full files names, e.g. 'what-' will exclude all files named 'what-' but won't exclude 'what-foo.php'
  * @param      $extension                      File extension for all positive matches
  * @param      $excludePattern         Regular expression to exclude more files (preg_match())
- * @param      $recursive                      whether to scan recursively
+ * @param      $recursive                      Whether to scan recursively
  * @param      $suffix                         Suffix for positive matches ($extension will be appended, too)
  * @param      $withPrefixSuffix       Whether to include prefix/suffix in found entries
  * @return     $foundMatches           All found positive matches for above criteria
@@ -2076,7 +2083,7 @@ function encodeUrl ($url, $outputMode = '0') {
        } // END - if
 
        // Add {?URL?} ?
-       if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
+       if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (!isFullQualifiedUrl($url))) {
                // Add it
                $url = '{?URL?}/' . $url;
        } // END - if
@@ -2114,43 +2121,6 @@ function isSpider () {
        return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
 }
 
-// Function to search for the last modified file
-function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
-       // Get dir as array
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
-       // 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, '', FALSE, TRUE, array(), '.php', $excludePattern);
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
-
-       // Walk through all entries
-       foreach ($ds as $d) {
-               // Generate proper FQFN
-               $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
-
-               // Is it a file and readable?
-               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
-               if (isFileReadable($FQFN)) {
-                       // $FQFN is a readable file so extract the requested data from it
-                       $check = extractRevisionInfoFromFile($FQFN, $lookFor);
-                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
-
-                       // Is the file more recent?
-                       if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
-                               // This file is newer as the file before
-                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
-                               $last_changed['path_name'] = $FQFN;
-                               $last_changed[$lookFor] = $check;
-                       } // END - if
-               } else {
-                       // Not readable
-                       /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
-               }
-       } // END - foreach
-}
-
 // Handles the braces [] of a field (e.g. value of 'name' attribute)
 function handleFieldWithBraces ($field) {
        // Are there braces [] at the end?
@@ -2192,6 +2162,18 @@ function convertZeroToNull ($number) {
        return $number;
 }
 
+// Converts an empty string to NULL, else leaves it untouched
+function convertEmptyToNull ($str) {
+       // Is the string empty?
+       if (strlen($str) == 0) {
+               // Is really empty
+               $str = NULL;
+       } // END - if
+
+       // Return it
+       return $str;
+}
+
 // Converts a NULL|empty string|< 1 to zero
 function convertNullToZero ($number) {
        // Is it a valid username?
@@ -2730,25 +2712,6 @@ function convertCharsetToUtf8 ($str, $charset) {
        return $str;
 }
 
-// Hash string with SHA256 and encode it to hex
-function hashSha256 ($str) {
-       /// Hash string
-       $hash = mhash(MHASH_SHA256, $str);
-
-       // Encode it to hexadecimal
-       $hex = '';
-       for ($i = 0; $i < strlen($hash); $i++) {
-               // Encode char to decimal, pad it with zero, add it
-               $hex .= padLeftZero(dechex(ord(substr($hash, $i, 1))), 2);
-       } // END - if
-
-       // Make sure 'length modulo 2' = 0
-       assert((strlen($hex) % 2) == 0);
-
-       // Return it
-       return $hex;
-}
-
 // ----------------------------------------------------------------------------
 //              "Translatation" functions for points_data table
 // ----------------------------------------------------------------------------
@@ -2852,62 +2815,6 @@ if (!function_exists('html_entity_decode')) {
        }
 } // END - if
 
-// "Calculates" password strength
-function calculatePasswordStrength ($password, $configEntry = 'min_password_length') {
-       // Default score
-       $score = 1;
-
-       if ((strlen($password) < 1) || (strlen($password) < getConfig($configEntry))) {
-               // Is to weak
-               return 0;
-       } // END - if
-
-       // At least 8 chars long?
-       if (strlen($password) >= 8) {
-               // Add score
-               $score++;
-       } // END - if
-
-       // At least 10 chars long?
-       if (strlen($password) >= 10) {
-               // Add score
-               $score++;
-       } // END - if
-
-       // Lower and upper cases?
-       if ((preg_match('/[a-z]/', $password)) && (preg_match('/[A-Z]/', $password))) {
-               // Add score
-               $score++;
-       } // END - if
-
-       // Also numbers?
-       if (preg_match('/[0-9]/', $password))  {
-               // Add score
-               $score++;
-       } // END - if
-
-       // Special characters?
-       if (preg_match('/.[!,@,#,$,%,^,&,*,?,\/,_,~,+,-,(,)]/', $password)) {
-               // Add score
-               $score++;
-       } // END - if
-
-       // Return password score
-       return $score;
-}
-
-// "Translates" password strength/score
-function translatePasswordStrength ($strength) {
-       // Return it translated
-       return '{--PASSWORD_SCORE_' . bigintval($strength) . '--}';
-}
-
-// Checks whether given password is strong enough
-function isStrongPassword ($password) {
-       // Determine it
-       return (calculatePasswordStrength($password) >= getConfig('min_password_score'));
-}
-
 // "Getter" for base path from theme
 function getBasePathFromTheme ($theme) {
        return sprintf('%stheme/%s/css/', getPath(), $theme);
@@ -2925,5 +2832,38 @@ function isThemeReadable ($theme) {
        return $GLOBALS[__FUNCTION__][$theme];
 }
 
+// Checks whether a given PHP extension is loaded or can be loaded at runtime
+//
+// Supported OS: Windows, Linux, (Mac?)
+function isPhpExtensionLoaded ($extension) {
+       // Is the extension loaded?
+       if (extension_loaded($extension)) {
+               // All fine
+               return TRUE;
+       } // END - if
+
+       // Try to load the extension
+       return loadLibrary($extension);
+}
+
+// Loads given library (aka. PHP extension)
+function loadLibrary ($n, $f = NULL) {
+       // Is the actual function dl() available? (Not on all SAPIs since 5.3)
+       if (!is_callable('dl')) {
+               // Not callable
+               /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dl() is not callable for n=' . $n . ',f[' . gettype($f) . ']=' . $f);
+               return FALSE;
+       } // END - if
+
+       // Try to load PHP library
+       return dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
+}
+
+// "Translates" given PHP extension name into a readable version
+function translatePhpExtension ($extension) {
+       // Return the language element
+       return '{--PHP_EXTENSION_' . strtoupper($extension) . '--}';
+}
+
 // [EOF]
 ?>