2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/25/2003 *
4 * =================== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-database functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-Datenbank-Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2012 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Init fatal message array
44 function initFatalMessages () {
45 $GLOBALS['fatal_messages'] = array();
48 // Getter for whole fatal error messages
49 function getFatalArray () {
50 return $GLOBALS['fatal_messages'];
53 // Add a fatal error message to the queue array
54 function addFatalMessage ($F, $L, $message, $extra = '') {
55 if (is_array($extra)) {
56 // Multiple extras for a message with masks
57 $message = call_user_func_array('sprintf', $extra);
58 } elseif (!empty($extra)) {
59 // $message is text with a mask plus extras to insert into the text
60 $message = sprintf($message, $extra);
63 // Add message to $GLOBALS['fatal_messages']
64 array_push($GLOBALS['fatal_messages'], $message);
66 // Log fatal messages away
67 logDebugMessage($F, $L, 'Fatal error message: ' . compileCode($message));
70 // Getter for total fatal message count
71 function getTotalFatalErrors () {
75 // Is there at least the first entry?
76 if (!empty($GLOBALS['fatal_messages'][0])) {
78 $count = count($GLOBALS['fatal_messages']);
85 // Generate a password in a specified length or use default password length
86 function generatePassword ($length = '0', $exclude = array()) {
87 // Auto-fix invalid length of zero
89 $length = getPassLen();
92 // Exclude some entries
93 $localAbc = array_diff($GLOBALS['_abc'], $exclude);
95 // $localAbc must have at least 10 entries
96 assert(count($localAbc) >= 10);
98 // Start creating password
100 while (strlen($password) < $length) {
101 $password .= $localAbc[mt_rand(0, count($localAbc) -1)];
105 * When the size is below 40 we can also add additional security by
106 * scrambling it. Otherwise the hash may corrupted..
108 if (strlen($password) <= 40) {
109 // Also scramble the password
110 $password = scrambleString($password);
113 // Return the password
117 // Generates a human-readable timestamp from the Uni* stamp
118 function generateDateTime ($time, $mode = '0') {
120 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
122 return $GLOBALS[__FUNCTION__][$time][$mode];
125 // If the stamp is zero it mostly didn't "happen"
126 if (($time == '0') || (is_null($time))) {
128 return '{--NEVER_HAPPENED--}';
131 // Filter out numbers
132 $timeSecured = bigintval($time);
135 switch (getLanguage()) {
136 case 'de': // German date / time format
138 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break;
139 case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break;
140 case '2': $ret = date('d.m.Y|H:i', $timeSecured); break;
141 case '3': $ret = date('d.m.Y', $timeSecured); break;
142 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
143 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
144 case '6': $ret = date('Ymd', $timeSecured); break;
145 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
147 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
152 default: // Default is the US date / time format!
154 case '0': $ret = date('r', $timeSecured); break;
155 case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break;
156 case '2': $ret = date('y-m-d|H:i', $timeSecured); break;
157 case '3': $ret = date('y-m-d', $timeSecured); break;
158 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
159 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
160 case '6': $ret = date('Ymd', $timeSecured); break;
161 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
163 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
169 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
175 // Translates Y/N to yes/no
176 function translateYesNo ($yn) {
178 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
180 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
182 case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
183 case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
186 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $yn));
192 return $GLOBALS[__FUNCTION__][$yn];
195 // Translates the american decimal dot into a german comma
196 // OPPOMENT: convertCommaToDot()
197 function translateComma ($dotted, $cut = TRUE, $max = '0') {
198 // First, cast all to double, due to PHP changes
199 $dotted = (double) $dotted;
201 // Default is 3 you can change this in admin area "Settings -> Misc Options"
202 if (!isConfigEntrySet('max_comma')) {
203 setConfigEntry('max_comma', 3);
206 // Use from config is default
207 $maxComma = getConfig('max_comma');
209 // Use from parameter?
215 if (($cut === TRUE) && ($max == '0')) {
216 // Test for commata if in cut-mode
217 $com = explode('.', $dotted);
218 if (count($com) < 2) {
219 // Don't display commatas even if there are none... ;-)
227 $translated = $dotted;
228 switch (getLanguage()) {
229 case 'de': // German language
230 $translated = number_format($dotted, $maxComma, ',', '.');
233 default: // All others
234 $translated = number_format($dotted, $maxComma, '.', ',');
238 // Return translated value
239 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
243 // Translate Uni*-like gender to human-readable
244 function translateGender ($gender) {
246 $ret = '!' . $gender . '!';
248 // Male/female or company?
253 // Use generic function
254 $ret = translateGeneric('GENDER', $gender);
258 // Please report bugs on unknown genders
259 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
263 // Return translated gender
267 // "Translates" the user status
268 function translateUserStatus ($status) {
269 // Default status is unknown if something goes through
270 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
272 // Generate message depending on status
277 // Use generic function for all "normal" cases"
278 $ret = translateGeneric('ACCOUNT_STATUS', $status);
281 case '': // Account deleted
282 case NULL: // Account deleted
283 $ret = '{--ACCOUNT_STATUS_DELETED--}';
286 default: // Please report all unknown status
287 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
295 // "Translates" 'visible' and 'locked' to a CSS class
296 function translateMenuVisibleLocked ($content, $prefix = '') {
297 // Default is 'menu_unknown'
298 $content['visible_css'] = $prefix . 'menu_unknown';
300 // Translate 'visible' and keep an eye on the prefix
301 switch ($content['visible']) {
302 case 'Y': // Should be visible
303 $content['visible_css'] = $prefix . 'menu_visible';
306 case 'N': // Is invisible
307 $content['visible_css'] = $prefix . 'menu_invisible';
310 default: // Please report this
311 reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
315 // Translate 'locked' and keep an eye on the prefix
316 switch ($content['locked']) {
317 case 'Y': // Should be locked, only admins can call this
318 $content['locked_css'] = $prefix . 'menu_locked';
321 case 'N': // Is unlocked and visible to members/guests/sponsors
322 $content['locked_css'] = $prefix . 'menu_unlocked';
325 default: // Please report this
326 reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
330 // Return the resulting array
334 // Generates an URL for the dereferer
335 function generateDereferrerUrl ($url) {
336 // Don't de-refer our own links!
337 if ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
339 $encodedUrl = encodeString(compileUriCode($url));
342 $hash = generateHash($url . getSiteKey() . getDateKey());
344 // Log plain URL and hash
345 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
348 $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie($hash) . '&salt=' . substr($hash, 0, getSaltLength()) . '%}';
355 // Generates an URL for the frametester
356 function generateFrametesterUrl ($url) {
357 // Prepare frametester URL
358 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
359 encodeString(compileUriCode($url))
362 // Return the new URL
363 return $frametesterUrl;
366 // Count entries from e.g. a selection box
367 function countSelection ($array) {
369 if (!is_array($array)) {
371 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
378 foreach ($array as $key => $selected) {
380 if (!empty($selected)) {
381 // Yes, then count it
386 // Return counted selections
390 // Generates a timestamp (some wrapper for mktime())
391 function makeTime ($hours, $minutes, $seconds, $stamp) {
392 // Extract day, month and year from given timestamp
393 $days = getDay($stamp);
394 $months = getMonth($stamp);
395 $years = getYear($stamp);
397 // Create timestamp for wished time which depends on extracted date
408 // Redirects to an URL and if neccessarry extends it with own base URL
409 function redirectToUrl ($url, $allowSpider = TRUE) {
410 // Is the output mode -2?
411 if (isAjaxOutputMode()) {
412 // This is always (!) an AJAX request and shall not be redirected
417 if (substr($url, 0, 6) == '{%url=') {
418 $url = substr($url, 6, -2);
422 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
424 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
425 $rel = ' rel="external"';
427 // Is there internal or external URL?
428 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
429 // Own (=internal) URL
433 // Three different ways to debug...
434 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
435 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
436 //* DEBUG: */ die($url);
438 // We should not sent a redirect if headers are already sent
439 if (!headers_sent()) {
440 // Load URL when headers are not sent
441 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE));
443 // Output error message
444 loadInclude('inc/header.php');
445 loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
446 loadInclude('inc/footer.php');
449 // Shut the mailer down here
453 /************************************************************************
455 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
456 * $a_sort sortiert: *
458 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
459 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
460 * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
461 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
462 * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
464 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
465 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
466 * Sie, dass es doch nicht so schwer ist! :-) *
468 ************************************************************************/
469 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
470 $temporaryArray = $array;
471 while ($primary_key < count($a_sort)) {
472 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
473 foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
475 if ($nums === FALSE) {
476 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
477 if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
478 } elseif ($key != $key2) {
479 // Sort numbers (E.g.: 9 < 10)
480 if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
481 if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
485 // We have found two different values, so let's sort whole array
486 foreach ($temporaryArray as $sort_key => $sort_val) {
487 $t = $temporaryArray[$sort_key][$key];
488 $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
489 $temporaryArray[$sort_key][$key2] = $t;
500 // Write back sorted array
501 $array = $temporaryArray;
506 // Deprecated : $length (still has one reference in this function)
507 // Optional : $extraData
509 function generateRandomCode ($length, $code, $userid, $extraData = '') {
510 // Build server string
511 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
514 $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
515 if (isConfigEntrySet('secret_key')) {
516 $keys .= getEncryptSeparator() . getSecretKey();
518 if (isConfigEntrySet('file_hash')) {
519 $keys .= getEncryptSeparator() . getFileHash();
521 $keys .= getEncryptSeparator() . getDateFromRepository();
522 if (isConfigEntrySet('master_salt')) {
523 $keys .= getEncryptSeparator() . getMasterSalt();
526 // Build string from misc data
527 $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
529 // Add more additional data
530 if (isSessionVariableSet('u_hash')) {
531 $data .= getEncryptSeparator() . getSession('u_hash');
534 // Add referral id, language, theme and userid
535 $data .= getEncryptSeparator() . determineReferralId();
536 $data .= getEncryptSeparator() . getLanguage();
537 $data .= getEncryptSeparator() . getCurrentTheme();
538 $data .= getEncryptSeparator() . getMemberId();
540 // Calculate number for generating the code
541 $a = $code + getConfig('_ADD') - 1;
543 if (isConfigEntrySet('master_salt')) {
544 // Generate hash with master salt from modula of number with the prime number and other data
545 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
547 // Generate hash with "hash of site key" from modula of number with the prime number and other data
548 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
551 // Create number from hash
552 $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
554 // At least 10 numbers shall be secure enought!
555 if (isExtensionActive('other')) {
556 $len = getCodeLength();
561 // Smaller 1 is not okay
567 // Cut off requested counts of number, but skip first digit (which is mostly a zero)
568 $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
570 // Done building code
574 // Does only allow numbers
575 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
576 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
577 // Filter all non-number chars out, so only number chars will remain
578 $ret = preg_replace('/[^0123456789]/', '', $num);
581 if ($castValue === TRUE) {
582 // Cast to biggest numeric type
583 $ret = (double) $ret;
586 // Has the whole value changed?
587 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
589 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
593 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
597 // Creates a Uni* timestamp from given selection data and prefix
598 function createEpocheTimeFromSelections ($prefix, $postData) {
599 // Initial return value
602 // Is there a leap year?
604 $TEST = getYear() / 4;
607 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
608 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) {
609 $SWITCH = getOneDay();
612 // First add years...
613 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
616 $ret += $postData[$prefix . '_mo'] * 2628000;
619 $ret += $postData[$prefix . '_we'] * 604800;
622 $ret += $postData[$prefix . '_da'] * 86400;
625 $ret += $postData[$prefix . '_ho'] * 3600;
628 $ret += $postData[$prefix . '_mi'] * 60;
630 // And at last seconds...
631 $ret += $postData[$prefix . '_se'];
633 // Return calculated value
637 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
638 function createFancyTime ($stamp) {
639 // Get data array with years/months/weeks/days/...
640 $data = createTimeSelections($stamp, '', '', '', TRUE);
642 foreach ($data as $k => $v) {
644 // Value is greater than 0 "eval" data to return string
645 $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
650 // Is something there?
652 // Remove leading commata and space
653 $ret = substr($ret, 2);
656 $ret = '0 {--TIME_UNIT_SECOND--}';
659 // Return fancy time string
663 // Taken from www.php.net isInStringIgnoreCase() user comments
664 function isEmailValid ($email) {
665 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
668 if (!isset($GLOBALS[__FUNCTION__][$email])) {
669 // Check first part of email address
670 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
673 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
676 $regex = '@^' . $first . '\@' . $domain . '$@iU';
679 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
682 // Return check result
683 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
684 return $GLOBALS[__FUNCTION__][$email];;
687 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
688 function isUrlValid ($url, $compile = TRUE) {
690 $url = trim(urldecode($url));
691 //* DEBUG: */ debugOutput($url);
693 // Compile some chars out...
694 if ($compile === TRUE) {
695 $url = compileUriCode($url, FALSE, FALSE, FALSE);
697 //* DEBUG: */ debugOutput($url);
699 // Check for the extension filter
700 if (isExtensionActive('filter')) {
701 // Use the extension's filter set
702 return FILTER_VALIDATE_URL($url, FALSE);
706 * If not installed, perform a simple test. Just make it sure there is always a
707 * http:// or https:// in front of the URLs.
709 return isUrlValidSimple($url);
712 // Generate a hash for extra-security for all passwords
713 function generateHash ($plainText, $salt = '', $hash = TRUE) {
715 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
717 // Is the required extension 'sql_patches' there and a salt is not given?
718 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
719 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
720 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
721 if ($hash === TRUE) {
723 return md5($plainText);
730 // Is an arry element missing here?
731 if (!isConfigEntrySet('file_hash')) {
733 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
736 // When the salt is empty build a new one, else use the first x configured characters as the salt
738 // Build server string for more entropy
739 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
742 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
745 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
747 // Calculate number for generating the code
748 $a = time() + getConfig('_ADD') - 1;
750 // Generate SHA1 sum from modula of number and the prime number
751 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
752 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
753 $sha1 = scrambleString($sha1);
754 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
755 //* DEBUG: */ $sha1b = descrambleString($sha1);
756 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
758 // Generate the password salt string
759 $salt = substr($sha1, 0, getSaltLength());
760 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
763 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
764 $salt = substr($salt, 0, getSaltLength());
765 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
767 // Sanity check on salt
768 if (strlen($salt) != getSaltLength()) {
770 reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
774 // Generate final hash (for debug output)
775 $finalHash = $salt . sha1($salt . $plainText);
778 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
785 function scrambleString ($str) {
789 // Final check, in case of failure it will return unscrambled string
790 if (strlen($str) > 40) {
791 // The string is to long
793 } elseif (strlen($str) == 40) {
795 $scrambleNums = explode(':', getPassScramble());
797 // Generate new numbers
798 $scrambleNums = explode(':', genScrambleString(strlen($str)));
801 // Compare both lengths and abort if different
802 if (strlen($str) != count($scrambleNums)) {
806 // Scramble string here
807 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
808 for ($idx = 0; $idx < strlen($str); $idx++) {
809 // Get char on scrambled position
810 $char = substr($str, $scrambleNums[$idx], 1);
812 // Add it to final output string
816 // Return scrambled string
817 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
821 // De-scramble a string scrambled by scrambleString()
822 function descrambleString ($str) {
823 // Scramble only 40 chars long strings
824 if (strlen($str) != 40) {
828 // Load numbers from config
829 $scrambleNums = explode(':', getPassScramble());
832 if (count($scrambleNums) != 40) {
836 // Begin descrambling
837 $orig = str_repeat(' ', 40);
838 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
839 for ($idx = 0; $idx < 40; $idx++) {
840 $char = substr($str, $idx, 1);
841 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
844 // Return scrambled string
845 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
849 // Generated a "string" for scrambling
850 function genScrambleString ($len) {
851 // Prepare array for the numbers
852 $scrambleNumbers = array();
854 // First we need to setup randomized numbers from 0 to 31
855 for ($idx = 0; $idx < $len; $idx++) {
857 $rand = mt_rand(0, ($len - 1));
859 // Check for it by creating more numbers
860 while (array_key_exists($rand, $scrambleNumbers)) {
861 $rand = mt_rand(0, ($len - 1));
865 $scrambleNumbers[$rand] = $rand;
868 // So let's create the string for storing it in database
869 $scrambleString = implode(':', $scrambleNumbers);
870 return $scrambleString;
873 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
874 function encodeHashForCookie ($passHash) {
875 // Return vanilla password hash
878 // Is a secret key and master salt already initialized?
879 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
880 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
881 // Only calculate when the secret key is generated
882 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
883 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
884 // Both keys must have same length so return unencrypted
885 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
889 $newHash = ''; $start = 9;
890 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
891 for ($idx = 0; $idx < 20; $idx++) {
892 // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
893 $part1 = hexdec(substr($passHash , $start, 2));
894 $part2 = hexdec(substr(getSecretKey(), $start, 2));
896 // Default is hexadecimal of index if both are same
898 // Is part1 larger or part2 than its counter part?
899 if ($part1 > $part2) {
901 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
902 } elseif ($part2 > $part1) {
904 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
907 $mod = substr($mod, 0, 2);
908 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
909 $mod = str_pad($mod, 2, '0', STR_PAD_LEFT);
910 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
915 // Just copy it over, as the master salt is not really helpful here
916 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
921 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
925 // Fix "deleted" cookies
926 function fixDeletedCookies ($cookies) {
927 // Is this an array with entries?
928 if ((is_array($cookies)) && (count($cookies) > 0)) {
929 // Then check all cookies if they are marked as deleted!
930 foreach ($cookies as $cookieName) {
931 // Is the cookie set to "deleted"?
932 if (getSession($cookieName) == 'deleted') {
933 setSession($cookieName, '');
939 // Checks if a given apache module is loaded
940 function isApacheModuleLoaded ($apacheModule) {
941 // Check it and return result
942 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
945 // Get current theme name
946 function getCurrentTheme () {
947 // The default theme is 'default'... ;-)
950 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
951 if (isExtensionActive('theme')) {
953 $ret = getActualTheme();
954 } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) {
955 // Use value from POST data
956 $ret = postRequestElement('theme');
957 } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) {
958 // Use value from GET data
959 $ret = getRequestElement('theme');
960 } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) {
961 // Use value from GET data
962 $ret = getMailerTheme();
965 // Return theme value
969 // Generates an error code from given account status
970 function generateErrorCodeFromUserStatus ($status = '') {
971 // If no status is provided, use the default, cached
972 if ((empty($status)) && (isMember())) {
974 $status = getUserData('status');
977 // Default error code if unknown account status
978 $errorCode = getCode('ACCOUNT_UNKNOWN');
980 // Generate constant name
981 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
983 // Is the constant there?
984 if (isCodeSet($codeName)) {
986 $errorCode = getCode($codeName);
989 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
996 // Back-ported from the new ship-simu engine. :-)
997 function debug_get_printable_backtrace () {
1001 // Get and prepare backtrace for output
1002 $backtraceArray = debug_backtrace();
1003 foreach ($backtraceArray as $key => $trace) {
1004 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1005 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1006 if (!isset($trace['args'])) $trace['args'] = array();
1007 $backtrace .= '<li class="debug_list"><span class="backtrace_file">' . basename($trace['file']) . '</span>:' . $trace['line'] . ', <span class="backtrace_function">' . $trace['function'] . '(' . count($trace['args']) . ')</span></li>';
1011 $backtrace .= '</ol>';
1013 // Return the backtrace
1017 // A mail-able backtrace
1018 function debug_get_mailable_backtrace () {
1022 // Get and prepare backtrace for output
1023 $backtraceArray = debug_backtrace();
1024 foreach ($backtraceArray as $key => $trace) {
1025 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1026 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1027 if (!isset($trace['args'])) $trace['args'] = array();
1028 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1031 // Return the backtrace
1035 // Generates a ***weak*** seed
1036 function generateSeed () {
1037 return microtime(TRUE) * 100000;
1040 // Converts a message code to a human-readable message
1041 function getMessageFromErrorCode ($code) {
1042 // Default is an unknown error code
1043 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1045 // Which code is provided?
1048 // No error code is bad coding practice
1049 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1052 // All error messages
1053 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1054 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1055 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1056 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1057 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1058 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1059 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1060 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1061 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1062 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1063 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1064 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1065 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1066 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1067 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1068 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1069 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1070 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1071 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1072 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1073 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1074 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1075 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1076 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1077 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1078 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1079 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1080 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1081 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1082 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1083 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1084 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1085 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1087 case getCode('ERROR_MAILID'):
1088 if (isExtensionActive('mailid', TRUE)) {
1089 $message = '{--ERROR_CONFIRMING_MAIL--}';
1091 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1095 case getCode('EXTENSION_PROBLEM'):
1096 if (isGetRequestElementSet('ext')) {
1097 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1099 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1103 case getCode('URL_TIME_LOCK'):
1104 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1105 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1106 array(bigintval(getRequestElement('id'))), __FUNCTION__, __LINE__);
1108 // Load timestamp from last order
1109 $content = SQL_FETCHARRAY($result);
1112 SQL_FREERESULT($result);
1114 // Translate it for templates
1115 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1117 // Calculate hours...
1118 $content['hours'] = round(getUrlTlock() / 60 / 60);
1121 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1124 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1126 // Finally contruct the message
1127 $message = loadTemplate('tlock_message', TRUE, $content);
1131 // Log missing/invalid error codes
1132 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1136 // Return the message
1140 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1141 function isUrlValidSimple ($url) {
1142 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1144 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1146 // Allows http and https
1147 $http = "(http|https)+(:\/\/)";
1149 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1150 // Test double-domains (e.g. .de.vu)
1151 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1153 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1155 $dir = "((/)+([-_\.[:alnum:]])+)*";
1157 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1158 // ... and the string after and including question character
1159 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1160 // Pattern for URLs like http://url/dir/doc.html?var=value
1161 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1162 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1163 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1164 // Pattern for URLs like http://url/dir/?var=value
1165 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1166 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1167 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1168 // Pattern for URLs like http://url/dir/page.ext
1169 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1170 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1171 $pattern['ipdp'] = $http . $ip . $dir . $page;
1172 // Pattern for URLs like http://url/dir
1173 $pattern['d1d'] = $http . $domain1 . $dir;
1174 $pattern['d2d'] = $http . $domain2 . $dir;
1175 $pattern['ipd'] = $http . $ip . $dir;
1176 // Pattern for URLs like http://url/?var=value
1177 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1178 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1179 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1180 // Pattern for URLs like http://url?var=value
1181 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1182 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1183 $pattern['ipg12'] = $http . $ip . $getstring1;
1185 // Test all patterns
1187 foreach ($pattern as $key => $pat) {
1189 if (isDebugRegularExpressionEnabled()) {
1190 // @TODO Are these convertions still required?
1191 $pat = str_replace('.', '\.', $pat);
1192 $pat = str_replace('@', '\@', $pat);
1193 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1196 // Check if expression matches
1197 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1200 if ($reg === TRUE) {
1205 // Return true/false
1206 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1210 // Wtites data to a config.php-style file
1211 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1212 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0) {
1213 // Initialize some variables
1219 // Is the file there and read-/write-able?
1220 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1221 $search = 'CFG: ' . $comment;
1222 $tmp = $FQFN . '.tmp';
1224 // Open the source file
1225 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1227 // Is the resource valid?
1228 if (is_resource($fp)) {
1229 // Open temporary file
1230 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1232 // Is the resource again valid?
1233 if (is_resource($fp_tmp)) {
1234 // Mark temporary file as readable
1235 $GLOBALS['file_readable'][$tmp] = TRUE;
1238 while (!feof($fp)) {
1239 // Read from source file
1240 $line = fgets ($fp, 1024);
1242 if (isInString($search, $line)) {
1248 if ($next === $seek) {
1250 $line = $prefix . $inserted . $suffix . PHP_EOL;
1256 // Write to temp file
1257 fwrite($fp_tmp, $line);
1263 // Finished writing tmp file
1267 // Close source file
1270 if (($done === TRUE) && ($found === TRUE)) {
1271 // Copy back tmp file and delete tmp :-)
1272 copyFileVerified($tmp, $FQFN, 0644);
1273 return removeFile($tmp);
1274 } elseif ($found === FALSE) {
1275 outputHtml('<strong>CHANGE:</strong> 404!');
1277 outputHtml('<strong>TMP:</strong> UNDONE!');
1281 // File not found, not readable or writeable
1282 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1285 // An error was detected!
1289 // Debug message logger
1290 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1291 // Is debug mode enabled?
1292 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1294 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1296 // Log this message away
1297 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1301 // Handle extra values
1302 function handleExtraValues ($filterFunction, $value, $extraValue) {
1303 // Default is the value itself
1306 // Is there a special filter function?
1307 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1308 // Call-back function does not exist or is empty
1309 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1312 // Is there extra parameters here?
1313 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1314 // Put both parameters in one new array by default
1315 $args = array($value, $extraValue);
1317 // If we have an array simply use it and pre-extend it with our value
1318 if (is_array($extraValue)) {
1319 // Make the new args array
1320 $args = merge_array(array($value), $extraValue);
1323 // Call the multi-parameter call-back
1324 $ret = call_user_func_array($filterFunction, $args);
1327 if ($ret === TRUE) {
1328 // Test passed, so write direct value
1332 // One parameter call
1333 $ret = call_user_func($filterFunction, $value);
1334 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1337 if ($ret === TRUE) {
1338 // Test passed, so write direct value
1347 // Tries to determine if call-back functions and/or extra values shall be parsed
1348 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1349 // Debug mode enabled?
1350 if (isDebugModeEnabled()) {
1352 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1355 // Send data through the filter function if found
1356 if ($key === $userIdColumn[0]) {
1357 // Is the userid, we have to process it with convertZeroToNull()
1358 $entries = convertZeroToNull($entries);
1359 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1360 // Debug mode enabled?
1361 if (isDebugModeEnabled()) {
1363 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1366 // Filter function + extra value set
1367 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1369 // Debug mode enabled?
1370 if (isDebugModeEnabled()) {
1372 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1374 } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1375 // Debug mode enabled?
1376 if (isDebugModeEnabled()) {
1378 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1381 // Handle extra values
1382 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1384 // Debug mode enabled?
1385 if (isDebugModeEnabled()) {
1387 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1390 // Make sure entries is not bool, then something went wrong
1391 assert(!is_bool($entries));
1392 } elseif (!empty($filterFunctions[$search])) {
1393 // Debug mode enabled?
1394 if (isDebugModeEnabled()) {
1396 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1399 // Handle extra values
1400 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1402 // Debug mode enabled?
1403 if (isDebugModeEnabled()) {
1405 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1408 // Make sure entries is not bool, then something went wrong
1409 assert(!is_bool($entries));
1416 // Converts timestamp selections into a timestamp
1417 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1418 // Init test variable
1422 // Get last three chars
1423 $test = substr($id, -3);
1425 // Improved way of checking! :-)
1426 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1427 // Found a multi-selection for timings?
1428 $test = substr($id, 0, -3);
1429 if ((isset($postData[$test . '_ye'])) && (isset($postData[$test . '_mo'])) && (isset($postData[$test . '_we'])) && (isset($postData[$test . '_da'])) && (isset($postData[$test . '_ho'])) && (isset($postData[$test . '_mi'])) && (isset($postData[$test . '_se'])) && ($test != $test2)) {
1430 // Generate timestamp
1431 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1432 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1433 $GLOBALS['skip_config'][$test] = TRUE;
1435 // Remove data from array
1436 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1437 unset($postData[$test . '_' . $rem]);
1448 // Reverts the german decimal comma into Computer decimal dot
1449 // OPPOMENT: translateComma()
1450 function convertCommaToDot ($str) {
1451 // Default float is not a float... ;-)
1454 // Which language is selected?
1455 switch (getLanguage()) {
1456 case 'de': // German language
1457 // Remove german thousand dots first
1458 $str = str_replace('.', '', $str);
1460 // Replace german commata with decimal dot and cast it
1461 $float = (float) str_replace(',', '.', $str);
1464 default: // US and so on
1465 // Remove thousand commatas first and cast
1466 $float = (float) str_replace(',', '', $str);
1474 // Handle menu-depending failed logins and return the rendered content
1475 function handleLoginFailures ($accessLevel) {
1476 // Default output is empty ;-)
1479 // Is the session data set?
1480 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1481 // Ignore zero values
1482 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1483 // Non-guest has login failures found, get both data and prepare it for template
1484 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1486 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1487 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1491 $OUT = loadTemplate('login_failures', TRUE, $content);
1494 // Reset session data
1495 setSession('mailer_' . $accessLevel . '_failures', '');
1496 setSession('mailer_' . $accessLevel . '_last_failure', '');
1499 // Return rendered content
1504 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1506 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1508 // Shall I remove the cache file?
1509 if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1510 // Rebuild cache only in HTML output-mode
1511 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1513 $GLOBALS['cache_instance']->removeCacheFile($force);
1516 // Include file given?
1519 $inc = sprintf("inc/loader/load-%s.php", $inc);
1521 // Is the include there?
1522 if (isIncludeReadable($inc)) {
1523 // And rebuild it from scratch
1524 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1527 // Include not found
1528 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1534 // Determines the real remote address
1535 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1536 // Default is 127.0.0.1
1537 $address = '127.0.0.1';
1539 // Is a proxy in use?
1540 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1542 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1543 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1544 // Yet, another proxy
1545 $address = $_SERVER['HTTP_CLIENT_IP'];
1546 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1547 // The regular address when no proxy was used
1548 $address = $_SERVER['REMOTE_ADDR'];
1551 // This strips out the real address from proxy output
1552 if (strstr($address, ',')) {
1553 $addressArray = explode(',', $address);
1554 $address = $addressArray[0];
1557 // Return the result
1561 // Adds a bonus mail to the queue
1562 // This is a high-level function!
1563 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1564 // Use mode from data if not set and availble ;-)
1565 if ((empty($mode)) && (isset($data['mail_mode']))) {
1566 $mode = $data['mail_mode'];
1569 // Generate receiver list
1570 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1573 if (!empty($receiver)) {
1574 // Add bonus mail to queue
1575 addBonusMailToQueue(
1587 // Mail inserted into bonus pool
1588 if ($output === TRUE) {
1589 displayMessage('{--ADMIN_BONUS_SEND--}');
1591 } elseif ($output === TRUE) {
1592 // More entered than can be reached!
1593 displayMessage('{--ADMIN_MORE_SELECTED--}');
1596 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1600 // Enables the reset mode and runs it
1601 function doReset () {
1602 // Enable the reset mode
1603 $GLOBALS['reset_enabled'] = TRUE;
1606 runFilterChain('reset');
1609 // Enables the reset mode (hourly, weekly and monthly) and runs it
1610 function doHourly () {
1611 // Enable the hourly reset mode
1612 $GLOBALS['hourly_enabled'] = TRUE;
1614 // Run filters (one always!)
1615 runFilterChain('hourly');
1618 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1619 function doShutdown () {
1620 // Call the filter chain 'shutdown'
1621 runFilterChain('shutdown', NULL);
1623 // Check if not in installation phase and the link is up
1624 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1626 SQL_CLOSE(__FUNCTION__, __LINE__);
1627 } elseif (!isInstallationPhase()) {
1629 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1632 // Stop executing here
1637 function initMemberId () {
1638 $GLOBALS['member_id'] = '0';
1641 // Setter for member id
1642 function setMemberId ($memberid) {
1643 // We should not set member id to zero
1644 if ($memberid == '0') {
1645 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1649 $GLOBALS['member_id'] = bigintval($memberid);
1652 // Getter for member id or returns zero
1653 function getMemberId () {
1654 // Default member id
1657 // Is the member id set?
1658 if (isMemberIdSet()) {
1660 $memberid = $GLOBALS['member_id'];
1667 // Checks ether the member id is set
1668 function isMemberIdSet () {
1669 return (isset($GLOBALS['member_id']));
1672 // Setter for extra title
1673 function setExtraTitle ($extraTitle) {
1674 $GLOBALS['extra_title'] = $extraTitle;
1677 // Getter for extra title
1678 function getExtraTitle () {
1679 // Is the extra title set?
1680 if (!isExtraTitleSet()) {
1681 // No, then abort here
1682 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1686 return $GLOBALS['extra_title'];
1689 // Checks if the extra title is set
1690 function isExtraTitleSet () {
1691 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1695 * Reads a directory recursively by default and searches for files not matching
1696 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1697 * a whole directory.
1699 * @param $baseDir Relative base directory to PATH to scan from
1700 * @param $prefix Prefix for all positive matches (which files should be found)
1701 * @param $fileIncludeDirs whether to include directories in the final output array
1702 * @param $addBaseDir whether to add $baseDir to all array entries
1703 * @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'
1704 * @param $extension File extension for all positive matches
1705 * @param $excludePattern Regular expression to exclude more files (preg_match())
1706 * @param $recursive whether to scan recursively
1707 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1708 * @return $foundMatches All found positive matches for above criteria
1710 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
1711 // Add default entries we should always exclude
1712 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1714 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1715 // Init found includes
1716 $foundMatches = array();
1719 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1722 while ($baseFile = readdir($dirPointer)) {
1723 // Exclude '.', '..' and entries in $excludeArray automatically
1724 if (in_array($baseFile, $excludeArray, TRUE)) {
1726 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1730 // Construct include filename and FQFN
1731 $fileName = $baseDir . $baseFile;
1732 $FQFN = getPath() . $fileName;
1734 // Remove double slashes
1735 $FQFN = str_replace('//', '/', $FQFN);
1737 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1738 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1740 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1746 // Skip also files with non-matching prefix genericly
1747 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1748 // Is a redirectory so read it as well
1749 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1751 // And skip further processing
1753 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1755 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1757 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1758 // Skip wrong suffix as well
1759 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1761 } elseif (!isFileReadable($FQFN)) {
1762 // Not readable so skip it
1763 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1764 } elseif (filesize($FQFN) < 50) {
1765 // Might be deprecated
1766 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1768 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1769 // This PHP script is deprecated
1770 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1774 // Get file' extension (last 4 chars)
1775 $fileExtension = substr($baseFile, -4, 4);
1777 // Is the file a PHP script or other?
1778 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1779 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1780 // Is this a valid include file?
1781 if ($extension == '.php') {
1782 // Remove both for extension name
1783 $extName = substr($baseFile, strlen($prefix), -4);
1785 // Add file with or without base path
1786 if ($addBaseDir === TRUE) {
1788 array_push($foundMatches, $fileName);
1791 array_push($foundMatches, $baseFile);
1794 // We found .php file but should not search for them, why?
1795 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1797 } elseif ($fileExtension == $extension) {
1798 // Other, generic file found
1799 array_push($foundMatches, $fileName);
1804 closedir($dirPointer);
1807 sort($foundMatches);
1809 // Return array with include files
1810 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1811 return $foundMatches;
1814 // Checks whether $prefix is found in $fileName
1815 function isFilePrefixFound ($fileName, $prefix) {
1816 // @TODO Find a way to cache this
1817 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1820 // Maps a module name into a database table name
1821 function mapModuleToTable ($moduleName) {
1822 // Map only these, still lame code...
1823 switch ($moduleName) {
1824 case 'index': // 'index' is the guest's menu
1825 $moduleName = 'guest';
1828 case 'login': // ... and 'login' the member's menu
1829 $moduleName = 'member';
1832 // Anything else will not be mapped, silently.
1839 // Add SQL debug data to array for later output
1840 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1842 if (!isset($GLOBALS['debug_sql_available'])) {
1843 // Check it and cache it in $GLOBALS
1844 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1847 // Don't execute anything here if we don't need or ext-other is missing
1848 if ($GLOBALS['debug_sql_available'] === FALSE) {
1852 // Already executed?
1853 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1854 // Then abort here, we don't need to profile a query twice
1858 // Remeber this as profiled (or not, but we don't care here)
1859 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
1863 'num_rows' => SQL_NUMROWS($result),
1864 'affected' => SQL_AFFECTEDROWS(),
1865 'sql_str' => $sqlString,
1866 'timing' => $timing,
1867 'file' => basename($F),
1872 array_push($GLOBALS['debug_sqls'], $record);
1875 // Initializes the cache instance
1876 function initCacheInstance () {
1877 // Check for double-initialization
1878 if (isset($GLOBALS['cache_instance'])) {
1879 // This should not happen and must be fixed
1880 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1883 // Load include for CacheSystem class
1884 loadIncludeOnce('inc/classes/cachesystem.class.php');
1886 // Initialize cache system only when it's needed
1887 $GLOBALS['cache_instance'] = new CacheSystem();
1890 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1891 // Failed to initialize cache sustem
1892 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1896 // Getter for message from array or raw message
1897 function getMessageFromIndexedArray ($message, $pos, $array) {
1898 // Check if the requested message was found in array
1899 if (isset($array[$pos])) {
1900 // ... if yes then use it!
1901 $ret = $array[$pos];
1903 // ... else use default message
1911 // Convert ';' to ', ' for e.g. receiver list
1912 function convertReceivers ($old) {
1913 return str_replace(';', ', ', $old);
1916 // Get a module from filename and access level
1917 function getModuleFromFileName ($file, $accessLevel) {
1918 // Default is 'invalid';
1919 $modCheck = 'invalid';
1921 // @TODO This is still very static, rewrite it somehow
1922 switch ($accessLevel) {
1924 $modCheck = 'admin';
1930 $modCheck = getModule();
1933 default: // Unsupported file name / access level
1934 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1942 // Encodes an URL for adding session id, etc.
1943 function encodeUrl ($url, $outputMode = '0') {
1944 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
1945 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1946 // Raw output mode detected or session_name() found in URL
1950 // Is there a valid session?
1951 if ((!isSessionValid()) && (!isSpider())) {
1952 // Determine right separator
1953 $separator = '&';
1954 if (!isInString('?', $url)) {
1959 // Then add it to URL
1960 $url .= $separator . session_name() . '=' . session_id();
1964 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1966 $url = '{?URL?}/' . $url;
1970 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
1972 // Is there to decode entities?
1973 if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
1974 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
1975 // Decode them for e.g. JavaScript parts
1976 $url = decodeEntities($url);
1977 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
1981 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
1983 // Return the encoded URL
1987 // Simple check for spider
1988 function isSpider () {
1989 // Get the UA and trim it down
1990 $userAgent = trim(detectUserAgent(TRUE));
1992 // It should not be empty, if so it is better a browser
1993 if (empty($userAgent)) {
1994 // It is a browser that blocks its UA string
1999 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2002 // Function to search for the last modified file
2003 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2005 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2006 // Does it match what we are looking for? (We skip a lot files already!)
2007 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2008 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2010 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2011 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2013 // Walk through all entries
2014 foreach ($ds as $d) {
2015 // Generate proper FQFN
2016 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2018 // Is it a file and readable?
2019 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2020 if (isFileReadable($FQFN)) {
2021 // $FQFN is a readable file so extract the requested data from it
2022 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2023 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2025 // Is the file more recent?
2026 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2027 // This file is newer as the file before
2028 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2029 $last_changed['path_name'] = $FQFN;
2030 $last_changed[$lookFor] = $check;
2034 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2039 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2040 function handleFieldWithBraces ($field) {
2041 // Are there braces [] at the end?
2042 if (substr($field, -2, 2) == '[]') {
2044 * Try to find one and replace it. I do it this way to allow easy
2045 * extending of this code.
2047 foreach (array('admin_list_builder_id_value') as $key) {
2048 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2049 // Is the cache entry set?
2050 if (isset($GLOBALS[$key])) {
2052 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2055 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2065 // Converts a zero or NULL to word 'NULL'
2066 function convertZeroToNull ($number) {
2067 // Is it a valid username?
2068 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2070 $number = bigintval($number);
2072 // Is not valid or zero
2080 // Converts a NULL to zero
2081 function convertNullToZero ($number) {
2082 // Is it a valid username?
2083 if ((is_null($number)) || (empty($number)) || ($number < 1)) {
2084 // Is not valid or zero
2092 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2093 // Note: This function is cached
2094 function capitalizeUnderscoreString ($str) {
2096 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2097 // Init target string
2100 // Explode it with the underscore, but rewrite dashes to underscore before
2101 $strArray = explode('_', str_replace('-', '_', $str));
2103 // "Walk" through all elements and make them lower-case but first upper-case
2104 foreach ($strArray as $part) {
2105 // Capitalize the string part
2106 $capitalized .= firstCharUpperCase($part);
2109 // Store the converted string in cache array
2110 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2114 return $GLOBALS[__FUNCTION__][$str];
2117 // Generate admin links for mail order
2118 // mailType can be: 'mid' or 'bid'
2119 function generateAdminMailLinks ($mailType, $mailId) {
2124 // Default column for mail status is 'data_type'
2125 // @TODO Rename column data_type to e.g. mail_status
2126 $statusColumn = 'data_type';
2128 // Which mail do we have?
2129 switch ($mailType) {
2130 case 'bid': // Bonus mail
2134 case 'mid': // Member mail
2138 default: // Handle unsupported types
2139 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2140 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2144 // Is the mail type supported?
2145 if (!empty($table)) {
2146 // Query for the mail
2147 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2152 ), __FILE__, __LINE__);
2154 // Is there one entry there?
2155 if (SQL_NUMROWS($result) == 1) {
2157 $content = SQL_FETCHARRAY($result);
2159 // Add output and type
2160 $content['type'] = $mailType;
2161 $content['__output'] = '';
2164 $content = runFilterChain('generate_admin_mail_links', $content);
2167 $OUT = $content['__output'];
2171 SQL_FREERESULT($result);
2174 // Return generated HTML code
2180 * Determine if a string can represent a number in hexadecimal
2182 * @param $hex A string to check if it is hex-encoded
2183 * @return $foo True if the string is a hex, otherwise false
2184 * @author Marques Johansson
2185 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2187 function isHexadecimal ($hex) {
2188 // Make it lowercase
2189 $hex = strtolower(trim(ltrim($hex, '0')));
2191 // Fix empty strings to zero
2196 // Simply compare decode->encode result with original
2197 return ($hex == dechex(hexdec($hex)));
2201 * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2202 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2203 * response handler functions.
2205 * @param $str String to overwork
2206 * @return $str Overworked string
2208 function replaceReturnNewLine ($str) {
2209 return str_replace(array(chr(13), PHP_EOL), array('[r]', '[n]'), $str);
2212 // Converts a given string by splitting it up with given delimiter similar to
2213 // explode(), but appending the delimiter again
2214 function stringToArray ($delimiter, $string) {
2216 $strArray = array();
2218 // "Walk" through all entries
2219 foreach (explode($delimiter, $string) as $split) {
2220 // Append the delimiter and add it to the array
2221 array_push($strArray, $split . $delimiter);
2228 // Detects the prefix 'mb_' if a multi-byte string is given
2229 function detectMultiBytePrefix ($str) {
2230 // Default is without multi-byte
2233 // Detect multi-byte (strictly)
2234 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2235 // With multi-byte encoded string
2239 // Return the prefix
2243 // Searches given array for a sub-string match and returns all found keys in an array
2244 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2245 // Init array for all found keys
2248 // Now check all entries
2249 foreach ($needles as $key => $needle) {
2250 // Is there found a partial string?
2251 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2252 if (strpos($heystack, $needle, $offset) !== FALSE) {
2253 // Add the found key
2254 array_push($keys, $key);
2262 // Determines database column name from given subject and locked
2263 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2264 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2265 // Default is 'normal' points
2266 $pointsColumn = 'points';
2268 // Which points, locked or normal?
2269 if ($locked === TRUE) {
2270 $pointsColumn = 'locked_points';
2273 // Prepare array for filter
2274 $filterData = array(
2275 'subject' => $subject,
2276 'locked' => $locked,
2277 'column' => $pointsColumn
2281 $filterData = runFilterChain('determine_points_column_name', $filterData);
2283 // Extract column name from array
2284 $pointsColumn = $filterData['column'];
2287 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2288 return $pointsColumn;
2291 // Converts a boolean variable into 'Y' for true and 'N' for false
2292 function convertBooleanToYesNo ($boolean) {
2295 if ($boolean === TRUE) {
2304 // "Translates" 'true' to true and 'false' to false
2305 function convertStringToBoolean ($str) {
2306 // Debug message (to measure how often this function is called)
2307 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2310 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2311 // Trim it lower-case for validation
2312 $strTrimmed = trim(strtolower($str));
2315 if (!in_array($strTrimmed, array('true', 'false'))) {
2317 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2321 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2325 return $GLOBALS[__FUNCTION__][$str];
2329 * "Makes" a variable in given string parseable, this function will throw an
2330 * error if the first character is not a dollar sign.
2332 * @param $varString String which contains a variable
2333 * @return $return String with added single quotes for better parsing
2335 function makeParseableVariable ($varString) {
2336 // The first character must be a dollar sign
2337 if (substr($varString, 0, 1) != '$') {
2338 // Please report this
2339 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2343 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2344 // Snap them in, if [,] are there
2345 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2349 return $GLOBALS[__FUNCTION__][$varString];
2352 // "Getter" for random TAN
2353 function getRandomTan () {
2355 return mt_rand(0, 99999);
2358 // Removes any : from subject
2359 function removeDoubleDotFromSubject ($subject) {
2361 $subjectArray = explode(':', $subject);
2362 $subject = $subjectArray[0];
2363 unset($subjectArray);
2369 // Adds a given entry to the database
2370 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2377 // Set POST data generic userid
2378 setPostRequestElement('userid', getMemberId());
2380 // Call inner function
2381 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2383 // Entry has been added?
2384 if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2385 // Display success message
2386 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2388 // Display failed message
2389 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2393 // Edit rows by given id numbers
2394 function memberEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $editNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $content = array()) {
2395 // $tableName must be an array
2396 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2397 // No tableName specified
2398 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2399 } elseif (!is_array($idColumn)) {
2400 // $idColumn is no array
2401 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2402 } elseif (!is_array($userIdColumn)) {
2403 // $userIdColumn is no array
2404 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2405 } elseif (!is_array($editNow)) {
2406 // $editNow is no array
2407 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2410 // Shall we change here or list for editing?
2411 if ($editNow[0] === TRUE) {
2412 // Add generic userid field
2413 setPostRequestElement('userid', getMemberId());
2415 // Call generic change method
2416 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2419 if ($affected == countPostSelection($idColumn[0])) {
2421 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2423 // Some are still there :(
2424 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2428 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2432 // Delete rows by given id numbers
2433 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()) {
2434 // Do this only for members
2437 // $tableName must be an array
2438 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2439 // No tableName specified
2440 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2441 } elseif (!is_array($idColumn)) {
2442 // $idColumn is no array
2443 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2444 } elseif (!is_array($userIdColumn)) {
2445 // $userIdColumn is no array
2446 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2447 } elseif (!is_array($deleteNow)) {
2448 // $deleteNow is no array
2449 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2452 // Shall we delete here or list for deletion?
2453 if ($deleteNow[0] === TRUE) {
2454 // Add generic userid field
2455 setPostRequestElement('userid', getMemberId());
2457 // Call generic function
2458 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2461 if ($affected == countPostSelection($idColumn[0])) {
2463 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2465 // Some are still there :(
2466 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
2469 // List for deletion confirmation
2470 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2474 // Build a special template list
2475 // @TODO cacheFiles is not yet supported
2476 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2477 // Do this only for logged in member
2480 // Call inner (general) function
2481 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2484 // Checks whether given address is IPv4
2485 function isIp4AddressValid ($address) {
2487 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2489 $GLOBALS[__FUNCTION__][$address] = preg_match('/((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))/', $address);
2493 return $GLOBALS[__FUNCTION__][$address];
2496 // Returns the string if not empty or FALSE if empty
2497 function validateIsEmpty ($str) {
2499 $trimmed = trim($str);
2501 // Is the string empty?
2502 if (empty($trimmed)) {
2511 // ----------------------------------------------------------------------------
2512 // "Translatation" functions for points_data table
2513 // ----------------------------------------------------------------------------
2515 // Translates generically some data into a target string
2516 function translateGeneric ($messagePrefix, $data) {
2517 // Is the method null or empty?
2518 if (is_null($data)) {
2521 } elseif (empty($data)) {
2522 // Is empty (string)
2526 // Default column name is unknown
2527 $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
2529 // Construct message id
2530 $messageId = $messagePrefix . '_' . strtoupper($data);
2533 if (isMessageIdValid($messageId)) {
2534 // Then use it as message string
2535 $return = '{--' . $messageId . '--}';
2538 // Return the column name
2542 // Translates points subject to human-readable
2543 function translatePointsSubject ($subject) {
2545 $subject = removeDoubleDotFromSubject($subject);
2548 return translateGeneric('POINTS_SUBJECT', $subject);
2551 // "Translates" given points account type
2552 function translatePointsAccountType ($accountType) {
2554 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2557 // "Translates" given points "locked mode"
2558 function translatePointsLockedMode ($lockedMode) {
2560 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2563 // "Translates" given points payment method
2564 function translatePointsPaymentMethod ($paymentMethod) {
2566 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2569 // "Translates" given points account provider
2570 function translatePointsAccountProvider ($accountProvider) {
2572 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2575 // "Translates" given points notify recipient
2576 function translatePointsNotifyRecipient ($notifyRecipient) {
2578 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2581 // "Translates" given mode to a human-readable version
2582 function translatePointsMode ($pointsMode) {
2584 return translateGeneric('POINTS_MODE', $pointsMode);
2587 // "Translates" task type to a human-readable version
2588 function translateTaskType ($taskType) {
2590 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2593 //-----------------------------------------------------------------------------
2594 // Automatically re-created functions, all taken from user comments on www.php.net
2595 //-----------------------------------------------------------------------------
2596 if (!function_exists('html_entity_decode')) {
2597 // Taken from documentation on www.php.net
2598 function html_entity_decode ($string) {
2599 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2600 $trans_tbl = array_flip($trans_tbl);
2601 return strtr($string, $trans_tbl);