X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;ds=sidebyside;f=inc%2Fgeneral-functions.php;fp=inc%2Fgeneral-functions.php;h=acdec10b659b5a5392d8259c5b07f823639db753;hb=cb11b0028323b24de48bfbab2ed576455e0d9465;hp=0000000000000000000000000000000000000000;hpb=4da10ba9e4a47d9b4eee4609a185fc7266fab031;p=mailer.git
diff --git a/inc/general-functions.php b/inc/general-functions.php
new file mode 100644
index 0000000000..acdec10b65
--- /dev/null
+++ b/inc/general-functions.php
@@ -0,0 +1,3081 @@
+= 10);
+
+ // Start creating password
+ $password = '';
+ while (strlen($password) < $length) {
+ $password .= $localAbc[mt_rand(0, count($localAbc) -1)];
+ } // END - while
+
+ /*
+ * 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
+ $password = scrambleString($password);
+ } // END - if
+
+ // Return the password
+ return $password;
+}
+
+// Generates a human-readable timestamp from the Uni* stamp
+function generateDateTime ($time, $mode = '0') {
+ // Is there cache?
+ if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
+ // Return it instead
+ return $GLOBALS[__FUNCTION__][$time][$mode];
+ } // END - if
+
+ // If the stamp is zero it mostly didn't "happen"
+ if (($time == '0') || (is_null($time))) {
+ // Never happend
+ return '{--NEVER_HAPPENED--}';
+ } // END - if
+
+ // Filter out numbers
+ $timeSecured = bigintval($time);
+
+ // Detect language
+ switch (getLanguage()) {
+ case 'de': // German date / time format
+ switch ($mode) {
+ case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break;
+ case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break;
+ case '2': $ret = date('d.m.Y|H:i', $timeSecured); break;
+ case '3': $ret = date('d.m.Y', $timeSecured); break;
+ case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
+ case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
+ 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));
+ break;
+ } // END - switch
+ break;
+
+ default: // Default is the US date / time format!
+ switch ($mode) {
+ case '0': $ret = date('r', $timeSecured); break;
+ case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break;
+ case '2': $ret = date('y-m-d|H:i', $timeSecured); break;
+ case '3': $ret = date('y-m-d', $timeSecured); break;
+ case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
+ case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
+ 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));
+ break;
+ } // END - switch
+ } // END - switch
+
+ // Store it in cache
+ $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
+
+ // Return result
+ return $ret;
+}
+
+// Translates Y/N to yes/no
+function translateYesNo ($yn) {
+ // Is it cached?
+ if (!isset($GLOBALS[__FUNCTION__][$yn])) {
+ // Default
+ $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
+ switch ($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
+
+ // Return it
+ return $GLOBALS[__FUNCTION__][$yn];
+}
+
+// "Translates" Y/N into "de-/active"
+function translateActivationStatus ($status) {
+ // Is it cached?
+ if (!isset($GLOBALS[__FUNCTION__][$status])) {
+ // Default
+ $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')';
+ switch ($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
+
+ // Return it
+ return $GLOBALS[__FUNCTION__][$status];
+}
+
+// Translates the american decimal dot into a german comma
+// OPPOMENT: convertCommaToDot()
+function translateComma ($dotted, $cut = TRUE, $max = '0') {
+ // First, cast all to double, due to PHP changes
+ $double = (double) $dotted;
+
+ // Use from config is default
+ $maxComma = getConfig('max_comma');
+
+ // Use from parameter?
+ if ($max > 0) {
+ $maxComma = $max;
+ } // END - if
+
+ // Cut zeros off?
+ if (($cut === TRUE) && ($max == '0')) {
+ // Test for commata if in cut-mode
+ $com = explode('.', $double);
+ if (count($com) < 2) {
+ // Don't display commatas even if there are none... ;-)
+ $maxComma = '0';
+ } // END - if
+ } // END - if
+
+ // Debug log
+
+ // Translate it now
+ $translated = $double;
+ switch (getLanguage()) {
+ case 'de': // German language
+ $translated = number_format($double, $maxComma, ',', '.');
+ break;
+
+ default: // All others
+ $translated = number_format($double, $maxComma, '.', ',');
+ break;
+ } // END - switch
+
+ // Return translated value
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'double=' . $double . ',translated=' . $translated . ',maxComma=' . $maxComma);
+ return $translated;
+}
+
+// Translate Uni*-like gender to human-readable
+function translateGender ($gender) {
+ // Default
+ $ret = '!' . $gender . '!';
+
+ // Male/female or company?
+ switch ($gender) {
+ case 'M': // Male
+ case 'F': // Female
+ case 'C': // Company
+ // Use generic function
+ $ret = translateGeneric('GENDER', $gender);
+ break;
+
+ default:
+ // Please report bugs on unknown genders
+ reportBug(__FUNCTION__, __LINE__, sprintf('Unknown gender %s detected.', $gender));
+ break;
+ } // END - switch
+
+ // Return translated gender
+ return $ret;
+}
+
+// "Translates" the user status
+function translateUserStatus ($status) {
+ // Default status is unknown if something goes through
+ $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
+
+ // Generate message depending on status
+ switch ($status) {
+ case 'UNCONFIRMED':
+ case 'CONFIRMED':
+ case 'LOCKED':
+ // Use generic function for all "normal" cases
+ $ret = translateGeneric('ACCOUNT_STATUS', $status);
+ break;
+
+ case '': // Account deleted
+ case NULL: // Account deleted
+ $ret = '{--ACCOUNT_STATUS_DELETED--}';
+ break;
+
+ default: // Please report all unknown status
+ reportBug(__FUNCTION__, __LINE__, sprintf('Unknown status %s(%s) detected.', $status, gettype($status)));
+ break;
+ } // END - switch
+
+ // Return it
+ return $ret;
+}
+
+// "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';
+
+ // Translate 'visible' and keep an eye on the prefix
+ switch ($content['visible']) {
+ case 'Y': // Should be visible
+ $content['visible_css'] = $prefix . 'menu_visible';
+ break;
+
+ case 'N': // Is invisible
+ $content['visible_css'] = $prefix . 'menu_invisible';
+ break;
+
+ default: // Please report this
+ reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=
' . print_r($content, TRUE) . '
');
+ break;
+ } // END - switch
+
+ // Translate 'locked' and keep an eye on the prefix
+ switch ($content['locked']) {
+ case 'Y': // Should be locked, only admins can call this
+ $content['locked_css'] = $prefix . 'menu_locked';
+ break;
+
+ case 'N': // Is unlocked and visible to members/guests/sponsors
+ $content['locked_css'] = $prefix . 'menu_unlocked';
+ break;
+
+ default: // Please report this
+ reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=
' . print_r($content, TRUE) . '
');
+ break;
+ } // END - switch
+
+ // Return the resulting array
+ return $content;
+}
+
+// Generates an URL for the dereferer
+function generateDereferrerUrl ($url) {
+ // Don't de-refer our own links!
+ if ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
+ // Encode URL
+ $encodedUrl = encodeString(compileUriCode($url));
+
+ // Generate hash
+ $hash = generateHash($url . getSiteKey() . getDateKey());
+
+ // Log plain URL and hash
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
+
+ // De-refer this URL
+ $url = sprintf(
+ '{%%url=modules.php?module=loader&url=%s&hash=%s&salt=%s%%}',
+ $encodedUrl,
+ encodeHashForCookie($hash),
+ substr($hash, 0, getSaltLength())
+ );
+ } // END - if
+
+ // Return link
+ return $url;
+}
+
+// Generates an URL for the frametester
+function generateFrametesterUrl ($url) {
+ // Prepare frametester URL
+ $frametesterUrl = sprintf('{%%url=modules.php?module=frametester&url=%s%%}',
+ encodeString(compileUriCode($url))
+ );
+
+ // Return the new URL
+ return $frametesterUrl;
+}
+
+// Count entries from e.g. a selection box
+function countSelection ($array) {
+ // Integrity check
+ if (!is_array($array)) {
+ // Not an array!
+ reportBug(__FUNCTION__, __LINE__, 'No array provided.');
+ } // END - if
+
+ // Init count
+ $ret = '0';
+
+ // Count all entries
+ foreach ($array as $selected) {
+ // Is it checked?
+ if (!empty($selected)) {
+ // Yes, then count it
+ $ret++;
+ } // END - if
+ } // END - foreach
+
+ // Return counted selections
+ return $ret;
+}
+
+// Generates a timestamp (some wrapper for mktime())
+function makeTime ($hours, $minutes, $seconds, $stamp) {
+ // Extract day, month and year from given timestamp
+ $days = getDay($stamp);
+ $months = getMonth($stamp);
+ $years = getYear($stamp);
+
+ // Create timestamp for wished time which depends on extracted date
+ return mktime(
+ $hours,
+ $minutes,
+ $seconds,
+ $months,
+ $days,
+ $years
+ );
+}
+
+// Redirects to an URL and if neccessarry extends it with own base URL
+// @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
+ return;
+ } // END - if
+
+ // Remove {%url=
+ if (substr($url, 0, 6) == '{%url=') {
+ $url = substr($url, 6, -2);
+ } // END - if
+
+ // 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"';
+
+ // Is there internal or external URL?
+ if (substr($url, 0, strlen(getUrl())) == getUrl()) {
+ // Own (=internal) URL
+ $rel = '';
+ } // END - if
+
+ // Three different ways to debug...
+ //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $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($url);
+ } else {
+ // Output error message
+ loadPageHeader();
+ loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
+ loadPageFooter();
+ }
+
+ // Shut the mailer down here
+ doShutdown();
+}
+
+/************************************************************************
+ * *
+ * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
+ * $a_sort sortiert: *
+ * *
+ * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
+ * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
+ * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
+ * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
+ * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
+ * *
+ * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
+ * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
+ * Sie, dass es doch nicht so schwer ist! :-) *
+ * *
+ ************************************************************************/
+function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
+ $temporaryArray = $array;
+ while ($primary_key < count($a_sort)) {
+ foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
+ foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
+ $match = FALSE;
+ if ($nums === FALSE) {
+ // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
+ if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
+ } elseif ($key != $key2) {
+ // Sort numbers (E.g.: 9 < 10)
+ if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
+ if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
+ }
+
+ 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];
+ $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
+ $temporaryArray[$sort_key][$key2] = $t;
+ unset($t);
+ } // END - foreach
+ } // END - if
+ } // END - foreach
+ } // END - foreach
+
+ // Count one up
+ $primary_key++;
+ } // END - while
+
+ // Write back sorted array
+ $array = $temporaryArray;
+}
+
+
+//
+// Deprecated : $length (still has one reference in this function)
+// Optional : $extraData
+//
+function generateRandomCode ($length, $code, $userid, $extraData = '') {
+ // Build server string
+ $server = $_SERVER['REQUEST_URI'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
+
+ // Build key string
+ $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
+ if (isConfigEntrySet('secret_key')) {
+ $keys .= getEncryptSeparator() . getSecretKey();
+ } // END - if
+ if (isConfigEntrySet('file_hash')) {
+ $keys .= getEncryptSeparator() . getFileHash();
+ } // END - if
+
+ if (isConfigEntrySet('master_salt')) {
+ $keys .= getEncryptSeparator() . getMasterSalt();
+ } // END - if
+
+ // Build string from misc data
+ $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
+
+ // Add more additional data
+ if (isSessionVariableSet('u_hash')) {
+ $data .= getEncryptSeparator() . getSession('u_hash');
+ } // END - if
+
+ // Add referral id, language, theme and userid
+ $data .= getEncryptSeparator() . determineReferralId();
+ $data .= getEncryptSeparator() . getLanguage();
+ $data .= getEncryptSeparator() . getCurrentTheme();
+ $data .= getEncryptSeparator() . getMemberId();
+
+ // Calculate number for generating the code
+ $a = $code + getConfig('_ADD') - 1;
+
+ if (isConfigEntrySet('master_salt')) {
+ // Generate hash with master salt from modula of number with the prime number and other data
+ $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
+ } else {
+ // Generate hash with "hash of site key" from modula of number with the prime number and other data
+ $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
+ }
+
+ // Create number from hash
+ $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
+
+ // At least 10 numbers shall be secure enought!
+ if (isExtensionActive('other')) {
+ $len = getCodeLength();
+ } else {
+ $len = $length;
+ } // END - if
+
+ // Smaller 1 is not okay
+ if ($len < 1) {
+ // Fix it to 10
+ $len = 10;
+ } // END - if
+
+ // Cut off requested counts of number, but skip first digit (which is mostly a zero)
+ $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
+
+ // Done building code
+ return $return;
+}
+
+// Does only allow numbers
+function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
+ //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
+ // Filter all non-number chars out, so only number chars will remain
+ $ret = preg_replace('/[^0123456789]/', '', $num);
+
+ // Shall we cast?
+ if ($castValue === TRUE) {
+ // Cast to biggest numeric type
+ $ret = (double) $ret;
+ } // END - if
+
+ // Has the whole value changed?
+ if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
+ // Log the values
+ reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
+ } // END - if
+
+ // Return result
+ //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
+ return $ret;
+}
+
+// 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();
+
+ // 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
+ if ((floor($TEST) == $TEST) && ($M1 == '02') && (((isset($postData[$prefix . '_mo'])) && ($postData[$prefix . '_mo'] > '02')) || ((isset($postData[$prefix . '_mn'])) && ($postData[$prefix . '_mn'] > '02')))) {
+ $SWITCH = getOneDay();
+ } // END - if
+
+ // First add years...
+ $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
+
+ // Next months...
+ if (isset($postData[$prefix . '_mo'])) {
+ $ret += $postData[$prefix . '_mo'] * 2628000;
+ } elseif (isset($postData[$prefix . '_mn'])) {
+ $ret += $postData[$prefix . '_mn'] * 2628000;
+ }
+
+ // Next weeks
+ $ret += $postData[$prefix . '_we'] * 604800;
+
+ // Next days...
+ $ret += $postData[$prefix . '_da'] * 86400;
+
+ // Next hours...
+ $ret += $postData[$prefix . '_ho'] * 3600;
+
+ // Next minutes..
+ $ret += $postData[$prefix . '_mi'] * 60;
+
+ // And at last seconds...
+ $ret += $postData[$prefix . '_se'];
+
+ // Return calculated value
+ return $ret;
+}
+
+// Creates a 'fancy' human-readable timestamp from a Uni* stamp
+function createFancyTime ($stamp) {
+ // Get data array with years/months/weeks/days/...
+ $data = createTimeSelections($stamp, '', '', '', TRUE);
+ $ret = '';
+ foreach ($data as $k => $v) {
+ if ($v > 0) {
+ // Value is greater than 0 "eval" data to return string
+ $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
+ break;
+ } // END - if
+ } // END - foreach
+
+ // Is something there?
+ if (!empty($ret)) {
+ // Remove leading commata and space
+ $ret = substr($ret, 2);
+ } else {
+ // Zero seconds
+ $ret = '0 {--TIME_UNIT_SECOND--}';
+ }
+
+ // Return fancy time string
+ return $ret;
+}
+
+// Taken from www.php.net isInStringIgnoreCase() user comments
+function isEmailValid ($email) {
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
+
+ // Is there cache?
+ if (!isset($GLOBALS[__FUNCTION__][$email])) {
+ // Check first part of email address
+ $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
+
+ // Check domain
+ $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
+
+ // Generate pattern
+ $regex = '@^' . $first . '\@' . $domain . '$@iU';
+
+ // Determine it
+ $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
+ } // END - if
+
+ // Return check result
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
+ return $GLOBALS[__FUNCTION__][$email];
+}
+
+// Function taken from user comments on www.php.net / function isInStringIgnoreCase()
+function isUrlValid ($url, $compile = TRUE) {
+ // Trim URL a little
+ $url = trim(urldecode($url));
+ //* DEBUG: */ debugOutput($url);
+
+ // Compile some chars out...
+ if ($compile === TRUE) {
+ $url = compileUriCode($url, FALSE, FALSE, FALSE);
+ } // END - if
+ //* DEBUG: */ debugOutput($url);
+
+ // Check for the extension filter
+ if (isExtensionActive('filter')) {
+ // Use the extension's filter set
+ return FILTER_VALIDATE_URL($url, FALSE);
+ } // END - if
+
+ /*
+ * If not installed, perform a simple test. Just make it sure there is always a
+ * http:// or https:// in front of the URLs.
+ */
+ return isUrlValidSimple($url);
+}
+
+// Generate a hash for extra-security for all passwords
+function generateHash ($plainText, $salt = '', $hash = TRUE) {
+ // Debug output
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
+
+ // Is the required extension 'sql_patches' there and a salt is not given?
+ // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
+ if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
+ // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
+ if ($hash === TRUE) {
+ // Is plain password
+ return md5($plainText);
+ } else {
+ // Is already a hash
+ return $plainText;
+ }
+ } // END - if
+
+ // Is an arry element missing here?
+ if (!isConfigEntrySet('file_hash')) {
+ // Stop here
+ reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
+ } // END - if
+
+ // 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['REQUEST_URI'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
+
+ // Build key string
+ $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();
+
+ // Calculate number for generating the code
+ $a = time() + getConfig('_ADD') - 1;
+
+ // Generate SHA1 sum from modula of number and the prime number
+ $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
+ $sha1 = scrambleString($sha1);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
+ //* DEBUG: */ $sha1b = descrambleString($sha1);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
+
+ // Generate the password salt string
+ $salt = substr($sha1, 0, getSaltLength());
+ //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
+ } else {
+ // Use given salt
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
+ $salt = substr($salt, 0, getSaltLength());
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
+
+ // Sanity check on salt
+ if (strlen($salt) != getSaltLength()) {
+ // Not the same!
+ reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
+ } // END - if
+ }
+
+ // Generate final hash (for debug output)
+ $finalHash = $salt . sha1($salt . $plainText);
+
+ // Debug output
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
+
+ // Return hash
+ return $finalHash;
+}
+
+// Scramble a string
+function scrambleString ($str) {
+ // Init
+ $scrambled = '';
+
+ // Final check, in case of failure it will return unscrambled string
+ if (strlen($str) > 40) {
+ // The string is to long
+ return $str;
+ } elseif ((strlen($str) == 40) && (getPassScramble() != '')) {
+ // From database
+ $scramble = getPassScramble();
+ } else {
+ // Generate new numbers
+ $scramble = genScrambleString(strlen($str));
+ }
+
+ // Convert it into an array
+ $scrambleNums = explode(':', $scramble);
+
+ // Assert on both lengths
+ assert(strlen($str) == count($scrambleNums));
+
+ // Scramble string here
+ //* DEBUG: */ debugOutput('***Original=' . $str.'*** ');
+ for ($idx = 0; $idx < strlen($str); $idx++) {
+ // Get char on scrambled position
+ $char = substr($str, $scrambleNums[$idx], 1);
+
+ // Add it to final output string
+ $scrambled .= $char;
+ } // END - for
+
+ // Return scrambled string
+ //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'*** ');
+ return $scrambled;
+}
+
+// De-scramble a string scrambled by scrambleString()
+function descrambleString ($str) {
+ // Scramble only 40 chars long strings
+ if (strlen($str) != 40) {
+ return $str;
+ } // END - if
+
+ // Load numbers from config
+ $scrambleNums = explode(':', getPassScramble());
+
+ // Validate numbers
+ if (count($scrambleNums) != 40) {
+ return $str;
+ } // END - if
+
+ // Begin descrambling
+ $orig = str_repeat(' ', 40);
+ //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++ ');
+ for ($idx = 0; $idx < 40; $idx++) {
+ $char = substr($str, $idx, 1);
+ $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
+ } // END - for
+
+ // Return scrambled string
+ //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++ ');
+ return $orig;
+}
+
+// Generated a "string" for scrambling
+function genScrambleString ($len) {
+ // Prepare array for the numbers
+ $scrambleNumbers = array();
+
+ // First we need to setup randomized numbers from 0 to 31
+ for ($idx = 0; $idx < $len; $idx++) {
+ // Generate number
+ $rand = mt_rand(0, ($len - 1));
+
+ // Check for it by creating more numbers
+ while (array_key_exists($rand, $scrambleNumbers)) {
+ $rand = mt_rand(0, ($len - 1));
+ } // END - while
+
+ // Add number
+ $scrambleNumbers[$rand] = $rand;
+ } // END - for
+
+ // So let's create the string for storing it in database
+ $scrambleString = implode(':', $scrambleNumbers);
+
+ // Return it
+ return $scrambleString;
+}
+
+// Generate an PGP-like encrypted hash of given hash for e.g. cookies
+function encodeHashForCookie ($passHash) {
+ // Return vanilla password hash
+ $ret = $passHash;
+
+ // Is a secret key and master salt already initialized?
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
+ if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
+ // Only calculate when the secret key is generated
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
+ if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
+ // Both keys must have same length so return unencrypted
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
+ return $ret;
+ } // END - if
+
+ $newHash = ''; $start = 9;
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
+ for ($idx = 0; $idx < 20; $idx++) {
+ // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
+ $part1 = hexdec(substr($passHash , $start, 2));
+ $part2 = hexdec(substr(getSecretKey(), $start, 2));
+
+ // 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
+ $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
+ } elseif ($part2 > $part1) {
+ // part2 is larger
+ $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
+ }
+
+ $mod = substr($mod, 0, 2);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
+ $mod = padLeftZero($mod, 2);
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
+ $start += 2;
+ $newHash .= $mod;
+ } // END - for
+
+ // Just copy it over, as the master salt is not really helpful here
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
+ $ret = $newHash;
+ } // END - if
+
+ // Return result
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
+ return $ret;
+}
+
+// Fix "deleted" cookies
+function fixDeletedCookies ($cookies) {
+ // Is this an array with entries?
+ if (isFilledArray($cookies)) {
+ // Then check all cookies if they are marked as deleted!
+ foreach ($cookies as $cookieName) {
+ // Is the cookie set to "deleted"?
+ if (getSession($cookieName) == 'deleted') {
+ setSession($cookieName, '');
+ } // END - if
+ } // END - foreach
+ } // END - if
+}
+
+// Checks if a given apache module is loaded
+function isApacheModuleLoaded ($apacheModule) {
+ // Check it and return result
+ return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
+}
+
+// Get current theme name
+function getCurrentTheme () {
+ // The default theme is 'default'... ;-)
+ $ret = 'default';
+
+ // Is there ext-theme installed and active or is 'theme' in URL or POST data?
+ if (isExtensionActive('theme')) {
+ // Call inner method
+ $ret = getActualTheme();
+ } elseif ((isPostRequestElementSet('theme')) && (isThemeReadable(postRequestElement('theme')))) {
+ // Use value from POST data
+ $ret = postRequestElement('theme');
+ } elseif ((isGetRequestElementSet('theme')) && (isThemeReadable(getRequestElement('theme')))) {
+ // Use value from GET data
+ $ret = getRequestElement('theme');
+ } elseif ((isMailerThemeSet()) && (isThemeReadable(getMailerTheme()))) {
+ // Use value from GET data
+ $ret = getMailerTheme();
+ }
+
+ // Return theme value
+ return $ret;
+}
+
+// Generates an error code from given account status
+function generateErrorCodeFromUserStatus ($status = '') {
+ // If no status is provided, use the default, cached
+ if ((empty($status)) && (isMember())) {
+ // Get user status
+ $status = getUserData('status');
+ } // END - if
+
+ // Default error code if unknown account status
+ $errorCode = getCode('ACCOUNT_UNKNOWN');
+
+ // Generate constant name
+ $codeName = sprintf('ACCOUNT_%s', strtoupper($status));
+
+ // Is the constant there?
+ if (isCodeSet($codeName)) {
+ // Then get it!
+ $errorCode = getCode($codeName);
+ } else {
+ // Unknown status
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown error status %s detected.', $status));
+ }
+
+ // Return error code
+ return $errorCode;
+}
+
+// Back-ported from the new ship-simu engine. :-)
+function debug_get_printable_backtrace () {
+ // Init variable
+ $backtrace = '';
+
+ // Get and prepare backtrace for output
+ $backtraceArray = debug_backtrace();
+ foreach ($backtraceArray as $key => $trace) {
+ if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
+ if (!isset($trace['line'])) $trace['line'] = __LINE__;
+ if (!isset($trace['args'])) $trace['args'] = array();
+ $backtrace .= '