X-Git-Url: https://git.mxchange.org/?p=mailer.git;a=blobdiff_plain;f=inc%2Ffunctions.php;h=07affa858ae621d45ada5a4a95e97f5e0b6732bb;hp=c227a23925e6d5069a84a1108ea06b4c353727d4;hb=abb35f6c84f2c58b2686d9a6d8855163225040d9;hpb=d1cf572ce023d55e2dbb810d1d6f9301c3d4e3db diff --git a/inc/functions.php b/inc/functions.php index c227a23925..07affa858a 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -10,13 +10,8 @@ * -------------------------------------------------------------------- * * 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 - 2016 by Mailer Developer Team * * For more information visit: http://mxchange.org * * * * This program is free software; you can redistribute it and/or modify * @@ -88,7 +83,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 +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 @@ -218,12 +224,7 @@ function translateActivationStatus ($status) { // OPPOMENT: convertCommaToDot() function translateComma ($dotted, $cut = TRUE, $max = '0') { // First, cast all to double, due to PHP changes - $dotted = (double) $dotted; - - // Default is 3 you can change this in admin area "Settings -> Misc Options" - if (!isConfigEntrySet('max_comma')) { - setConfigEntry('max_comma', 3); - } // END - if + $double = (double) $dotted; // Use from config is default $maxComma = getConfig('max_comma'); @@ -236,7 +237,7 @@ function translateComma ($dotted, $cut = TRUE, $max = '0') { // Cut zeros off? if (($cut === TRUE) && ($max == '0')) { // Test for commata if in cut-mode - $com = explode('.', $dotted); + $com = explode('.', $double); if (count($com) < 2) { // Don't display commatas even if there are none... ;-) $maxComma = '0'; @@ -246,19 +247,19 @@ function translateComma ($dotted, $cut = TRUE, $max = '0') { // Debug log // Translate it now - $translated = $dotted; + $translated = $double; switch (getLanguage()) { case 'de': // German language - $translated = number_format($dotted, $maxComma, ',', '.'); + $translated = number_format($double, $maxComma, ',', '.'); break; default: // All others - $translated = number_format($dotted, $maxComma, '.', ','); + $translated = number_format($double, $maxComma, '.', ','); break; } // END - switch // Return translated value - //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'double=' . $double . ',translated=' . $translated . ',maxComma=' . $maxComma); return $translated; } @@ -278,7 +279,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 +297,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 +307,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 @@ -316,6 +317,9 @@ function translateUserStatus ($status) { // "Translates" 'visible' and 'locked' to a CSS class function translateMenuVisibleLocked ($content, $prefix = '') { + // 1st parameter should be an array + assert(is_array($content)); + // Default is 'menu_unknown' $content['visible_css'] = $prefix . 'menu_unknown'; @@ -367,7 +371,12 @@ function generateDereferrerUrl ($url) { //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')'); // De-refer this URL - $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie($hash) . '&salt=' . substr($hash, 0, getSaltLength()) . '%}'; + $url = sprintf( + '{%url=modules.php?module=loader&url=%s&hash=%s&salt=%s%}', + $encodedUrl, + encodeHashForCookie($hash), + substr($hash, 0, getSaltLength()) + ); } // END - if // Return link @@ -377,7 +386,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)) ); @@ -397,7 +406,7 @@ function countSelection ($array) { $ret = '0'; // Count all entries - foreach ($array as $key => $selected) { + foreach ($array as $selected) { // Is it checked? if (!empty($selected)) { // Yes, then count it @@ -428,7 +437,8 @@ function makeTime ($hours, $minutes, $seconds, $stamp) { } // Redirects to an URL and if neccessarry extends it with own base URL -function redirectToUrl ($url, $allowSpider = TRUE) { +// @TODO $allowSpider is unused +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 @@ -440,8 +450,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"'; @@ -455,17 +468,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 . '
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('&', '&', $url), FALSE); + } // END - if + // Load URL when headers are not sent - sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE)); + sendRawRedirect($url); } 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 @@ -506,7 +525,7 @@ function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums if ($match) { // We have found two different values, so let's sort whole array foreach ($temporaryArray as $sort_key => $sort_val) { - $t = $temporaryArray[$sort_key][$key]; + $t = $temporaryArray[$sort_key][$key]; $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2]; $temporaryArray[$sort_key][$key2] = $t; unset($t); @@ -530,7 +549,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(); @@ -540,7 +559,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 +637,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 +730,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() @@ -763,10 +785,16 @@ 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() . 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(); @@ -817,18 +845,19 @@ 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)); } - // Compare both lengths and abort if different - if (strlen($str) != count($scrambleNums)) { - return $str; - } // END - if + // Convert it into an array + $scrambleNums = explode(':', $scramble); + + // Assert on both lengths + assert(strlen($str) == count($scrambleNums)); // Scramble string here //* DEBUG: */ debugOutput('***Original=' . $str.'***
'); @@ -894,6 +923,8 @@ function genScrambleString ($len) { // So let's create the string for storing it in database $scrambleString = implode(':', $scrambleNumbers); + + // Return it return $scrambleString; } @@ -922,6 +953,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 +965,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 +984,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 +1010,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 +1037,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 +1045,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 +1562,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 +1573,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 +1581,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 +1714,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 +1738,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.'); } @@ -1765,12 +1812,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 @@ -1854,7 +1901,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $ad if ($addBaseDir === TRUE) { // With base path array_push($foundMatches, $fileName); - } elseif ($withPrefixSuffix === FALSE) { + } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) { // No prefix/suffix array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension))); } else { @@ -1865,9 +1912,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) || (empty($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 @@ -2018,7 +2074,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)) { @@ -2031,7 +2087,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 @@ -2069,43 +2125,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? @@ -2135,7 +2154,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 { @@ -2147,10 +2166,22 @@ 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? - if ((is_null($number)) || (empty($number)) || ($number < 1)) { + if (!isValidNumber($number)) { // Is not valid or zero $number = '0'; } // END - if @@ -2788,5 +2819,151 @@ if (!function_exists('html_entity_decode')) { } } // END - if +// "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]; +} + +// 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) . '--}'; +} + +// Loads stylesheet files in different ways, depending on output mode +function loadStyleSheets () { + // Default styles + $stylesList = array( + 'general.css', + 'ajax.css', + ); + + // Add stylesheet for installation + if ((isInstaller())) { + array_push($stylesList, 'install.css'); + } // END - if + + // When no CSS output-mode is set, set it to file-output + if (!isConfigEntrySet('css_php')) { + setConfigEntry('css_php', 'FILE'); + } // END - if + + // Get current theme + $currentTheme = getCurrentTheme(); + + // Has the theme changed? + if ($currentTheme != getSession('mailer_theme')) { + // Then set it + setMailerTheme($currentTheme); + } // END - if + + // Output CSS files or content or link to css.php ? + if ((isCssOutputMode()) || (getCssPhp() == 'DIRECT')) { + // Load CSS files + $stylesList = merge_array($stylesList, getExtensionCssFiles()); + + // Generate base path + $basePath = getBasePathFromTheme($currentTheme); + + // Output inclusion lines + foreach ($stylesList as $value) { + // Only include found CSS files (to reduce 404 requests) + $FQFN = $basePath . '/' . $value; + + // Do include only existing files and whose are not empty + if ((isFileReadable($FQFN)) && (filesize($FQFN) > 0)) { + switch (getCssPhp()) { + case 'DIRECT': // Just link them (unsupported) + $GLOBALS['__page_header'] .= ''; + break; + + case 'FILE': // Output contents + $GLOBALS['__page_header'] .= removeDeprecatedComment(readFromFile($FQFN)); + break; + + default: // Invalid mode! + reportBug(__FILE__, __LINE__, sprintf('Invalid css_php value %s detected.', getCssPhp())); + break; + } // END - switch + } // END - if + } // END - foreach + } elseif ((isHtmlOutputMode()) || (getCssPhp() == 'INLINE')) { + // Load CSS files + $stylesList = merge_array($stylesList, getExtensionCssFiles()); + + // Generate base path + $basePath = getBasePathFromTheme(getCurrentTheme()); + + // Output inclusion lines + $OUT = ''; + foreach ($stylesList as $value) { + // Only include found CSS files (to reduce 404 requests) + $FQFN = $basePath . '/' . $value; + + // Do include only existing files and whose are not empty + if ((isFileReadable($FQFN)) && (filesize($FQFN) > 0)) { + // Load CSS content + $OUT .= readFromFile($FQFN); + } // END - if + } // END - foreach + + // Load template + $GLOBALS['__page_header'] .= loadTemplate('css_inline', TRUE, removeDeprecatedComment($OUT)); + } else { + // Now we load all CSS files from css.php! + $OUT = ''; + } +} + // [EOF] ?>