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?
651 if (strlen($ret) > 0) {
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)) return $str;
804 // Scramble string here
805 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
806 for ($idx = 0; $idx < strlen($str); $idx++) {
807 // Get char on scrambled position
808 $char = substr($str, $scrambleNums[$idx], 1);
810 // Add it to final output string
814 // Return scrambled string
815 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
819 // De-scramble a string scrambled by scrambleString()
820 function descrambleString ($str) {
821 // Scramble only 40 chars long strings
822 if (strlen($str) != 40) {
826 // Load numbers from config
827 $scrambleNums = explode(':', getPassScramble());
830 if (count($scrambleNums) != 40) {
834 // Begin descrambling
835 $orig = str_repeat(' ', 40);
836 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
837 for ($idx = 0; $idx < 40; $idx++) {
838 $char = substr($str, $idx, 1);
839 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
842 // Return scrambled string
843 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
847 // Generated a "string" for scrambling
848 function genScrambleString ($len) {
849 // Prepare array for the numbers
850 $scrambleNumbers = array();
852 // First we need to setup randomized numbers from 0 to 31
853 for ($idx = 0; $idx < $len; $idx++) {
855 $rand = mt_rand(0, ($len - 1));
857 // Check for it by creating more numbers
858 while (array_key_exists($rand, $scrambleNumbers)) {
859 $rand = mt_rand(0, ($len - 1));
863 $scrambleNumbers[$rand] = $rand;
866 // So let's create the string for storing it in database
867 $scrambleString = implode(':', $scrambleNumbers);
868 return $scrambleString;
871 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
872 function encodeHashForCookie ($passHash) {
873 // Return vanilla password hash
876 // Is a secret key and master salt already initialized?
877 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
878 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
879 // Only calculate when the secret key is generated
880 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
881 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
882 // Both keys must have same length so return unencrypted
883 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
887 $newHash = ''; $start = 9;
888 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
889 for ($idx = 0; $idx < 20; $idx++) {
890 // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
891 $part1 = hexdec(substr($passHash , $start, 2));
892 $part2 = hexdec(substr(getSecretKey(), $start, 2));
894 // Default is hexadecimal of index if both are same
896 // Is part1 larger or part2 than its counter part?
897 if ($part1 > $part2) {
899 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
900 } elseif ($part2 > $part1) {
902 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
905 $mod = substr($mod, 0, 2);
906 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
907 $mod = str_repeat('0', (2 - strlen($mod))) . $mod;
908 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
913 // Just copy it over, as the master salt is not really helpful here
914 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
919 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
923 // Fix "deleted" cookies
924 function fixDeletedCookies ($cookies) {
925 // Is this an array with entries?
926 if ((is_array($cookies)) && (count($cookies) > 0)) {
927 // Then check all cookies if they are marked as deleted!
928 foreach ($cookies as $cookieName) {
929 // Is the cookie set to "deleted"?
930 if (getSession($cookieName) == 'deleted') {
931 setSession($cookieName, '');
937 // Checks if a given apache module is loaded
938 function isApacheModuleLoaded ($apacheModule) {
939 // Check it and return result
940 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
943 // Get current theme name
944 function getCurrentTheme () {
945 // The default theme is 'default'... ;-)
948 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
949 if (isExtensionActive('theme')) {
951 $ret = getActualTheme();
952 } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) {
953 // Use value from POST data
954 $ret = postRequestElement('theme');
955 } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) {
956 // Use value from GET data
957 $ret = getRequestElement('theme');
958 } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) {
959 // Use value from GET data
960 $ret = getMailerTheme();
963 // Return theme value
967 // Generates an error code from given account status
968 function generateErrorCodeFromUserStatus ($status = '') {
969 // If no status is provided, use the default, cached
970 if ((empty($status)) && (isMember())) {
972 $status = getUserData('status');
975 // Default error code if unknown account status
976 $errorCode = getCode('ACCOUNT_UNKNOWN');
978 // Generate constant name
979 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
981 // Is the constant there?
982 if (isCodeSet($codeName)) {
984 $errorCode = getCode($codeName);
987 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
994 // Back-ported from the new ship-simu engine. :-)
995 function debug_get_printable_backtrace () {
999 // Get and prepare backtrace for output
1000 $backtraceArray = debug_backtrace();
1001 foreach ($backtraceArray as $key => $trace) {
1002 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1003 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1004 if (!isset($trace['args'])) $trace['args'] = array();
1005 $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>';
1009 $backtrace .= '</ol>';
1011 // Return the backtrace
1015 // A mail-able backtrace
1016 function debug_get_mailable_backtrace () {
1020 // Get and prepare backtrace for output
1021 $backtraceArray = debug_backtrace();
1022 foreach ($backtraceArray as $key => $trace) {
1023 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1024 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1025 if (!isset($trace['args'])) $trace['args'] = array();
1026 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1029 // Return the backtrace
1033 // Generates a ***weak*** seed
1034 function generateSeed () {
1035 return microtime(TRUE) * 100000;
1038 // Converts a message code to a human-readable message
1039 function getMessageFromErrorCode ($code) {
1040 // Default is an unknown error code
1041 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1043 // Which code is provided?
1046 // No error code is bad coding practice
1047 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1050 // All error messages
1051 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1052 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1053 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1054 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1055 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1056 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1057 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1058 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1059 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1060 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1061 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1062 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1063 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1064 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1065 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1066 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1067 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1068 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1069 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1070 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1071 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1072 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1073 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1074 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1075 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1076 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1077 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1078 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1079 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1080 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1081 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1082 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1083 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1085 case getCode('ERROR_MAILID'):
1086 if (isExtensionActive('mailid', TRUE)) {
1087 $message = '{--ERROR_CONFIRMING_MAIL--}';
1089 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1093 case getCode('EXTENSION_PROBLEM'):
1094 if (isGetRequestElementSet('ext')) {
1095 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1097 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1101 case getCode('URL_TIME_LOCK'):
1102 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1103 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1104 array(bigintval(getRequestElement('id'))), __FUNCTION__, __LINE__);
1106 // Load timestamp from last order
1107 $content = SQL_FETCHARRAY($result);
1110 SQL_FREERESULT($result);
1112 // Translate it for templates
1113 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1115 // Calculate hours...
1116 $content['hours'] = round(getUrlTlock() / 60 / 60);
1119 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1122 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1124 // Finally contruct the message
1125 $message = loadTemplate('tlock_message', TRUE, $content);
1129 // Log missing/invalid error codes
1130 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1134 // Return the message
1138 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1139 function isUrlValidSimple ($url) {
1140 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1142 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1144 // Allows http and https
1145 $http = "(http|https)+(:\/\/)";
1147 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1148 // Test double-domains (e.g. .de.vu)
1149 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1151 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1153 $dir = "((/)+([-_\.[:alnum:]])+)*";
1155 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1156 // ... and the string after and including question character
1157 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1158 // Pattern for URLs like http://url/dir/doc.html?var=value
1159 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1160 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1161 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1162 // Pattern for URLs like http://url/dir/?var=value
1163 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1164 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1165 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1166 // Pattern for URLs like http://url/dir/page.ext
1167 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1168 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1169 $pattern['ipdp'] = $http . $ip . $dir . $page;
1170 // Pattern for URLs like http://url/dir
1171 $pattern['d1d'] = $http . $domain1 . $dir;
1172 $pattern['d2d'] = $http . $domain2 . $dir;
1173 $pattern['ipd'] = $http . $ip . $dir;
1174 // Pattern for URLs like http://url/?var=value
1175 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1176 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1177 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1178 // Pattern for URLs like http://url?var=value
1179 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1180 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1181 $pattern['ipg12'] = $http . $ip . $getstring1;
1183 // Test all patterns
1185 foreach ($pattern as $key => $pat) {
1187 if (isDebugRegularExpressionEnabled()) {
1188 // @TODO Are these convertions still required?
1189 $pat = str_replace('.', '\.', $pat);
1190 $pat = str_replace('@', '\@', $pat);
1191 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1194 // Check if expression matches
1195 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1198 if ($reg === TRUE) {
1203 // Return true/false
1204 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1208 // Wtites data to a config.php-style file
1209 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1210 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0) {
1211 // Initialize some variables
1217 // Is the file there and read-/write-able?
1218 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1219 $search = 'CFG: ' . $comment;
1220 $tmp = $FQFN . '.tmp';
1222 // Open the source file
1223 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1225 // Is the resource valid?
1226 if (is_resource($fp)) {
1227 // Open temporary file
1228 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1230 // Is the resource again valid?
1231 if (is_resource($fp_tmp)) {
1232 // Mark temporary file as readable
1233 $GLOBALS['file_readable'][$tmp] = TRUE;
1236 while (!feof($fp)) {
1237 // Read from source file
1238 $line = fgets ($fp, 1024);
1240 if (isInString($search, $line)) {
1246 if ($next === $seek) {
1248 $line = $prefix . $inserted . $suffix . PHP_EOL;
1254 // Write to temp file
1255 fwrite($fp_tmp, $line);
1261 // Finished writing tmp file
1265 // Close source file
1268 if (($done === TRUE) && ($found === TRUE)) {
1269 // Copy back tmp file and delete tmp :-)
1270 copyFileVerified($tmp, $FQFN, 0644);
1271 return removeFile($tmp);
1272 } elseif ($found === FALSE) {
1273 outputHtml('<strong>CHANGE:</strong> 404!');
1275 outputHtml('<strong>TMP:</strong> UNDONE!');
1279 // File not found, not readable or writeable
1280 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1283 // An error was detected!
1287 // Debug message logger
1288 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1289 // Is debug mode enabled?
1290 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1292 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1294 // Log this message away
1295 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1299 // Handle extra values
1300 function handleExtraValues ($filterFunction, $value, $extraValue) {
1301 // Default is the value itself
1304 // Is there a special filter function?
1305 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1306 // Call-back function does not exist or is empty
1307 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1310 // Is there extra parameters here?
1311 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1312 // Put both parameters in one new array by default
1313 $args = array($value, $extraValue);
1315 // If we have an array simply use it and pre-extend it with our value
1316 if (is_array($extraValue)) {
1317 // Make the new args array
1318 $args = merge_array(array($value), $extraValue);
1321 // Call the multi-parameter call-back
1322 $ret = call_user_func_array($filterFunction, $args);
1325 if ($ret === TRUE) {
1326 // Test passed, so write direct value
1330 // One parameter call
1331 $ret = call_user_func($filterFunction, $value);
1332 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1335 if ($ret === TRUE) {
1336 // Test passed, so write direct value
1345 // Tries to determine if call-back functions and/or extra values shall be parsed
1346 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1347 // Debug mode enabled?
1348 if (isDebugModeEnabled()) {
1350 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1353 // Send data through the filter function if found
1354 if ($key == $userIdColumn[0]) {
1355 // Is the userid, we have to process it with convertZeroToNull()
1356 $entries = convertZeroToNull($entries);
1357 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1358 // Debug mode enabled?
1359 if (isDebugModeEnabled()) {
1361 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1364 // Filter function + extra value set
1365 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1367 // Debug mode enabled?
1368 if (isDebugModeEnabled()) {
1370 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1372 } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1373 // Debug mode enabled?
1374 if (isDebugModeEnabled()) {
1376 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1379 // Handle extra values
1380 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1382 // Debug mode enabled?
1383 if (isDebugModeEnabled()) {
1385 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1388 // Make sure entries is not bool, then something went wrong
1389 assert(!is_bool($entries));
1390 } elseif (!empty($filterFunctions[$search])) {
1391 // Debug mode enabled?
1392 if (isDebugModeEnabled()) {
1394 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1397 // Handle extra values
1398 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1400 // Debug mode enabled?
1401 if (isDebugModeEnabled()) {
1403 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1406 // Make sure entries is not bool, then something went wrong
1407 assert(!is_bool($entries));
1414 // Converts timestamp selections into a timestamp
1415 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1416 // Init test variable
1420 // Get last three chars
1421 $test = substr($id, -3);
1423 // Improved way of checking! :-)
1424 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1425 // Found a multi-selection for timings?
1426 $test = substr($id, 0, -3);
1427 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)) {
1428 // Generate timestamp
1429 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1430 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1431 $GLOBALS['skip_config'][$test] = TRUE;
1433 // Remove data from array
1434 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1435 unset($postData[$test . '_' . $rem]);
1446 // Reverts the german decimal comma into Computer decimal dot
1447 // OPPOMENT: translateComma()
1448 function convertCommaToDot ($str) {
1449 // Default float is not a float... ;-)
1452 // Which language is selected?
1453 switch (getLanguage()) {
1454 case 'de': // German language
1455 // Remove german thousand dots first
1456 $str = str_replace('.', '', $str);
1458 // Replace german commata with decimal dot and cast it
1459 $float = (float) str_replace(',', '.', $str);
1462 default: // US and so on
1463 // Remove thousand commatas first and cast
1464 $float = (float) str_replace(',', '', $str);
1472 // Handle menu-depending failed logins and return the rendered content
1473 function handleLoginFailures ($accessLevel) {
1474 // Default output is empty ;-)
1477 // Is the session data set?
1478 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1479 // Ignore zero values
1480 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1481 // Non-guest has login failures found, get both data and prepare it for template
1482 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1484 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1485 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1489 $OUT = loadTemplate('login_failures', TRUE, $content);
1492 // Reset session data
1493 setSession('mailer_' . $accessLevel . '_failures', '');
1494 setSession('mailer_' . $accessLevel . '_last_failure', '');
1497 // Return rendered content
1502 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1504 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1506 // Shall I remove the cache file?
1507 if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1508 // Rebuild cache only in HTML output-mode
1509 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1511 $GLOBALS['cache_instance']->removeCacheFile($force);
1514 // Include file given?
1517 $inc = sprintf("inc/loader/load-%s.php", $inc);
1519 // Is the include there?
1520 if (isIncludeReadable($inc)) {
1521 // And rebuild it from scratch
1522 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1525 // Include not found
1526 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1532 // Determines the real remote address
1533 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1534 // Default is 127.0.0.1
1535 $address = '127.0.0.1';
1537 // Is a proxy in use?
1538 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1540 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1541 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1542 // Yet, another proxy
1543 $address = $_SERVER['HTTP_CLIENT_IP'];
1544 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1545 // The regular address when no proxy was used
1546 $address = $_SERVER['REMOTE_ADDR'];
1549 // This strips out the real address from proxy output
1550 if (strstr($address, ',')) {
1551 $addressArray = explode(',', $address);
1552 $address = $addressArray[0];
1555 // Return the result
1559 // Adds a bonus mail to the queue
1560 // This is a high-level function!
1561 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1562 // Use mode from data if not set and availble ;-)
1563 if ((empty($mode)) && (isset($data['mail_mode']))) {
1564 $mode = $data['mail_mode'];
1567 // Generate receiver list
1568 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1571 if (!empty($receiver)) {
1572 // Add bonus mail to queue
1573 addBonusMailToQueue(
1585 // Mail inserted into bonus pool
1586 if ($output === TRUE) {
1587 displayMessage('{--ADMIN_BONUS_SEND--}');
1589 } elseif ($output === TRUE) {
1590 // More entered than can be reached!
1591 displayMessage('{--ADMIN_MORE_SELECTED--}');
1594 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1598 // Enables the reset mode and runs it
1599 function doReset () {
1600 // Enable the reset mode
1601 $GLOBALS['reset_enabled'] = TRUE;
1604 runFilterChain('reset');
1607 // Enables the reset mode (hourly, weekly and monthly) and runs it
1608 function doHourly () {
1609 // Enable the hourly reset mode
1610 $GLOBALS['hourly_enabled'] = TRUE;
1612 // Run filters (one always!)
1613 runFilterChain('hourly');
1616 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1617 function doShutdown () {
1618 // Call the filter chain 'shutdown'
1619 runFilterChain('shutdown', NULL);
1621 // Check if not in installation phase and the link is up
1622 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1624 SQL_CLOSE(__FUNCTION__, __LINE__);
1625 } elseif (!isInstallationPhase()) {
1627 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1630 // Stop executing here
1635 function initMemberId () {
1636 $GLOBALS['member_id'] = '0';
1639 // Setter for member id
1640 function setMemberId ($memberid) {
1641 // We should not set member id to zero
1642 if ($memberid == '0') {
1643 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1647 $GLOBALS['member_id'] = bigintval($memberid);
1650 // Getter for member id or returns zero
1651 function getMemberId () {
1652 // Default member id
1655 // Is the member id set?
1656 if (isMemberIdSet()) {
1658 $memberid = $GLOBALS['member_id'];
1665 // Checks ether the member id is set
1666 function isMemberIdSet () {
1667 return (isset($GLOBALS['member_id']));
1670 // Setter for extra title
1671 function setExtraTitle ($extraTitle) {
1672 $GLOBALS['extra_title'] = $extraTitle;
1675 // Getter for extra title
1676 function getExtraTitle () {
1677 // Is the extra title set?
1678 if (!isExtraTitleSet()) {
1679 // No, then abort here
1680 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1684 return $GLOBALS['extra_title'];
1687 // Checks if the extra title is set
1688 function isExtraTitleSet () {
1689 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1693 * Reads a directory recursively by default and searches for files not matching
1694 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1695 * a whole directory.
1697 * @param $baseDir Relative base directory to PATH to scan from
1698 * @param $prefix Prefix for all positive matches (which files should be found)
1699 * @param $fileIncludeDirs whether to include directories in the final output array
1700 * @param $addBaseDir whether to add $baseDir to all array entries
1701 * @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'
1702 * @param $extension File extension for all positive matches
1703 * @param $excludePattern Regular expression to exclude more files (preg_match())
1704 * @param $recursive whether to scan recursively
1705 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1706 * @return $foundMatches All found positive matches for above criteria
1708 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
1709 // Add default entries we should always exclude
1710 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1712 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1713 // Init found includes
1714 $foundMatches = array();
1717 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1720 while ($baseFile = readdir($dirPointer)) {
1721 // Exclude '.', '..' and entries in $excludeArray automatically
1722 if (in_array($baseFile, $excludeArray, TRUE)) {
1724 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1728 // Construct include filename and FQFN
1729 $fileName = $baseDir . $baseFile;
1730 $FQFN = getPath() . $fileName;
1732 // Remove double slashes
1733 $FQFN = str_replace('//', '/', $FQFN);
1735 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1736 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1738 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1744 // Skip also files with non-matching prefix genericly
1745 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1746 // Is a redirectory so read it as well
1747 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1749 // And skip further processing
1751 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1753 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1755 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1756 // Skip wrong suffix as well
1757 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1759 } elseif (!isFileReadable($FQFN)) {
1760 // Not readable so skip it
1761 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1762 } elseif (filesize($FQFN) < 50) {
1763 // Might be deprecated
1764 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1766 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1767 // This PHP script is deprecated
1768 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1772 // Get file' extension (last 4 chars)
1773 $fileExtension = substr($baseFile, -4, 4);
1775 // Is the file a PHP script or other?
1776 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1777 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1778 // Is this a valid include file?
1779 if ($extension == '.php') {
1780 // Remove both for extension name
1781 $extName = substr($baseFile, strlen($prefix), -4);
1783 // Add file with or without base path
1784 if ($addBaseDir === TRUE) {
1786 array_push($foundMatches, $fileName);
1789 array_push($foundMatches, $baseFile);
1792 // We found .php file but should not search for them, why?
1793 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1795 } elseif ($fileExtension == $extension) {
1796 // Other, generic file found
1797 array_push($foundMatches, $fileName);
1802 closedir($dirPointer);
1805 sort($foundMatches);
1807 // Return array with include files
1808 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1809 return $foundMatches;
1812 // Checks whether $prefix is found in $fileName
1813 function isFilePrefixFound ($fileName, $prefix) {
1814 // @TODO Find a way to cache this
1815 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1818 // Maps a module name into a database table name
1819 function mapModuleToTable ($moduleName) {
1820 // Map only these, still lame code...
1821 switch ($moduleName) {
1822 case 'index': // 'index' is the guest's menu
1823 $moduleName = 'guest';
1826 case 'login': // ... and 'login' the member's menu
1827 $moduleName = 'member';
1830 // Anything else will not be mapped, silently.
1837 // Add SQL debug data to array for later output
1838 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1840 if (!isset($GLOBALS['debug_sql_available'])) {
1841 // Check it and cache it in $GLOBALS
1842 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1845 // Don't execute anything here if we don't need or ext-other is missing
1846 if ($GLOBALS['debug_sql_available'] === FALSE) {
1850 // Already executed?
1851 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1852 // Then abort here, we don't need to profile a query twice
1856 // Remeber this as profiled (or not, but we don't care here)
1857 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
1861 'num_rows' => SQL_NUMROWS($result),
1862 'affected' => SQL_AFFECTEDROWS(),
1863 'sql_str' => $sqlString,
1864 'timing' => $timing,
1865 'file' => basename($F),
1870 array_push($GLOBALS['debug_sqls'], $record);
1873 // Initializes the cache instance
1874 function initCacheInstance () {
1875 // Check for double-initialization
1876 if (isset($GLOBALS['cache_instance'])) {
1877 // This should not happen and must be fixed
1878 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1881 // Load include for CacheSystem class
1882 loadIncludeOnce('inc/classes/cachesystem.class.php');
1884 // Initialize cache system only when it's needed
1885 $GLOBALS['cache_instance'] = new CacheSystem();
1888 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1889 // Failed to initialize cache sustem
1890 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1894 // Getter for message from array or raw message
1895 function getMessageFromIndexedArray ($message, $pos, $array) {
1896 // Check if the requested message was found in array
1897 if (isset($array[$pos])) {
1898 // ... if yes then use it!
1899 $ret = $array[$pos];
1901 // ... else use default message
1909 // Convert ';' to ', ' for e.g. receiver list
1910 function convertReceivers ($old) {
1911 return str_replace(';', ', ', $old);
1914 // Get a module from filename and access level
1915 function getModuleFromFileName ($file, $accessLevel) {
1916 // Default is 'invalid';
1917 $modCheck = 'invalid';
1919 // @TODO This is still very static, rewrite it somehow
1920 switch ($accessLevel) {
1922 $modCheck = 'admin';
1928 $modCheck = getModule();
1931 default: // Unsupported file name / access level
1932 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1940 // Encodes an URL for adding session id, etc.
1941 function encodeUrl ($url, $outputMode = '0') {
1942 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
1943 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1944 // Raw output mode detected or session_name() found in URL
1948 // Is there a valid session?
1949 if ((!isSessionValid()) && (!isSpider())) {
1950 // Determine right separator
1951 $separator = '&';
1952 if (!isInString('?', $url)) {
1957 // Then add it to URL
1958 $url .= $separator . session_name() . '=' . session_id();
1962 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1964 $url = '{?URL?}/' . $url;
1968 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
1970 // Is there to decode entities?
1971 if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
1972 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
1973 // Decode them for e.g. JavaScript parts
1974 $url = decodeEntities($url);
1975 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
1979 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
1981 // Return the encoded URL
1985 // Simple check for spider
1986 function isSpider () {
1987 // Get the UA and trim it down
1988 $userAgent = trim(detectUserAgent(TRUE));
1990 // It should not be empty, if so it is better a browser
1991 if (empty($userAgent)) {
1992 // It is a browser that blocks its UA string
1997 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2000 // Function to search for the last modified file
2001 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2003 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2004 // Does it match what we are looking for? (We skip a lot files already!)
2005 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2006 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2008 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2009 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2011 // Walk through all entries
2012 foreach ($ds as $d) {
2013 // Generate proper FQFN
2014 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2016 // Is it a file and readable?
2017 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2018 if (isFileReadable($FQFN)) {
2019 // $FQFN is a readable file so extract the requested data from it
2020 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2021 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2023 // Is the file more recent?
2024 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2025 // This file is newer as the file before
2026 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2027 $last_changed['path_name'] = $FQFN;
2028 $last_changed[$lookFor] = $check;
2032 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2037 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2038 function handleFieldWithBraces ($field) {
2039 // Are there braces [] at the end?
2040 if (substr($field, -2, 2) == '[]') {
2042 * Try to find one and replace it. I do it this way to allow easy
2043 * extending of this code.
2045 foreach (array('admin_list_builder_id_value') as $key) {
2046 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2047 // Is the cache entry set?
2048 if (isset($GLOBALS[$key])) {
2050 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2053 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2063 // Converts a zero or NULL to word 'NULL'
2064 function convertZeroToNull ($number) {
2065 // Is it a valid username?
2066 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2068 $number = bigintval($number);
2070 // Is not valid or zero
2078 // Converts a NULL to zero
2079 function convertNullToZero ($number) {
2080 // Is it a valid username?
2081 if ((is_null($number)) || (empty($number)) || ($number < 1)) {
2082 // Is not valid or zero
2090 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2091 // Note: This function is cached
2092 function capitalizeUnderscoreString ($str) {
2094 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2095 // Init target string
2098 // Explode it with the underscore, but rewrite dashes to underscore before
2099 $strArray = explode('_', str_replace('-', '_', $str));
2101 // "Walk" through all elements and make them lower-case but first upper-case
2102 foreach ($strArray as $part) {
2103 // Capitalize the string part
2104 $capitalized .= firstCharUpperCase($part);
2107 // Store the converted string in cache array
2108 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2112 return $GLOBALS[__FUNCTION__][$str];
2115 // Generate admin links for mail order
2116 // mailType can be: 'mid' or 'bid'
2117 function generateAdminMailLinks ($mailType, $mailId) {
2122 // Default column for mail status is 'data_type'
2123 // @TODO Rename column data_type to e.g. mail_status
2124 $statusColumn = 'data_type';
2126 // Which mail do we have?
2127 switch ($mailType) {
2128 case 'bid': // Bonus mail
2132 case 'mid': // Member mail
2136 default: // Handle unsupported types
2137 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2138 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2142 // Is the mail type supported?
2143 if (!empty($table)) {
2144 // Query for the mail
2145 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2150 ), __FILE__, __LINE__);
2152 // Is there one entry there?
2153 if (SQL_NUMROWS($result) == 1) {
2155 $content = SQL_FETCHARRAY($result);
2157 // Add output and type
2158 $content['type'] = $mailType;
2159 $content['__output'] = '';
2162 $content = runFilterChain('generate_admin_mail_links', $content);
2165 $OUT = $content['__output'];
2169 SQL_FREERESULT($result);
2172 // Return generated HTML code
2178 * Determine if a string can represent a number in hexadecimal
2180 * @param $hex A string to check if it is hex-encoded
2181 * @return $foo True if the string is a hex, otherwise false
2182 * @author Marques Johansson
2183 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2185 function isHexadecimal ($hex) {
2186 // Make it lowercase
2187 $hex = strtolower(trim(ltrim($hex, '0')));
2189 // Fix empty strings to zero
2194 // Simply compare decode->encode result with original
2195 return ($hex == dechex(hexdec($hex)));
2199 * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2200 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2201 * response handler functions.
2203 * @param $str String to overwork
2204 * @return $str Overworked string
2206 function replaceReturnNewLine ($str) {
2207 return str_replace(array(chr(13), PHP_EOL), array('[r]', '[n]'), $str);
2210 // Converts a given string by splitting it up with given delimiter similar to
2211 // explode(), but appending the delimiter again
2212 function stringToArray ($delimiter, $string) {
2214 $strArray = array();
2216 // "Walk" through all entries
2217 foreach (explode($delimiter, $string) as $split) {
2218 // Append the delimiter and add it to the array
2219 array_push($strArray, $split . $delimiter);
2226 // Detects the prefix 'mb_' if a multi-byte string is given
2227 function detectMultiBytePrefix ($str) {
2228 // Default is without multi-byte
2231 // Detect multi-byte (strictly)
2232 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2233 // With multi-byte encoded string
2237 // Return the prefix
2241 // Searches given array for a sub-string match and returns all found keys in an array
2242 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2243 // Init array for all found keys
2246 // Now check all entries
2247 foreach ($needles as $key => $needle) {
2248 // Is there found a partial string?
2249 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2250 if (strpos($heystack, $needle, $offset) !== FALSE) {
2251 // Add the found key
2252 array_push($keys, $key);
2260 // Determines database column name from given subject and locked
2261 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2262 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2263 // Default is 'normal' points
2264 $pointsColumn = 'points';
2266 // Which points, locked or normal?
2267 if ($locked === TRUE) {
2268 $pointsColumn = 'locked_points';
2271 // Prepare array for filter
2272 $filterData = array(
2273 'subject' => $subject,
2274 'locked' => $locked,
2275 'column' => $pointsColumn
2279 $filterData = runFilterChain('determine_points_column_name', $filterData);
2281 // Extract column name from array
2282 $pointsColumn = $filterData['column'];
2285 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2286 return $pointsColumn;
2289 // Converts a boolean variable into 'Y' for true and 'N' for false
2290 function convertBooleanToYesNo ($boolean) {
2293 if ($boolean === TRUE) {
2302 // "Translates" 'true' to true and 'false' to false
2303 function convertStringToBoolean ($str) {
2304 // Debug message (to measure how often this function is called)
2305 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2308 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2309 // Trim it lower-case for validation
2310 $strTrimmed = trim(strtolower($str));
2313 if (!in_array($strTrimmed, array('true', 'false'))) {
2315 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2319 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2323 return $GLOBALS[__FUNCTION__][$str];
2327 * "Makes" a variable in given string parseable, this function will throw an
2328 * error if the first character is not a dollar sign.
2330 * @param $varString String which contains a variable
2331 * @return $return String with added single quotes for better parsing
2333 function makeParseableVariable ($varString) {
2334 // The first character must be a dollar sign
2335 if (substr($varString, 0, 1) != '$') {
2336 // Please report this
2337 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2341 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2342 // Snap them in, if [,] are there
2343 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2347 return $GLOBALS[__FUNCTION__][$varString];
2350 // "Getter" for random TAN
2351 function getRandomTan () {
2353 return mt_rand(0, 99999);
2356 // Removes any : from subject
2357 function removeDoubleDotFromSubject ($subject) {
2359 $subjectArray = explode(':', $subject);
2360 $subject = $subjectArray[0];
2361 unset($subjectArray);
2367 // Adds a given entry to the database
2368 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2375 // Set POST data generic userid
2376 setPostRequestElement('userid', getMemberId());
2378 // Call inner function
2379 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2381 // Entry has been added?
2382 if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2383 // Display success message
2384 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2386 // Display failed message
2387 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2391 // Edit rows by given id numbers
2392 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()) {
2393 // $tableName must be an array
2394 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2395 // No tableName specified
2396 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2397 } elseif (!is_array($idColumn)) {
2398 // $idColumn is no array
2399 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2400 } elseif (!is_array($userIdColumn)) {
2401 // $userIdColumn is no array
2402 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2403 } elseif (!is_array($editNow)) {
2404 // $editNow is no array
2405 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2408 // Shall we change here or list for editing?
2409 if ($editNow[0] === TRUE) {
2410 // Add generic userid field
2411 setPostRequestElement('userid', getMemberId());
2413 // Call generic change method
2414 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2417 if ($affected == countPostSelection($idColumn[0])) {
2419 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2421 // Some are still there :(
2422 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2426 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2430 // Delete rows by given id numbers
2431 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()) {
2432 // Do this only for members
2435 // $tableName must be an array
2436 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2437 // No tableName specified
2438 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2439 } elseif (!is_array($idColumn)) {
2440 // $idColumn is no array
2441 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2442 } elseif (!is_array($userIdColumn)) {
2443 // $userIdColumn is no array
2444 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2445 } elseif (!is_array($deleteNow)) {
2446 // $deleteNow is no array
2447 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2450 // Shall we delete here or list for deletion?
2451 if ($deleteNow[0] === TRUE) {
2452 // Add generic userid field
2453 setPostRequestElement('userid', getMemberId());
2455 // Call generic function
2456 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2459 if ($affected == countPostSelection($idColumn[0])) {
2461 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2463 // Some are still there :(
2464 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
2467 // List for deletion confirmation
2468 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2472 // Build a special template list
2473 // @TODO cacheFiles is not yet supported
2474 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2475 // Do this only for logged in member
2478 // Call inner (general) function
2479 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2482 // Checks whether given address is IPv4
2483 function isIp4AddressValid ($address) {
2485 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2487 $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);
2491 return $GLOBALS[__FUNCTION__][$address];
2494 // Returns the string if not empty or FALSE if empty
2495 function validateIsEmpty ($str) {
2497 $trimmed = trim($str);
2499 // Is the string empty?
2500 if (empty($trimmed)) {
2509 // ----------------------------------------------------------------------------
2510 // "Translatation" functions for points_data table
2511 // ----------------------------------------------------------------------------
2513 // Translates generically some data into a target string
2514 function translateGeneric ($messagePrefix, $data) {
2515 // Is the method null or empty?
2516 if (is_null($data)) {
2519 } elseif (empty($data)) {
2520 // Is empty (string)
2524 // Default column name is unknown
2525 $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
2527 // Construct message id
2528 $messageId = $messagePrefix . '_' . strtoupper($data);
2531 if (isMessageIdValid($messageId)) {
2532 // Then use it as message string
2533 $return = '{--' . $messageId . '--}';
2536 // Return the column name
2540 // Translates points subject to human-readable
2541 function translatePointsSubject ($subject) {
2543 $subject = removeDoubleDotFromSubject($subject);
2546 return translateGeneric('POINTS_SUBJECT', $subject);
2549 // "Translates" given points account type
2550 function translatePointsAccountType ($accountType) {
2552 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2555 // "Translates" given points "locked mode"
2556 function translatePointsLockedMode ($lockedMode) {
2558 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2561 // "Translates" given points payment method
2562 function translatePointsPaymentMethod ($paymentMethod) {
2564 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2567 // "Translates" given points account provider
2568 function translatePointsAccountProvider ($accountProvider) {
2570 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2573 // "Translates" given points notify recipient
2574 function translatePointsNotifyRecipient ($notifyRecipient) {
2576 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2579 // "Translates" given mode to a human-readable version
2580 function translatePointsMode ($pointsMode) {
2582 return translateGeneric('POINTS_MODE', $pointsMode);
2585 // "Translates" task type to a human-readable version
2586 function translateTaskType ($taskType) {
2588 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2591 //-----------------------------------------------------------------------------
2592 // Automatically re-created functions, all taken from user comments on www.php.net
2593 //-----------------------------------------------------------------------------
2594 if (!function_exists('html_entity_decode')) {
2595 // Taken from documentation on www.php.net
2596 function html_entity_decode ($string) {
2597 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2598 $trans_tbl = array_flip($trans_tbl);
2599 return strtr($string, $trans_tbl);