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 // $search shall not be NULL
1348 assert(!is_null($search));
1350 // Debug mode enabled?
1351 if (isDebugModeEnabled()) {
1353 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1356 // Send data through the filter function if found
1357 if ($key === $userIdColumn[0]) {
1358 // Is the userid, we have to process it with convertZeroToNull()
1359 $entries = convertZeroToNull($entries);
1360 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1361 // Debug mode enabled?
1362 if (isDebugModeEnabled()) {
1364 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1367 // Filter function + extra value set
1368 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1370 // Debug mode enabled?
1371 if (isDebugModeEnabled()) {
1373 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1375 } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1376 // Debug mode enabled?
1377 if (isDebugModeEnabled()) {
1379 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1382 // Handle extra values
1383 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1385 // Debug mode enabled?
1386 if (isDebugModeEnabled()) {
1388 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1391 // Make sure entries is not bool, then something went wrong
1392 assert(!is_bool($entries));
1393 } elseif (!empty($filterFunctions[$search])) {
1394 // Debug mode enabled?
1395 if (isDebugModeEnabled()) {
1397 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1400 // Handle extra values
1401 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1403 // Debug mode enabled?
1404 if (isDebugModeEnabled()) {
1406 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1409 // Make sure entries is not bool, then something went wrong
1410 assert(!is_bool($entries));
1417 // Converts timestamp selections into a timestamp
1418 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1419 // Init test variable
1423 // Get last three chars
1424 $test = substr($id, -3);
1426 // Improved way of checking! :-)
1427 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1428 // Found a multi-selection for timings?
1429 $test = substr($id, 0, -3);
1430 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)) {
1431 // Generate timestamp
1432 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1433 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1434 $GLOBALS['skip_config'][$test] = TRUE;
1436 // Remove data from array
1437 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1438 unset($postData[$test . '_' . $rem]);
1449 // Reverts the german decimal comma into Computer decimal dot
1450 // OPPOMENT: translateComma()
1451 function convertCommaToDot ($str) {
1452 // Default float is not a float... ;-)
1455 // Which language is selected?
1456 switch (getLanguage()) {
1457 case 'de': // German language
1458 // Remove german thousand dots first
1459 $str = str_replace('.', '', $str);
1461 // Replace german commata with decimal dot and cast it
1462 $float = (float) str_replace(',', '.', $str);
1465 default: // US and so on
1466 // Remove thousand commatas first and cast
1467 $float = (float) str_replace(',', '', $str);
1475 // Handle menu-depending failed logins and return the rendered content
1476 function handleLoginFailures ($accessLevel) {
1477 // Default output is empty ;-)
1480 // Is the session data set?
1481 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1482 // Ignore zero values
1483 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1484 // Non-guest has login failures found, get both data and prepare it for template
1485 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1487 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1488 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1492 $OUT = loadTemplate('login_failures', TRUE, $content);
1495 // Reset session data
1496 setSession('mailer_' . $accessLevel . '_failures', '');
1497 setSession('mailer_' . $accessLevel . '_last_failure', '');
1500 // Return rendered content
1505 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1507 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1509 // Shall I remove the cache file?
1510 if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1511 // Rebuild cache only in HTML output-mode
1512 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1514 $GLOBALS['cache_instance']->removeCacheFile($force);
1517 // Include file given?
1520 $inc = sprintf("inc/loader/load-%s.php", $inc);
1522 // Is the include there?
1523 if (isIncludeReadable($inc)) {
1524 // And rebuild it from scratch
1525 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1528 // Include not found
1529 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1535 // Determines the real remote address
1536 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1537 // Default is 127.0.0.1
1538 $address = '127.0.0.1';
1540 // Is a proxy in use?
1541 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1543 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1544 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1545 // Yet, another proxy
1546 $address = $_SERVER['HTTP_CLIENT_IP'];
1547 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1548 // The regular address when no proxy was used
1549 $address = $_SERVER['REMOTE_ADDR'];
1552 // This strips out the real address from proxy output
1553 if (strstr($address, ',')) {
1554 $addressArray = explode(',', $address);
1555 $address = $addressArray[0];
1558 // Return the result
1562 // Adds a bonus mail to the queue
1563 // This is a high-level function!
1564 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1565 // Use mode from data if not set and availble ;-)
1566 if ((empty($mode)) && (isset($data['mail_mode']))) {
1567 $mode = $data['mail_mode'];
1570 // Generate receiver list
1571 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1574 if (!empty($receiver)) {
1575 // Add bonus mail to queue
1576 addBonusMailToQueue(
1588 // Mail inserted into bonus pool
1589 if ($output === TRUE) {
1590 displayMessage('{--ADMIN_BONUS_SEND--}');
1592 } elseif ($output === TRUE) {
1593 // More entered than can be reached!
1594 displayMessage('{--ADMIN_MORE_SELECTED--}');
1597 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1601 // Enables the reset mode and runs it
1602 function doReset () {
1603 // Enable the reset mode
1604 $GLOBALS['reset_enabled'] = TRUE;
1607 runFilterChain('reset');
1610 // Enables the reset mode (hourly, weekly and monthly) and runs it
1611 function doHourly () {
1612 // Enable the hourly reset mode
1613 $GLOBALS['hourly_enabled'] = TRUE;
1615 // Run filters (one always!)
1616 runFilterChain('hourly');
1619 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1620 function doShutdown () {
1621 // Call the filter chain 'shutdown'
1622 runFilterChain('shutdown', NULL);
1624 // Check if not in installation phase and the link is up
1625 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1627 SQL_CLOSE(__FUNCTION__, __LINE__);
1628 } elseif (!isInstallationPhase()) {
1630 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1633 // Stop executing here
1638 function initMemberId () {
1639 $GLOBALS['member_id'] = '0';
1642 // Setter for member id
1643 function setMemberId ($memberid) {
1644 // We should not set member id to zero
1645 if ($memberid == '0') {
1646 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1650 $GLOBALS['member_id'] = bigintval($memberid);
1653 // Getter for member id or returns zero
1654 function getMemberId () {
1655 // Default member id
1658 // Is the member id set?
1659 if (isMemberIdSet()) {
1661 $memberid = $GLOBALS['member_id'];
1668 // Checks ether the member id is set
1669 function isMemberIdSet () {
1670 return (isset($GLOBALS['member_id']));
1673 // Setter for extra title
1674 function setExtraTitle ($extraTitle) {
1675 $GLOBALS['extra_title'] = $extraTitle;
1678 // Getter for extra title
1679 function getExtraTitle () {
1680 // Is the extra title set?
1681 if (!isExtraTitleSet()) {
1682 // No, then abort here
1683 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1687 return $GLOBALS['extra_title'];
1690 // Checks if the extra title is set
1691 function isExtraTitleSet () {
1692 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1696 * Reads a directory recursively by default and searches for files not matching
1697 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1698 * a whole directory.
1700 * @param $baseDir Relative base directory to PATH to scan from
1701 * @param $prefix Prefix for all positive matches (which files should be found)
1702 * @param $fileIncludeDirs whether to include directories in the final output array
1703 * @param $addBaseDir whether to add $baseDir to all array entries
1704 * @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'
1705 * @param $extension File extension for all positive matches
1706 * @param $excludePattern Regular expression to exclude more files (preg_match())
1707 * @param $recursive whether to scan recursively
1708 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1709 * @return $foundMatches All found positive matches for above criteria
1711 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
1712 // Add default entries we should always exclude
1713 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1715 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1716 // Init found includes
1717 $foundMatches = array();
1720 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1723 while ($baseFile = readdir($dirPointer)) {
1724 // Exclude '.', '..' and entries in $excludeArray automatically
1725 if (in_array($baseFile, $excludeArray, TRUE)) {
1727 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1731 // Construct include filename and FQFN
1732 $fileName = $baseDir . $baseFile;
1733 $FQFN = getPath() . $fileName;
1735 // Remove double slashes
1736 $FQFN = str_replace('//', '/', $FQFN);
1738 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1739 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1741 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1747 // Skip also files with non-matching prefix genericly
1748 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1749 // Is a redirectory so read it as well
1750 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1752 // And skip further processing
1754 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1756 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1758 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1759 // Skip wrong suffix as well
1760 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1762 } elseif (!isFileReadable($FQFN)) {
1763 // Not readable so skip it
1764 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1765 } elseif (filesize($FQFN) < 50) {
1766 // Might be deprecated
1767 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1769 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1770 // This PHP script is deprecated
1771 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1775 // Get file' extension (last 4 chars)
1776 $fileExtension = substr($baseFile, -4, 4);
1778 // Is the file a PHP script or other?
1779 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1780 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1781 // Is this a valid include file?
1782 if ($extension == '.php') {
1783 // Remove both for extension name
1784 $extName = substr($baseFile, strlen($prefix), -4);
1786 // Add file with or without base path
1787 if ($addBaseDir === TRUE) {
1789 array_push($foundMatches, $fileName);
1792 array_push($foundMatches, $baseFile);
1795 // We found .php file but should not search for them, why?
1796 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1798 } elseif ($fileExtension == $extension) {
1799 // Other, generic file found
1800 array_push($foundMatches, $fileName);
1805 closedir($dirPointer);
1808 sort($foundMatches);
1810 // Return array with include files
1811 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1812 return $foundMatches;
1815 // Checks whether $prefix is found in $fileName
1816 function isFilePrefixFound ($fileName, $prefix) {
1817 // @TODO Find a way to cache this
1818 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1821 // Maps a module name into a database table name
1822 function mapModuleToTable ($moduleName) {
1823 // Map only these, still lame code...
1824 switch ($moduleName) {
1825 case 'index': // 'index' is the guest's menu
1826 $moduleName = 'guest';
1829 case 'login': // ... and 'login' the member's menu
1830 $moduleName = 'member';
1833 // Anything else will not be mapped, silently.
1840 // Add SQL debug data to array for later output
1841 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1843 if (!isset($GLOBALS['debug_sql_available'])) {
1844 // Check it and cache it in $GLOBALS
1845 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1848 // Don't execute anything here if we don't need or ext-other is missing
1849 if ($GLOBALS['debug_sql_available'] === FALSE) {
1853 // Already executed?
1854 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1855 // Then abort here, we don't need to profile a query twice
1859 // Remeber this as profiled (or not, but we don't care here)
1860 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
1864 'num_rows' => SQL_NUMROWS($result),
1865 'affected' => SQL_AFFECTEDROWS(),
1866 'sql_str' => $sqlString,
1867 'timing' => $timing,
1868 'file' => basename($F),
1873 array_push($GLOBALS['debug_sqls'], $record);
1876 // Initializes the cache instance
1877 function initCacheInstance () {
1878 // Check for double-initialization
1879 if (isset($GLOBALS['cache_instance'])) {
1880 // This should not happen and must be fixed
1881 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1884 // Load include for CacheSystem class
1885 loadIncludeOnce('inc/classes/cachesystem.class.php');
1887 // Initialize cache system only when it's needed
1888 $GLOBALS['cache_instance'] = new CacheSystem();
1891 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1892 // Failed to initialize cache sustem
1893 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1897 // Getter for message from array or raw message
1898 function getMessageFromIndexedArray ($message, $pos, $array) {
1899 // Check if the requested message was found in array
1900 if (isset($array[$pos])) {
1901 // ... if yes then use it!
1902 $ret = $array[$pos];
1904 // ... else use default message
1912 // Convert ';' to ', ' for e.g. receiver list
1913 function convertReceivers ($old) {
1914 return str_replace(';', ', ', $old);
1917 // Get a module from filename and access level
1918 function getModuleFromFileName ($file, $accessLevel) {
1919 // Default is 'invalid';
1920 $modCheck = 'invalid';
1922 // @TODO This is still very static, rewrite it somehow
1923 switch ($accessLevel) {
1925 $modCheck = 'admin';
1931 $modCheck = getModule();
1934 default: // Unsupported file name / access level
1935 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1943 // Encodes an URL for adding session id, etc.
1944 function encodeUrl ($url, $outputMode = '0') {
1945 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
1946 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1947 // Raw output mode detected or session_name() found in URL
1951 // Is there a valid session?
1952 if ((!isSessionValid()) && (!isSpider())) {
1953 // Determine right separator
1954 $separator = '&';
1955 if (!isInString('?', $url)) {
1960 // Then add it to URL
1961 $url .= $separator . session_name() . '=' . session_id();
1965 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1967 $url = '{?URL?}/' . $url;
1971 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
1973 // Is there to decode entities?
1974 if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
1975 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
1976 // Decode them for e.g. JavaScript parts
1977 $url = decodeEntities($url);
1978 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
1982 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
1984 // Return the encoded URL
1988 // Simple check for spider
1989 function isSpider () {
1990 // Get the UA and trim it down
1991 $userAgent = trim(detectUserAgent(TRUE));
1993 // It should not be empty, if so it is better a browser
1994 if (empty($userAgent)) {
1995 // It is a browser that blocks its UA string
2000 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2003 // Function to search for the last modified file
2004 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2006 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2007 // Does it match what we are looking for? (We skip a lot files already!)
2008 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2009 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2011 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2012 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2014 // Walk through all entries
2015 foreach ($ds as $d) {
2016 // Generate proper FQFN
2017 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2019 // Is it a file and readable?
2020 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2021 if (isFileReadable($FQFN)) {
2022 // $FQFN is a readable file so extract the requested data from it
2023 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2024 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2026 // Is the file more recent?
2027 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2028 // This file is newer as the file before
2029 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2030 $last_changed['path_name'] = $FQFN;
2031 $last_changed[$lookFor] = $check;
2035 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2040 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2041 function handleFieldWithBraces ($field) {
2042 // Are there braces [] at the end?
2043 if (substr($field, -2, 2) == '[]') {
2045 * Try to find one and replace it. I do it this way to allow easy
2046 * extending of this code.
2048 foreach (array('admin_list_builder_id_value') as $key) {
2049 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2050 // Is the cache entry set?
2051 if (isset($GLOBALS[$key])) {
2053 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2056 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2066 // Converts a zero or NULL to word 'NULL'
2067 function convertZeroToNull ($number) {
2068 // Is it a valid username?
2069 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2071 $number = bigintval($number);
2073 // Is not valid or zero
2081 // Converts a NULL to zero
2082 function convertNullToZero ($number) {
2083 // Is it a valid username?
2084 if ((is_null($number)) || (empty($number)) || ($number < 1)) {
2085 // Is not valid or zero
2093 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2094 // Note: This function is cached
2095 function capitalizeUnderscoreString ($str) {
2097 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2098 // Init target string
2101 // Explode it with the underscore, but rewrite dashes to underscore before
2102 $strArray = explode('_', str_replace('-', '_', $str));
2104 // "Walk" through all elements and make them lower-case but first upper-case
2105 foreach ($strArray as $part) {
2106 // Capitalize the string part
2107 $capitalized .= firstCharUpperCase($part);
2110 // Store the converted string in cache array
2111 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2115 return $GLOBALS[__FUNCTION__][$str];
2118 // Generate admin links for mail order
2119 // mailType can be: 'mid' or 'bid'
2120 function generateAdminMailLinks ($mailType, $mailId) {
2125 // Default column for mail status is 'data_type'
2126 // @TODO Rename column data_type to e.g. mail_status
2127 $statusColumn = 'data_type';
2129 // Which mail do we have?
2130 switch ($mailType) {
2131 case 'bid': // Bonus mail
2135 case 'mid': // Member mail
2139 default: // Handle unsupported types
2140 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2141 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2145 // Is the mail type supported?
2146 if (!empty($table)) {
2147 // Query for the mail
2148 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2153 ), __FILE__, __LINE__);
2155 // Is there one entry there?
2156 if (SQL_NUMROWS($result) == 1) {
2158 $content = SQL_FETCHARRAY($result);
2160 // Add output and type
2161 $content['type'] = $mailType;
2162 $content['__output'] = '';
2165 $content = runFilterChain('generate_admin_mail_links', $content);
2168 $OUT = $content['__output'];
2172 SQL_FREERESULT($result);
2175 // Return generated HTML code
2181 * Determine if a string can represent a number in hexadecimal
2183 * @param $hex A string to check if it is hex-encoded
2184 * @return $foo True if the string is a hex, otherwise false
2185 * @author Marques Johansson
2186 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2188 function isHexadecimal ($hex) {
2189 // Make it lowercase
2190 $hex = strtolower(trim(ltrim($hex, '0')));
2192 // Fix empty strings to zero
2197 // Simply compare decode->encode result with original
2198 return ($hex == dechex(hexdec($hex)));
2202 * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2203 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2204 * response handler functions.
2206 * @param $str String to overwork
2207 * @return $str Overworked string
2209 function replaceReturnNewLine ($str) {
2210 return str_replace(array(chr(13), PHP_EOL), array('[r]', '[n]'), $str);
2213 // Converts a given string by splitting it up with given delimiter similar to
2214 // explode(), but appending the delimiter again
2215 function stringToArray ($delimiter, $string) {
2217 $strArray = array();
2219 // "Walk" through all entries
2220 foreach (explode($delimiter, $string) as $split) {
2221 // Append the delimiter and add it to the array
2222 array_push($strArray, $split . $delimiter);
2229 // Detects the prefix 'mb_' if a multi-byte string is given
2230 function detectMultiBytePrefix ($str) {
2231 // Default is without multi-byte
2234 // Detect multi-byte (strictly)
2235 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2236 // With multi-byte encoded string
2240 // Return the prefix
2244 // Searches given array for a sub-string match and returns all found keys in an array
2245 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2246 // Init array for all found keys
2249 // Now check all entries
2250 foreach ($needles as $key => $needle) {
2251 // Is there found a partial string?
2252 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2253 if (strpos($heystack, $needle, $offset) !== FALSE) {
2254 // Add the found key
2255 array_push($keys, $key);
2263 // Determines database column name from given subject and locked
2264 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2265 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2266 // Default is 'normal' points
2267 $pointsColumn = 'points';
2269 // Which points, locked or normal?
2270 if ($locked === TRUE) {
2271 $pointsColumn = 'locked_points';
2274 // Prepare array for filter
2275 $filterData = array(
2276 'subject' => $subject,
2277 'locked' => $locked,
2278 'column' => $pointsColumn
2282 $filterData = runFilterChain('determine_points_column_name', $filterData);
2284 // Extract column name from array
2285 $pointsColumn = $filterData['column'];
2288 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2289 return $pointsColumn;
2292 // Converts a boolean variable into 'Y' for true and 'N' for false
2293 function convertBooleanToYesNo ($boolean) {
2296 if ($boolean === TRUE) {
2305 // "Translates" 'true' to true and 'false' to false
2306 function convertStringToBoolean ($str) {
2307 // Debug message (to measure how often this function is called)
2308 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2311 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2312 // Trim it lower-case for validation
2313 $strTrimmed = trim(strtolower($str));
2316 if (!in_array($strTrimmed, array('true', 'false'))) {
2318 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2322 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2326 return $GLOBALS[__FUNCTION__][$str];
2330 * "Makes" a variable in given string parseable, this function will throw an
2331 * error if the first character is not a dollar sign.
2333 * @param $varString String which contains a variable
2334 * @return $return String with added single quotes for better parsing
2336 function makeParseableVariable ($varString) {
2337 // The first character must be a dollar sign
2338 if (substr($varString, 0, 1) != '$') {
2339 // Please report this
2340 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2344 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2345 // Snap them in, if [,] are there
2346 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2350 return $GLOBALS[__FUNCTION__][$varString];
2353 // "Getter" for random TAN
2354 function getRandomTan () {
2356 return mt_rand(0, 99999);
2359 // Removes any : from subject
2360 function removeDoubleDotFromSubject ($subject) {
2362 $subjectArray = explode(':', $subject);
2363 $subject = $subjectArray[0];
2364 unset($subjectArray);
2370 // Adds a given entry to the database
2371 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2378 // Set POST data generic userid
2379 setPostRequestElement('userid', getMemberId());
2381 // Call inner function
2382 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2384 // Entry has been added?
2385 if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2386 // Display success message
2387 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2389 // Display failed message
2390 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2394 // Edit rows by given id numbers
2395 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()) {
2396 // $tableName must be an array
2397 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2398 // No tableName specified
2399 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2400 } elseif (!is_array($idColumn)) {
2401 // $idColumn is no array
2402 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2403 } elseif (!is_array($userIdColumn)) {
2404 // $userIdColumn is no array
2405 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2406 } elseif (!is_array($editNow)) {
2407 // $editNow is no array
2408 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2411 // Shall we change here or list for editing?
2412 if ($editNow[0] === TRUE) {
2413 // Add generic userid field
2414 setPostRequestElement('userid', getMemberId());
2416 // Call generic change method
2417 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2420 if ($affected == countPostSelection($idColumn[0])) {
2422 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2424 // Some are still there :(
2425 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2429 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2433 // Delete rows by given id numbers
2434 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()) {
2435 // Do this only for members
2438 // $tableName must be an array
2439 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2440 // No tableName specified
2441 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2442 } elseif (!is_array($idColumn)) {
2443 // $idColumn is no array
2444 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2445 } elseif (!is_array($userIdColumn)) {
2446 // $userIdColumn is no array
2447 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2448 } elseif (!is_array($deleteNow)) {
2449 // $deleteNow is no array
2450 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2453 // Shall we delete here or list for deletion?
2454 if ($deleteNow[0] === TRUE) {
2455 // Add generic userid field
2456 setPostRequestElement('userid', getMemberId());
2458 // Call generic function
2459 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2462 if ($affected == countPostSelection($idColumn[0])) {
2464 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2466 // Some are still there :(
2467 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
2470 // List for deletion confirmation
2471 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2475 // Build a special template list
2476 // @TODO cacheFiles is not yet supported
2477 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2478 // Do this only for logged in member
2481 // Call inner (general) function
2482 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2485 // Checks whether given address is IPv4
2486 function isIp4AddressValid ($address) {
2488 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2490 $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);
2494 return $GLOBALS[__FUNCTION__][$address];
2497 // Returns the string if not empty or FALSE if empty
2498 function validateIsEmpty ($str) {
2500 $trimmed = trim($str);
2502 // Is the string empty?
2503 if (empty($trimmed)) {
2512 // ----------------------------------------------------------------------------
2513 // "Translatation" functions for points_data table
2514 // ----------------------------------------------------------------------------
2516 // Translates generically some data into a target string
2517 function translateGeneric ($messagePrefix, $data) {
2518 // Is the method null or empty?
2519 if (is_null($data)) {
2522 } elseif (empty($data)) {
2523 // Is empty (string)
2527 // Default column name is unknown
2528 $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
2530 // Construct message id
2531 $messageId = $messagePrefix . '_' . strtoupper($data);
2534 if (isMessageIdValid($messageId)) {
2535 // Then use it as message string
2536 $return = '{--' . $messageId . '--}';
2539 // Return the column name
2543 // Translates points subject to human-readable
2544 function translatePointsSubject ($subject) {
2546 $subject = removeDoubleDotFromSubject($subject);
2549 return translateGeneric('POINTS_SUBJECT', $subject);
2552 // "Translates" given points account type
2553 function translatePointsAccountType ($accountType) {
2555 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2558 // "Translates" given points "locked mode"
2559 function translatePointsLockedMode ($lockedMode) {
2561 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2564 // "Translates" given points payment method
2565 function translatePointsPaymentMethod ($paymentMethod) {
2567 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2570 // "Translates" given points account provider
2571 function translatePointsAccountProvider ($accountProvider) {
2573 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2576 // "Translates" given points notify recipient
2577 function translatePointsNotifyRecipient ($notifyRecipient) {
2579 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2582 // "Translates" given mode to a human-readable version
2583 function translatePointsMode ($pointsMode) {
2585 return translateGeneric('POINTS_MODE', $pointsMode);
2588 // "Translates" task type to a human-readable version
2589 function translateTaskType ($taskType) {
2591 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2594 //-----------------------------------------------------------------------------
2595 // Automatically re-created functions, all taken from user comments on www.php.net
2596 //-----------------------------------------------------------------------------
2597 if (!function_exists('html_entity_decode')) {
2598 // Taken from documentation on www.php.net
2599 function html_entity_decode ($string) {
2600 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2601 $trans_tbl = array_flip($trans_tbl);
2602 return strtr($string, $trans_tbl);