X-Git-Url: https://git.mxchange.org/?p=mailer.git;a=blobdiff_plain;f=inc%2Ffunctions.php;h=f55c9a396a70d70b13db32e2ce2794b95f016a56;hp=561bbdadf576f00aeef9b519712d8f8a951f48d3;hb=ed930d1133b51edc7ec2379d91286d64afd9bc4f;hpb=175b3f506e193d8d791ec6523db42276e296dd0b diff --git a/inc/functions.php b/inc/functions.php index 561bbdadf5..f55c9a396a 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -10,11 +10,6 @@ * -------------------------------------------------------------------- * * 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 * * For more information visit: http://mxchange.org * @@ -95,7 +90,7 @@ function generatePassword ($length = '0', $exclude = array()) { $localAbc = array_diff($GLOBALS['_abc'], $exclude); // $localAbc must have at least 10 entries - assert(count($localAbc) >= 10, 'localAbc()=' . count($localAbc) . ' is to small.'); + assert(count($localAbc) >= 10); // Start creating password $password = ''; @@ -104,8 +99,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 +142,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 +158,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 +177,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 +202,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 +284,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 +302,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 +312,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 +383,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)) ); @@ -463,9 +469,9 @@ function redirectToUrl ($url, $allowSpider = TRUE) { sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE)); } else { // Output error message - loadInclude('inc/header.php'); + loadPageHeader(); loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url)); - loadInclude('inc/footer.php'); + loadPageFooter(); } // Shut the mailer down here @@ -540,7 +546,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 @@ -618,13 +624,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 +717,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 +775,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() . 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 +840,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 +907,8 @@ function genScrambleString ($len) { // So let's create the string for storing it in database $scrambleString = implode(':', $scrambleNumbers); + + // Return it return $scrambleString; } @@ -922,6 +937,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 +949,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; @@ -978,13 +994,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 +1021,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 +1029,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 @@ -1412,7 +1428,7 @@ function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $u } // END - if // Make sure entries is not bool, then something went wrong - assert(!is_bool($entries), 'entries[]=bool which is not expected.'); + assert(!is_bool($entries)); } elseif (!empty($filterFunctions[$search])) { // Debug mode enabled? if (isDebugModeEnabled()) { @@ -1430,7 +1446,7 @@ function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $u } // END - if // Make sure entries is not bool, then something went wrong - assert(!is_bool($entries), 'entries[]=bool which is not expected.'); + assert(!is_bool($entries)); } // Return value @@ -1549,8 +1565,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 @@ -1780,12 +1796,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 @@ -2093,43 +2109,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? @@ -2171,6 +2150,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? @@ -2526,7 +2517,7 @@ function memberEditEntriesConfirm ($tableName, $columns = array(), $filterFuncti // Delete rows by given id numbers function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $content = array()) { // Do this only for members - assert(isMember(), 'isMember()=false which is not expected.'); + assert(isMember()); // $tableName must be an array if ((!is_array($tableName)) || (count($tableName) != 1)) { @@ -2569,7 +2560,7 @@ function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunc // @TODO cacheFiles is not yet supported function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) { // Do this only for logged in member - assert(isMember(), 'isMember()=false which is not expected.'); + assert(isMember()); // Call inner (general) function doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content); @@ -2647,7 +2638,7 @@ function caluculateTimeUnitValue ($seconds, $timeUnit) { // "Getter" for an array from given one but only one index of it function getArrayFromArrayIndex ($array, $key) { // Some simple validation - assert(isset($array[0][$key]), 'array[0][' . $key . '] is not set.'); + assert(isset($array[0][$key])); // Init new array $newArray = array(); @@ -2718,9 +2709,12 @@ function hashSha256 ($str) { $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)))); + $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; } @@ -2889,5 +2883,43 @@ 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]; +} + +// 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) +// Credits: shaunspiller at spammenot-gmail dot com ( http://de.php.net/dl#88566 ) +function loadLibrary ($n, $f = NULL) { + return extension_loaded($n) or 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] ?>