X-Git-Url: https://git.mxchange.org/?p=mailer.git;a=blobdiff_plain;f=inc%2Ffunctions.php;h=f7c2247656835dd9c582791c8f158c5b67629422;hp=01f21ce86940b7ff2c8b24a4e84984f211fff6ba;hb=a00ad7dd8c36a5322e28f38d8d641efb90c00c92;hpb=f2b603aed42bfdf7a94611d7bae71fe3a1048890 diff --git a/inc/functions.php b/inc/functions.php index 01f21ce869..f7c2247656 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -88,7 +88,7 @@ function getTotalFatalErrors () { function generatePassword ($length = '0', $exclude = array()) { // Auto-fix invalid length of zero if ($length == '0') { - $length = getPassLen(); + $length = getMinPasswordLength(); } // END - if // Exclude some entries @@ -104,8 +104,9 @@ function generatePassword ($length = '0', $exclude = array()) { } // END - while /* - * When the size is below 40 we can also add additional security by - * scrambling it. Otherwise the hash may corrupted.. + * When the length of the password is below 40 characters additional + * security can be added by scrambling it. Otherwise the hash may + * corrupted. */ if (strlen($password) <= 40) { // Also scramble the password @@ -146,7 +147,7 @@ function generateDateTime ($time, $mode = '0') { case '6': $ret = date('Ymd', $timeSecured); break; case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP default: - logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode)); + logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode)); break; } // END - switch break; @@ -162,7 +163,7 @@ function generateDateTime ($time, $mode = '0') { case '6': $ret = date('Ymd', $timeSecured); break; case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP default: - logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode)); + logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode)); break; } // END - switch } // END - switch @@ -181,11 +182,16 @@ function translateYesNo ($yn) { // Default $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')'; switch ($yn) { - case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break; - case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break; - default: - // Log unknown value - logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $yn)); + case 'Y': // Yes + $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; + break; + + case 'N': // No + $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; + break; + + default: // Log unknown value + logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $yn)); break; } // END - switch } // END - if @@ -201,11 +207,16 @@ function translateActivationStatus ($status) { // Default $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')'; switch ($status) { - case 'Y': $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}'; break; - case 'N': $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}'; break; - default: - // Log unknown value - logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $status)); + case 'Y': // Activated + $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}'; + break; + + case 'N': // Deactivated + $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}'; + break; + + default: // Log unknown value + logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $status)); break; } // END - switch } // END - if @@ -278,7 +289,7 @@ function translateGender ($gender) { default: // Please report bugs on unknown genders - reportBug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender)); + reportBug(__FUNCTION__, __LINE__, sprintf('Unknown gender %s detected.', $gender)); break; } // END - switch @@ -296,7 +307,7 @@ function translateUserStatus ($status) { case 'UNCONFIRMED': case 'CONFIRMED': case 'LOCKED': - // Use generic function for all "normal" cases" + // Use generic function for all "normal" cases $ret = translateGeneric('ACCOUNT_STATUS', $status); break; @@ -306,7 +317,7 @@ function translateUserStatus ($status) { break; default: // Please report all unknown status - reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status))); + reportBug(__FUNCTION__, __LINE__, sprintf('Unknown status %s(%s) detected.', $status, gettype($status))); break; } // END - switch @@ -377,7 +388,7 @@ function generateDereferrerUrl ($url) { // Generates an URL for the frametester function generateFrametesterUrl ($url) { // Prepare frametester URL - $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}", + $frametesterUrl = sprintf('{%%url=modules.php?module=frametester&url=%s%%}', encodeString(compileUriCode($url)) ); @@ -618,13 +629,16 @@ function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) { // Creates a Uni* timestamp from given selection data and prefix function createEpocheTimeFromSelections ($prefix, $postData) { + // Assert on typical array element (maybe all?) + assert(isset($postData[$prefix . '_ye'])); + // Initial return value $ret = '0'; // Is there a leap year? $SWITCH = '0'; - $TEST = getYear() / 4; - $M1 = getMonth(); + $TEST = getYear() / 4; + $M1 = getMonth(); // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day) // 01 2 2 1 1 1 123 4 43 3 32 233 4 43 3 3210 @@ -708,7 +722,7 @@ function isEmailValid ($email) { // Return check result //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!'); - return $GLOBALS[__FUNCTION__][$email];; + return $GLOBALS[__FUNCTION__][$email]; } // Function taken from user comments on www.php.net / function isInStringIgnoreCase() @@ -766,7 +780,13 @@ function generateHash ($plainText, $salt = '', $hash = TRUE) { $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr(); // Build key string - $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt(); + $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt(); + + // Is the secret_key config entry set? + if (isConfigEntrySet('secret_key')) { + // Add it + $keys .= getEncryptSeparator() . getSecretKey(); + } // END - if // Additional data $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time(); @@ -825,10 +845,8 @@ function scrambleString ($str) { $scrambleNums = explode(':', genScrambleString(strlen($str))); } - // Compare both lengths and abort if different - if (strlen($str) != count($scrambleNums)) { - return $str; - } // END - if + // Assert on both lengths + assert(strlen($str) == count($scrambleNums)); // Scramble string here //* DEBUG: */ debugOutput('***Original=' . $str.'***
'); @@ -894,6 +912,8 @@ function genScrambleString ($len) { // So let's create the string for storing it in database $scrambleString = implode(':', $scrambleNumbers); + + // Return it return $scrambleString; } @@ -922,6 +942,7 @@ function encodeHashForCookie ($passHash) { // Default is hexadecimal of index if both are same $mod = dechex($idx); + // Is part1 larger or part2 than its counter part? if ($part1 > $part2) { // part1 is larger @@ -933,7 +954,7 @@ function encodeHashForCookie ($passHash) { $mod = substr($mod, 0, 2); //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')'); - $mod = padLeftZero($mod); + $mod = padLeftZero($mod, 2); //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*'); $start += 2; $newHash .= $mod; @@ -952,7 +973,7 @@ function encodeHashForCookie ($passHash) { // Fix "deleted" cookies function fixDeletedCookies ($cookies) { // Is this an array with entries? - if ((is_array($cookies)) && (count($cookies) > 0)) { + if (isFilledArray($cookies)) { // Then check all cookies if they are marked as deleted! foreach ($cookies as $cookieName) { // Is the cookie set to "deleted"? @@ -978,13 +999,13 @@ function getCurrentTheme () { if (isExtensionActive('theme')) { // Call inner method $ret = getActualTheme(); - } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) { + } elseif ((isPostRequestElementSet('theme')) && (isThemeReadable(postRequestElement('theme')))) { // Use value from POST data $ret = postRequestElement('theme'); - } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) { + } elseif ((isGetRequestElementSet('theme')) && (isThemeReadable(getRequestElement('theme')))) { // Use value from GET data $ret = getRequestElement('theme'); - } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) { + } elseif ((isMailerThemeSet()) && (isThemeReadable(getMailerTheme()))) { // Use value from GET data $ret = getMailerTheme(); } @@ -1005,7 +1026,7 @@ function generateErrorCodeFromUserStatus ($status = '') { $errorCode = getCode('ACCOUNT_UNKNOWN'); // Generate constant name - $codeName = sprintf("ACCOUNT_%s", strtoupper($status)); + $codeName = sprintf('ACCOUNT_%s', strtoupper($status)); // Is the constant there? if (isCodeSet($codeName)) { @@ -1013,7 +1034,7 @@ function generateErrorCodeFromUserStatus ($status = '') { $errorCode = getCode($codeName); } else { // Unknown status - logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status)); + logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown error status %s detected.', $status)); } // Return error code @@ -1530,7 +1551,7 @@ function rebuildCache ($cache, $inc = '', $force = FALSE) { //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force))); // Shall I remove the cache file? - if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) { + if ((isExtensionInstalled('cache')) && (isValidCacheInstance()) && (isHtmlOutputMode())) { // Rebuild cache only in HTML output-mode // @TODO This should be rewritten not to load the cache file for just checking if it is there for save removal. if ($GLOBALS['cache_instance']->loadCacheFile($cache)) { @@ -1541,7 +1562,7 @@ function rebuildCache ($cache, $inc = '', $force = FALSE) { // Include file given? if (!empty($inc)) { // Construct FQFN - $inc = sprintf("inc/loader/load-%s.php", $inc); + $inc = sprintf('inc/loader/load-%s.php', $inc); // Is the include there? if (isIncludeReadable($inc)) { @@ -1549,8 +1570,8 @@ function rebuildCache ($cache, $inc = '', $force = FALSE) { //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!'); loadInclude($inc); } else { - // Include not found - logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache); + // Include not found, which needs now tracing + reportBug(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache); } } // END - if } // END - if @@ -1682,6 +1703,21 @@ function doMonthly () { } // END - if } +// Enables the yearly reset mode and runs it +function doYearly () { + // Enable the reset mode + $GLOBALS['yearly_enabled'] = TRUE; + + // Run filters + runFilterChain('yearly'); + + // Do not update in yearly debug mode + if ((!isConfigEntrySet('DEBUG_YEARLY')) || (!isDebugYearlyEnabled())) { + // Update database + updateConfiguration('last_yearly', getYear()); + } // END - if +} + // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.) function doShutdown () { // Call the filter chain 'shutdown' @@ -1691,7 +1727,7 @@ function doShutdown () { if (isSqlLinkUp()) { // Close link sqlCloseLink(__FUNCTION__, __LINE__); - } elseif (!isInstallationPhase()) { + } elseif (!isInstaller()) { // No database link reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.'); } @@ -1772,9 +1808,10 @@ function isExtraTitleSet () { * @param $excludePattern Regular expression to exclude more files (preg_match()) * @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 */ -function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') { +function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '', $withPrefixSuffix = TRUE) { // Add default entries we should always exclude array_unshift($excludeArray, '.', '..', '.svn', '.htaccess'); @@ -1853,6 +1890,9 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $ad if ($addBaseDir === TRUE) { // With base path array_push($foundMatches, $fileName); + } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) { + // No prefix/suffix + array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension))); } else { // No base path array_push($foundMatches, $baseFile); @@ -1861,9 +1901,18 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $ad // We found .php file but should not search for them, why? reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')'); } - } elseif ($fileExtension == $extension) { + } elseif ((($fileExtension == $extension) || (empty($extension))) && (isFileReadable($FQFN))) { // Other, generic file found - array_push($foundMatches, $fileName); + if ($addBaseDir === TRUE) { + // With base path + array_push($foundMatches, $fileName); + } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) { + // No prefix/suffix + array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension))); + } else { + // No base path + array_push($foundMatches, $baseFile); + } } } // END - while @@ -2014,7 +2063,7 @@ function encodeUrl ($url, $outputMode = '0') { } // END - if // Is there a valid session? - if ((!isSessionValid()) && (!isSpider())) { + if ((!isValidSession()) && (!isSpider())) { // Determine right separator $separator = '&'; if (!isInString('?', $url)) { @@ -2131,7 +2180,7 @@ function handleFieldWithBraces ($field) { // Converts a zero or NULL to word 'NULL' function convertZeroToNull ($number) { // Is it a valid username? - if ((!is_null($number)) && (!empty($number)) && ($number > 0)) { + if (isValidNumber($number)) { // Always secure it $number = bigintval($number); } else { @@ -2146,7 +2195,7 @@ function convertZeroToNull ($number) { // Converts a NULL|empty string|< 1 to zero function convertNullToZero ($number) { // Is it a valid username? - if ((is_null($number)) || (empty($number)) || ($number < 1)) { + if (!isValidNumber($number)) { // Is not valid or zero $number = '0'; } // END - if @@ -2681,6 +2730,22 @@ 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 + + // Return it + return $hex; +} + // ---------------------------------------------------------------------------- // "Translatation" functions for points_data table // ---------------------------------------------------------------------------- @@ -2784,5 +2849,78 @@ 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); +} + +// Wrapper to check whether given theme is readable +function isThemeReadable ($theme) { + // Is there cache? + if (!isset($GLOBALS[__FUNCTION__][$theme])) { + // Determine it + $GLOBALS[__FUNCTION__][$theme] = (isIncludeReadable(sprintf('theme/%s/theme.php', $theme))); + } // END - if + + // Return cache + return $GLOBALS[__FUNCTION__][$theme]; +} + // [EOF] ?>