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 // Start creating password
97 while (strlen($password) < $length) {
98 $password .= $localAbc[mt_rand(0, count($localAbc) -1)];
102 * When the size is below 40 we can also add additional security by
103 * scrambling it. Otherwise the hash may corrupted..
105 if (strlen($password) <= 40) {
106 // Also scramble the password
107 $password = scrambleString($password);
110 // Return the password
114 // Generates a human-readable timestamp from the Uni* stamp
115 function generateDateTime ($time, $mode = '0') {
117 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
119 return $GLOBALS[__FUNCTION__][$time][$mode];
122 // If the stamp is zero it mostly didn't "happen"
123 if (($time == '0') || (is_null($time))) {
125 return '{--NEVER_HAPPENED--}';
128 // Filter out numbers
129 $timeSecured = bigintval($time);
132 switch (getLanguage()) {
133 case 'de': // German date / time format
135 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break;
136 case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break;
137 case '2': $ret = date('d.m.Y|H:i', $timeSecured); break;
138 case '3': $ret = date('d.m.Y', $timeSecured); break;
139 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
140 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
141 case '6': $ret = date('Ymd', $timeSecured); break;
142 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
144 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
149 default: // Default is the US date / time format!
151 case '0': $ret = date('r', $timeSecured); break;
152 case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break;
153 case '2': $ret = date('y-m-d|H:i', $timeSecured); break;
154 case '3': $ret = date('y-m-d', $timeSecured); break;
155 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
156 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
157 case '6': $ret = date('Ymd', $timeSecured); break;
158 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
160 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
166 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
172 // Translates Y/N to yes/no
173 function translateYesNo ($yn) {
175 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
177 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
179 case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
180 case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
183 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $yn));
189 return $GLOBALS[__FUNCTION__][$yn];
192 // Translates the american decimal dot into a german comma
193 // OPPOMENT: convertCommaToDot()
194 function translateComma ($dotted, $cut = TRUE, $max = '0') {
195 // First, cast all to double, due to PHP changes
196 $dotted = (double) $dotted;
198 // Default is 3 you can change this in admin area "Settings -> Misc Options"
199 if (!isConfigEntrySet('max_comma')) {
200 setConfigEntry('max_comma', 3);
203 // Use from config is default
204 $maxComma = getConfig('max_comma');
206 // Use from parameter?
212 if (($cut === TRUE) && ($max == '0')) {
213 // Test for commata if in cut-mode
214 $com = explode('.', $dotted);
215 if (count($com) < 2) {
216 // Don't display commatas even if there are none... ;-)
224 $translated = $dotted;
225 switch (getLanguage()) {
226 case 'de': // German language
227 $translated = number_format($dotted, $maxComma, ',', '.');
230 default: // All others
231 $translated = number_format($dotted, $maxComma, '.', ',');
235 // Return translated value
236 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
240 // Translate Uni*-like gender to human-readable
241 function translateGender ($gender) {
243 $ret = '!' . $gender . '!';
245 // Male/female or company?
250 // Use generic function
251 $ret = translateGeneric('GENDER', $gender);
255 // Please report bugs on unknown genders
256 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
260 // Return translated gender
264 // "Translates" the user status
265 function translateUserStatus ($status) {
266 // Default status is unknown if something goes through
267 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
269 // Generate message depending on status
274 // Use generic function for all "normal" cases"
275 $ret = translateGeneric('ACCOUNT_STATUS', $status);
278 case '': // Account deleted
279 case NULL: // Account deleted
280 $ret = '{--ACCOUNT_STATUS_DELETED--}';
283 default: // Please report all unknown status
284 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
292 // "Translates" 'visible' and 'locked' to a CSS class
293 function translateMenuVisibleLocked ($content, $prefix = '') {
294 // Default is 'menu_unknown'
295 $content['visible_css'] = $prefix . 'menu_unknown';
297 // Translate 'visible' and keep an eye on the prefix
298 switch ($content['visible']) {
299 case 'Y': // Should be visible
300 $content['visible_css'] = $prefix . 'menu_visible';
303 case 'N': // Is invisible
304 $content['visible_css'] = $prefix . 'menu_invisible';
307 default: // Please report this
308 reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
312 // Translate 'locked' and keep an eye on the prefix
313 switch ($content['locked']) {
314 case 'Y': // Should be locked, only admins can call this
315 $content['locked_css'] = $prefix . 'menu_locked';
318 case 'N': // Is unlocked and visible to members/guests/sponsors
319 $content['locked_css'] = $prefix . 'menu_unlocked';
322 default: // Please report this
323 reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
327 // Return the resulting array
331 // Generates an URL for the dereferer
332 function generateDereferrerUrl ($url) {
333 // Don't de-refer our own links!
334 if (substr($url, 0, strlen(getUrl())) != getUrl()) {
336 $encodedUrl = encodeString(compileUriCode($url));
339 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url);
342 $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie(generateHash($url)) . '%}';
349 // Generates an URL for the frametester
350 function generateFrametesterUrl ($url) {
351 // Prepare frametester URL
352 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
353 encodeString(compileUriCode($url))
356 // Return the new URL
357 return $frametesterUrl;
360 // Count entries from e.g. a selection box
361 function countSelection ($array) {
363 if (!is_array($array)) {
365 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
372 foreach ($array as $key => $selected) {
374 if (!empty($selected)) {
375 // Yes, then count it
380 // Return counted selections
384 // Generates a timestamp (some wrapper for mktime())
385 function makeTime ($hours, $minutes, $seconds, $stamp) {
386 // Extract day, month and year from given timestamp
387 $days = getDay($stamp);
388 $months = getMonth($stamp);
389 $years = getYear($stamp);
391 // Create timestamp for wished time which depends on extracted date
402 // Redirects to an URL and if neccessarry extends it with own base URL
403 function redirectToUrl ($url, $allowSpider = TRUE) {
404 // Is the output mode -2?
405 if (isAjaxOutputMode()) {
406 // This is always (!) an AJAX request and shall not be redirected
411 if (substr($url, 0, 6) == '{%url=') {
412 $url = substr($url, 6, -2);
416 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
418 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
419 $rel = ' rel="external"';
421 // Is there internal or external URL?
422 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
423 // Own (=internal) URL
427 // Three different ways to debug...
428 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
429 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
430 //* DEBUG: */ die($url);
432 // We should not sent a redirect if headers are already sent
433 if (!headers_sent()) {
434 // Load URL when headers are not sent
435 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE));
437 // Output error message
438 loadInclude('inc/header.php');
439 loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
440 loadInclude('inc/footer.php');
443 // Shut the mailer down here
447 /************************************************************************
449 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
450 * $a_sort sortiert: *
452 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
453 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
454 * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
455 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
456 * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
458 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
459 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
460 * Sie, dass es doch nicht so schwer ist! :-) *
462 ************************************************************************/
463 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
464 $temporaryArray = $array;
465 while ($primary_key < count($a_sort)) {
466 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
467 foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
469 if ($nums === FALSE) {
470 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
471 if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
472 } elseif ($key != $key2) {
473 // Sort numbers (E.g.: 9 < 10)
474 if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
475 if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
479 // We have found two different values, so let's sort whole array
480 foreach ($temporaryArray as $sort_key => $sort_val) {
481 $t = $temporaryArray[$sort_key][$key];
482 $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
483 $temporaryArray[$sort_key][$key2] = $t;
494 // Write back sorted array
495 $array = $temporaryArray;
500 // Deprecated : $length (still has one reference in this function)
501 // Optional : $extraData
503 function generateRandomCode ($length, $code, $userid, $extraData = '') {
504 // Build server string
505 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
508 $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
509 if (isConfigEntrySet('secret_key')) {
510 $keys .= getEncryptSeparator() . getSecretKey();
512 if (isConfigEntrySet('file_hash')) {
513 $keys .= getEncryptSeparator() . getFileHash();
515 $keys .= getEncryptSeparator() . getDateFromRepository();
516 if (isConfigEntrySet('master_salt')) {
517 $keys .= getEncryptSeparator() . getMasterSalt();
520 // Build string from misc data
521 $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
523 // Add more additional data
524 if (isSessionVariableSet('u_hash')) {
525 $data .= getEncryptSeparator() . getSession('u_hash');
528 // Add referral id, language, theme and userid
529 $data .= getEncryptSeparator() . determineReferralId();
530 $data .= getEncryptSeparator() . getLanguage();
531 $data .= getEncryptSeparator() . getCurrentTheme();
532 $data .= getEncryptSeparator() . getMemberId();
534 // Calculate number for generating the code
535 $a = $code + getConfig('_ADD') - 1;
537 if (isConfigEntrySet('master_salt')) {
538 // Generate hash with master salt from modula of number with the prime number and other data
539 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
541 // Generate hash with "hash of site key" from modula of number with the prime number and other data
542 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
545 // Create number from hash
546 $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
548 // At least 10 numbers shall be secure enought!
549 if (isExtensionActive('other')) {
550 $len = getCodeLength();
555 // Smaller 1 is not okay
561 // Cut off requested counts of number, but skip first digit (which is mostly a zero)
562 $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
564 // Done building code
568 // Does only allow numbers
569 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
570 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
571 // Filter all non-number chars out, so only number chars will remain
572 $ret = preg_replace('/[^0123456789]/', '', $num);
575 if ($castValue === TRUE) {
576 // Cast to biggest numeric type
577 $ret = (double) $ret;
580 // Has the whole value changed?
581 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
583 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
587 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
591 // Creates a Uni* timestamp from given selection data and prefix
592 function createEpocheTimeFromSelections ($prefix, $postData) {
593 // Initial return value
596 // Is there a leap year?
598 $TEST = getYear() / 4;
601 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
602 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) {
603 $SWITCH = getOneDay();
606 // First add years...
607 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
610 $ret += $postData[$prefix . '_mo'] * 2628000;
613 $ret += $postData[$prefix . '_we'] * 604800;
616 $ret += $postData[$prefix . '_da'] * 86400;
619 $ret += $postData[$prefix . '_ho'] * 3600;
622 $ret += $postData[$prefix . '_mi'] * 60;
624 // And at last seconds...
625 $ret += $postData[$prefix . '_se'];
627 // Return calculated value
631 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
632 function createFancyTime ($stamp) {
633 // Get data array with years/months/weeks/days/...
634 $data = createTimeSelections($stamp, '', '', '', TRUE);
636 foreach ($data as $k => $v) {
638 // Value is greater than 0 "eval" data to return string
639 $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
644 // Is something there?
645 if (strlen($ret) > 0) {
646 // Remove leading commata and space
647 $ret = substr($ret, 2);
650 $ret = '0 {--TIME_UNIT_SECOND--}';
653 // Return fancy time string
657 // Taken from www.php.net isInStringIgnoreCase() user comments
658 function isEmailValid ($email) {
659 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
662 if (!isset($GLOBALS[__FUNCTION__][$email])) {
663 // Check first part of email address
664 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
667 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
670 $regex = '@^' . $first . '\@' . $domain . '$@iU';
673 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
676 // Return check result
677 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
678 return $GLOBALS[__FUNCTION__][$email];;
681 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
682 function isUrlValid ($url, $compile = TRUE) {
684 $url = trim(urldecode($url));
685 //* DEBUG: */ debugOutput($url);
687 // Compile some chars out...
688 if ($compile === TRUE) {
689 $url = compileUriCode($url, FALSE, FALSE, FALSE);
691 //* DEBUG: */ debugOutput($url);
693 // Check for the extension filter
694 if (isExtensionActive('filter')) {
695 // Use the extension's filter set
696 return FILTER_VALIDATE_URL($url, FALSE);
700 * If not installed, perform a simple test. Just make it sure there is always a
701 * http:// or https:// in front of the URLs.
703 return isUrlValidSimple($url);
706 // Generate a hash for extra-security for all passwords
707 function generateHash ($plainText, $salt = '', $hash = TRUE) {
709 //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
711 // Is the required extension 'sql_patches' there and a salt is not given?
712 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
713 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
714 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
715 if ($hash === TRUE) {
717 return md5($plainText);
724 // Is an arry element missing here?
725 if (!isConfigEntrySet('file_hash')) {
727 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
730 // When the salt is empty build a new one, else use the first x configured characters as the salt
732 // Build server string for more entropy
733 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
736 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
739 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
741 // Calculate number for generating the code
742 $a = time() + getConfig('_ADD') - 1;
744 // Generate SHA1 sum from modula of number and the prime number
745 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
746 //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
747 $sha1 = scrambleString($sha1);
748 //* DEBUG: */ debugOutput('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
749 //* DEBUG: */ $sha1b = descrambleString($sha1);
750 //* DEBUG: */ debugOutput('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
752 // Generate the password salt string
753 $salt = substr($sha1, 0, getSaltLength());
754 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')<br />');
757 //* DEBUG: */ debugOutput('salt=' . $salt);
758 $salt = substr($salt, 0, getSaltLength());
759 //* DEBUG: */ debugOutput('salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')<br />');
761 // Sanity check on salt
762 if (strlen($salt) != getSaltLength()) {
764 reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
768 // Generate final hash (for debug output)
769 $finalHash = $salt . sha1($salt . $plainText);
772 //* DEBUG: */ debugOutput('finalHash('.strlen($finalHash).')=' . $finalHash);
779 function scrambleString ($str) {
783 // Final check, in case of failure it will return unscrambled string
784 if (strlen($str) > 40) {
785 // The string is to long
787 } elseif (strlen($str) == 40) {
789 $scrambleNums = explode(':', getPassScramble());
791 // Generate new numbers
792 $scrambleNums = explode(':', genScrambleString(strlen($str)));
795 // Compare both lengths and abort if different
796 if (strlen($str) != count($scrambleNums)) return $str;
798 // Scramble string here
799 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
800 for ($idx = 0; $idx < strlen($str); $idx++) {
801 // Get char on scrambled position
802 $char = substr($str, $scrambleNums[$idx], 1);
804 // Add it to final output string
808 // Return scrambled string
809 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
813 // De-scramble a string scrambled by scrambleString()
814 function descrambleString ($str) {
815 // Scramble only 40 chars long strings
816 if (strlen($str) != 40) {
820 // Load numbers from config
821 $scrambleNums = explode(':', getPassScramble());
824 if (count($scrambleNums) != 40) {
828 // Begin descrambling
829 $orig = str_repeat(' ', 40);
830 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
831 for ($idx = 0; $idx < 40; $idx++) {
832 $char = substr($str, $idx, 1);
833 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
836 // Return scrambled string
837 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
841 // Generated a "string" for scrambling
842 function genScrambleString ($len) {
843 // Prepare array for the numbers
844 $scrambleNumbers = array();
846 // First we need to setup randomized numbers from 0 to 31
847 for ($idx = 0; $idx < $len; $idx++) {
849 $rand = mt_rand(0, ($len - 1));
851 // Check for it by creating more numbers
852 while (array_key_exists($rand, $scrambleNumbers)) {
853 $rand = mt_rand(0, ($len - 1));
857 $scrambleNumbers[$rand] = $rand;
860 // So let's create the string for storing it in database
861 $scrambleString = implode(':', $scrambleNumbers);
862 return $scrambleString;
865 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
866 function encodeHashForCookie ($passHash) {
867 // Return vanilla password hash
870 // Is a secret key and master salt already initialized?
871 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
872 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
873 // Only calculate when the secret key is generated
874 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
875 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
876 // Both keys must have same length so return unencrypted
877 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40');
881 $newHash = ''; $start = 9;
882 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
883 for ($idx = 0; $idx < 20; $idx++) {
884 $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getSecretKey())), 2));
885 $part2 = hexdec(substr(getSecretKey(), $start, 2));
886 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
888 if ($part1 > $part2) {
889 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
890 } elseif ($part2 > $part1) {
891 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
893 $mod = substr($mod, 0, 2);
894 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
895 $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
896 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
901 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
902 $ret = generateHash($newHash, getMasterSalt());
906 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
910 // Fix "deleted" cookies
911 function fixDeletedCookies ($cookies) {
912 // Is this an array with entries?
913 if ((is_array($cookies)) && (count($cookies) > 0)) {
914 // Then check all cookies if they are marked as deleted!
915 foreach ($cookies as $cookieName) {
916 // Is the cookie set to "deleted"?
917 if (getSession($cookieName) == 'deleted') {
918 setSession($cookieName, '');
924 // Checks if a given apache module is loaded
925 function isApacheModuleLoaded ($apacheModule) {
926 // Check it and return result
927 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
930 // Get current theme name
931 function getCurrentTheme () {
932 // The default theme is 'default'... ;-)
935 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
936 if (isExtensionActive('theme')) {
938 $ret = getActualTheme();
939 } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) {
940 // Use value from POST data
941 $ret = postRequestElement('theme');
942 } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) {
943 // Use value from GET data
944 $ret = getRequestElement('theme');
945 } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) {
946 // Use value from GET data
947 $ret = getMailerTheme();
950 // Return theme value
954 // Generates an error code from given account status
955 function generateErrorCodeFromUserStatus ($status = '') {
956 // If no status is provided, use the default, cached
957 if ((empty($status)) && (isMember())) {
959 $status = getUserData('status');
962 // Default error code if unknown account status
963 $errorCode = getCode('ACCOUNT_UNKNOWN');
965 // Generate constant name
966 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
968 // Is the constant there?
969 if (isCodeSet($codeName)) {
971 $errorCode = getCode($codeName);
974 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
981 // Back-ported from the new ship-simu engine. :-)
982 function debug_get_printable_backtrace () {
986 // Get and prepare backtrace for output
987 $backtraceArray = debug_backtrace();
988 foreach ($backtraceArray as $key => $trace) {
989 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
990 if (!isset($trace['line'])) $trace['line'] = __LINE__;
991 if (!isset($trace['args'])) $trace['args'] = array();
992 $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>';
996 $backtrace .= '</ol>';
998 // Return the backtrace
1002 // A mail-able backtrace
1003 function debug_get_mailable_backtrace () {
1007 // Get and prepare backtrace for output
1008 $backtraceArray = debug_backtrace();
1009 foreach ($backtraceArray as $key => $trace) {
1010 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1011 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1012 if (!isset($trace['args'])) $trace['args'] = array();
1013 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1016 // Return the backtrace
1020 // Generates a ***weak*** seed
1021 function generateSeed () {
1022 return microtime(TRUE) * 100000;
1025 // Converts a message code to a human-readable message
1026 function getMessageFromErrorCode ($code) {
1027 // Default is an unknown error code
1028 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1030 // Which code is provided?
1033 // No error code is bad coding practice
1034 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1037 // All error messages
1038 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1039 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1040 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1041 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1042 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1043 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1044 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1045 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1046 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1047 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1048 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1049 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1050 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1051 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1052 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1053 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1054 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1055 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1056 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1057 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1058 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1059 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1060 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1061 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1062 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1063 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1064 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1065 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1066 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1067 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1068 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1069 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1070 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1072 case getCode('ERROR_MAILID'):
1073 if (isExtensionActive('mailid', TRUE)) {
1074 $message = '{--ERROR_CONFIRMING_MAIL--}';
1076 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1080 case getCode('EXTENSION_PROBLEM'):
1081 if (isGetRequestElementSet('ext')) {
1082 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1084 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1088 case getCode('URL_TIME_LOCK'):
1089 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1090 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1091 array(bigintval(getRequestElement('id'))), __FUNCTION__, __LINE__);
1093 // Load timestamp from last order
1094 $content = SQL_FETCHARRAY($result);
1097 SQL_FREERESULT($result);
1099 // Translate it for templates
1100 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1102 // Calculate hours...
1103 $content['hours'] = round(getUrlTlock() / 60 / 60);
1106 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1109 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1111 // Finally contruct the message
1112 $message = loadTemplate('tlock_message', TRUE, $content);
1116 // Log missing/invalid error codes
1117 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1121 // Return the message
1125 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1126 function isUrlValidSimple ($url) {
1127 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1129 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1131 // Allows http and https
1132 $http = "(http|https)+(:\/\/)";
1134 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1135 // Test double-domains (e.g. .de.vu)
1136 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1138 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1140 $dir = "((/)+([-_\.[:alnum:]])+)*";
1142 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1143 // ... and the string after and including question character
1144 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1145 // Pattern for URLs like http://url/dir/doc.html?var=value
1146 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1147 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1148 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1149 // Pattern for URLs like http://url/dir/?var=value
1150 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1151 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1152 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1153 // Pattern for URLs like http://url/dir/page.ext
1154 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1155 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1156 $pattern['ipdp'] = $http . $ip . $dir . $page;
1157 // Pattern for URLs like http://url/dir
1158 $pattern['d1d'] = $http . $domain1 . $dir;
1159 $pattern['d2d'] = $http . $domain2 . $dir;
1160 $pattern['ipd'] = $http . $ip . $dir;
1161 // Pattern for URLs like http://url/?var=value
1162 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1163 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1164 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1165 // Pattern for URLs like http://url?var=value
1166 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1167 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1168 $pattern['ipg12'] = $http . $ip . $getstring1;
1170 // Test all patterns
1172 foreach ($pattern as $key => $pat) {
1174 if (isDebugRegularExpressionEnabled()) {
1175 // @TODO Are these convertions still required?
1176 $pat = str_replace('.', '\.', $pat);
1177 $pat = str_replace('@', '\@', $pat);
1178 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1181 // Check if expression matches
1182 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1185 if ($reg === TRUE) {
1190 // Return true/false
1191 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1195 // Wtites data to a config.php-style file
1196 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1197 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0) {
1198 // Initialize some variables
1204 // Is the file there and read-/write-able?
1205 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1206 $search = 'CFG: ' . $comment;
1207 $tmp = $FQFN . '.tmp';
1209 // Open the source file
1210 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1212 // Is the resource valid?
1213 if (is_resource($fp)) {
1214 // Open temporary file
1215 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1217 // Is the resource again valid?
1218 if (is_resource($fp_tmp)) {
1219 // Mark temporary file as readable
1220 $GLOBALS['file_readable'][$tmp] = TRUE;
1223 while (!feof($fp)) {
1224 // Read from source file
1225 $line = fgets ($fp, 1024);
1227 if (isInString($search, $line)) {
1233 if ($next === $seek) {
1235 $line = $prefix . $inserted . $suffix . chr(10);
1241 // Write to temp file
1242 fwrite($fp_tmp, $line);
1248 // Finished writing tmp file
1252 // Close source file
1255 if (($done === TRUE) && ($found === TRUE)) {
1256 // Copy back tmp file and delete tmp :-)
1257 copyFileVerified($tmp, $FQFN, 0644);
1258 return removeFile($tmp);
1259 } elseif ($found === FALSE) {
1260 outputHtml('<strong>CHANGE:</strong> 404!');
1262 outputHtml('<strong>TMP:</strong> UNDONE!');
1266 // File not found, not readable or writeable
1267 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1270 // An error was detected!
1274 // Debug message logger
1275 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1276 // Is debug mode enabled?
1277 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1279 $message = str_replace(array(chr(13), chr(10)), array('', ''), $message);
1281 // Log this message away
1282 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1286 // Handle extra values
1287 function handleExtraValues ($filterFunction, $value, $extraValue) {
1288 // Default is the value itself
1291 // Is there a special filter function?
1292 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1293 // Call-back function does not exist or is empty
1294 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1297 // Is there extra parameters here?
1298 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1299 // Put both parameters in one new array by default
1300 $args = array($value, $extraValue);
1302 // If we have an array simply use it and pre-extend it with our value
1303 if (is_array($extraValue)) {
1304 // Make the new args array
1305 $args = merge_array(array($value), $extraValue);
1308 // Call the multi-parameter call-back
1309 $ret = call_user_func_array($filterFunction, $args);
1312 if ($ret === TRUE) {
1313 // Test passed, so write direct value
1317 // One parameter call
1318 $ret = call_user_func($filterFunction, $value);
1319 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1322 if ($ret === TRUE) {
1323 // Test passed, so write direct value
1332 // Tries to determine if call-back functions and/or extra values shall be parsed
1333 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search) {
1335 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1337 // Send data through the filter function if found
1338 if ($key == $userIdColumn[0]) {
1339 // Is the userid, we have to process it with convertZeroToNull()
1340 $entries = convertZeroToNull($entries);
1341 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1342 // Debug mode enabled?
1343 if (isDebugModeEnabled()) {
1345 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1348 // Filter function + extra value set
1349 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1351 // Debug mode enabled?
1352 if (isDebugModeEnabled()) {
1354 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1356 } elseif (!empty($filterFunctions[$search])) {
1357 // Debug mode enabled?
1358 if (isDebugModeEnabled()) {
1360 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1363 // Handle extra values
1364 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1366 // Debug mode enabled?
1367 if (isDebugModeEnabled()) {
1369 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1372 // Make sure entries is not bool, then something went wrong
1373 assert(!is_bool($entries));
1380 // Converts timestamp selections into a timestamp
1381 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1382 // Init test variable
1386 // Get last three chars
1387 $test = substr($id, -3);
1389 // Improved way of checking! :-)
1390 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1391 // Found a multi-selection for timings?
1392 $test = substr($id, 0, -3);
1393 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)) {
1394 // Generate timestamp
1395 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1396 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1397 $GLOBALS['skip_config'][$test] = TRUE;
1399 // Remove data from array
1400 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1401 unset($postData[$test . '_' . $rem]);
1412 // Reverts the german decimal comma into Computer decimal dot
1413 // OPPOMENT: translateComma()
1414 function convertCommaToDot ($str) {
1415 // Default float is not a float... ;-)
1418 // Which language is selected?
1419 switch (getLanguage()) {
1420 case 'de': // German language
1421 // Remove german thousand dots first
1422 $str = str_replace('.', '', $str);
1424 // Replace german commata with decimal dot and cast it
1425 $float = (float) str_replace(',', '.', $str);
1428 default: // US and so on
1429 // Remove thousand commatas first and cast
1430 $float = (float) str_replace(',', '', $str);
1438 // Handle menu-depending failed logins and return the rendered content
1439 function handleLoginFailures ($accessLevel) {
1440 // Default output is empty ;-)
1443 // Is the session data set?
1444 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1445 // Ignore zero values
1446 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1447 // Non-guest has login failures found, get both data and prepare it for template
1448 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1450 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1451 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1455 $OUT = loadTemplate('login_failures', TRUE, $content);
1458 // Reset session data
1459 setSession('mailer_' . $accessLevel . '_failures', '');
1460 setSession('mailer_' . $accessLevel . '_last_failure', '');
1463 // Return rendered content
1468 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1470 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1472 // Shall I remove the cache file?
1473 if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1474 // Rebuild cache only in HTML output-mode
1475 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1477 $GLOBALS['cache_instance']->removeCacheFile($force);
1480 // Include file given?
1483 $inc = sprintf("inc/loader/load-%s.php", $inc);
1485 // Is the include there?
1486 if (isIncludeReadable($inc)) {
1487 // And rebuild it from scratch
1488 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1491 // Include not found
1492 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1498 // Determines the real remote address
1499 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1500 // Default is 127.0.0.1
1501 $address = '127.0.0.1';
1503 // Is a proxy in use?
1504 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1506 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1507 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1508 // Yet, another proxy
1509 $address = $_SERVER['HTTP_CLIENT_IP'];
1510 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1511 // The regular address when no proxy was used
1512 $address = $_SERVER['REMOTE_ADDR'];
1515 // This strips out the real address from proxy output
1516 if (strstr($address, ',')) {
1517 $addressArray = explode(',', $address);
1518 $address = $addressArray[0];
1521 // Return the result
1525 // Adds a bonus mail to the queue
1526 // This is a high-level function!
1527 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1528 // Use mode from data if not set and availble ;-)
1529 if ((empty($mode)) && (isset($data['mail_mode']))) {
1530 $mode = $data['mail_mode'];
1533 // Generate receiver list
1534 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1537 if (!empty($receiver)) {
1538 // Add bonus mail to queue
1539 addBonusMailToQueue(
1551 // Mail inserted into bonus pool
1552 if ($output === TRUE) {
1553 displayMessage('{--ADMIN_BONUS_SEND--}');
1555 } elseif ($output === TRUE) {
1556 // More entered than can be reached!
1557 displayMessage('{--ADMIN_MORE_SELECTED--}');
1560 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1564 // Enables the reset mode and runs it
1565 function doReset () {
1566 // Enable the reset mode
1567 $GLOBALS['reset_enabled'] = TRUE;
1570 runFilterChain('reset');
1573 // Enables the reset mode (hourly, weekly and monthly) and runs it
1574 function doHourly () {
1575 // Enable the hourly reset mode
1576 $GLOBALS['hourly_enabled'] = TRUE;
1578 // Run filters (one always!)
1579 runFilterChain('hourly');
1582 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1583 function doShutdown () {
1584 // Call the filter chain 'shutdown'
1585 runFilterChain('shutdown', NULL);
1587 // Check if not in installation phase and the link is up
1588 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1590 SQL_CLOSE(__FUNCTION__, __LINE__);
1591 } elseif (!isInstallationPhase()) {
1593 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1596 // Stop executing here
1601 function initMemberId () {
1602 $GLOBALS['member_id'] = '0';
1605 // Setter for member id
1606 function setMemberId ($memberid) {
1607 // We should not set member id to zero
1608 if ($memberid == '0') {
1609 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1613 $GLOBALS['member_id'] = bigintval($memberid);
1616 // Getter for member id or returns zero
1617 function getMemberId () {
1618 // Default member id
1621 // Is the member id set?
1622 if (isMemberIdSet()) {
1624 $memberid = $GLOBALS['member_id'];
1631 // Checks ether the member id is set
1632 function isMemberIdSet () {
1633 return (isset($GLOBALS['member_id']));
1636 // Setter for extra title
1637 function setExtraTitle ($extraTitle) {
1638 $GLOBALS['extra_title'] = $extraTitle;
1641 // Getter for extra title
1642 function getExtraTitle () {
1643 // Is the extra title set?
1644 if (!isExtraTitleSet()) {
1645 // No, then abort here
1646 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1650 return $GLOBALS['extra_title'];
1653 // Checks if the extra title is set
1654 function isExtraTitleSet () {
1655 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1659 * Reads a directory recursively by default and searches for files not matching
1660 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1661 * a whole directory.
1663 * @param $baseDir Relative base directory to PATH to scan from
1664 * @param $prefix Prefix for all positive matches (which files should be found)
1665 * @param $fileIncludeDirs whether to include directories in the final output array
1666 * @param $addBaseDir whether to add $baseDir to all array entries
1667 * @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'
1668 * @param $extension File extension for all positive matches
1669 * @param $excludePattern Regular expression to exclude more files (preg_match())
1670 * @param $recursive whether to scan recursively
1671 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1672 * @return $foundMatches All found positive matches for above criteria
1674 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
1675 // Add default entries we should always exclude
1676 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1678 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1679 // Init found includes
1680 $foundMatches = array();
1683 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1686 while ($baseFile = readdir($dirPointer)) {
1687 // Exclude '.', '..' and entries in $excludeArray automatically
1688 if (in_array($baseFile, $excludeArray, TRUE)) {
1690 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1694 // Construct include filename and FQFN
1695 $fileName = $baseDir . $baseFile;
1696 $FQFN = getPath() . $fileName;
1698 // Remove double slashes
1699 $FQFN = str_replace('//', '/', $FQFN);
1701 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1702 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1704 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1710 // Skip also files with non-matching prefix genericly
1711 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1712 // Is a redirectory so read it as well
1713 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1715 // And skip further processing
1717 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1719 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1721 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1722 // Skip wrong suffix as well
1723 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1725 } elseif (!isFileReadable($FQFN)) {
1726 // Not readable so skip it
1727 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1728 } elseif (filesize($FQFN) < 50) {
1729 // Might be deprecated
1730 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1732 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1733 // This PHP script is deprecated
1734 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1738 // Get file' extension (last 4 chars)
1739 $fileExtension = substr($baseFile, -4, 4);
1741 // Is the file a PHP script or other?
1742 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1743 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1744 // Is this a valid include file?
1745 if ($extension == '.php') {
1746 // Remove both for extension name
1747 $extName = substr($baseFile, strlen($prefix), -4);
1749 // Add file with or without base path
1750 if ($addBaseDir === TRUE) {
1752 array_push($foundMatches, $fileName);
1755 array_push($foundMatches, $baseFile);
1758 // We found .php file but should not search for them, why?
1759 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1761 } elseif ($fileExtension == $extension) {
1762 // Other, generic file found
1763 array_push($foundMatches, $fileName);
1768 closedir($dirPointer);
1771 sort($foundMatches);
1773 // Return array with include files
1774 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1775 return $foundMatches;
1778 // Checks whether $prefix is found in $fileName
1779 function isFilePrefixFound ($fileName, $prefix) {
1780 // @TODO Find a way to cache this
1781 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1784 // Maps a module name into a database table name
1785 function mapModuleToTable ($moduleName) {
1786 // Map only these, still lame code...
1787 switch ($moduleName) {
1788 case 'index': // 'index' is the guest's menu
1789 $moduleName = 'guest';
1792 case 'login': // ... and 'login' the member's menu
1793 $moduleName = 'member';
1796 // Anything else will not be mapped, silently.
1803 // Add SQL debug data to array for later output
1804 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1806 if (!isset($GLOBALS['debug_sql_available'])) {
1807 // Check it and cache it in $GLOBALS
1808 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1811 // Don't execute anything here if we don't need or ext-other is missing
1812 if ($GLOBALS['debug_sql_available'] === FALSE) {
1816 // Already executed?
1817 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1818 // Then abort here, we don't need to profile a query twice
1822 // Remeber this as profiled (or not, but we don't care here)
1823 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
1827 'num_rows' => SQL_NUMROWS($result),
1828 'affected' => SQL_AFFECTEDROWS(),
1829 'sql_str' => $sqlString,
1830 'timing' => $timing,
1831 'file' => basename($F),
1836 array_push($GLOBALS['debug_sqls'], $record);
1839 // Initializes the cache instance
1840 function initCacheInstance () {
1841 // Check for double-initialization
1842 if (isset($GLOBALS['cache_instance'])) {
1843 // This should not happen and must be fixed
1844 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1847 // Load include for CacheSystem class
1848 loadIncludeOnce('inc/classes/cachesystem.class.php');
1850 // Initialize cache system only when it's needed
1851 $GLOBALS['cache_instance'] = new CacheSystem();
1854 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1855 // Failed to initialize cache sustem
1856 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1860 // Getter for message from array or raw message
1861 function getMessageFromIndexedArray ($message, $pos, $array) {
1862 // Check if the requested message was found in array
1863 if (isset($array[$pos])) {
1864 // ... if yes then use it!
1865 $ret = $array[$pos];
1867 // ... else use default message
1875 // Convert ';' to ', ' for e.g. receiver list
1876 function convertReceivers ($old) {
1877 return str_replace(';', ', ', $old);
1880 // Get a module from filename and access level
1881 function getModuleFromFileName ($file, $accessLevel) {
1882 // Default is 'invalid';
1883 $modCheck = 'invalid';
1885 // @TODO This is still very static, rewrite it somehow
1886 switch ($accessLevel) {
1888 $modCheck = 'admin';
1894 $modCheck = getModule();
1897 default: // Unsupported file name / access level
1898 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1906 // Encodes an URL for adding session id, etc.
1907 function encodeUrl ($url, $outputMode = '0') {
1908 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
1909 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1910 // Raw output mode detected or session_name() found in URL
1914 // Is there a valid session?
1915 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === FALSE) || (!isset($_COOKIE[session_name()]))) && (isSpider() === FALSE)) {
1916 // Determine right separator
1917 $separator = '&';
1918 if (!isInString('?', $url)) {
1923 // Is the session id set?
1924 if (session_id() != '') {
1925 // Then add it to URL
1926 $url .= $separator . session_name() . '=' . session_id();
1931 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1933 $url = '{?URL?}/' . $url;
1937 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
1939 // Is there to decode entities?
1940 if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
1941 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
1942 // Decode them for e.g. JavaScript parts
1943 $url = decodeEntities($url);
1944 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
1948 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
1950 // Return the encoded URL
1954 // Simple check for spider
1955 function isSpider () {
1956 // Get the UA and trim it down
1957 $userAgent = trim(detectUserAgent(TRUE));
1959 // It should not be empty, if so it is better a spider/bot
1960 if (empty($userAgent)) {
1961 // It is a spider/bot
1966 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
1969 // Function to search for the last modified file
1970 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
1972 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
1973 // Does it match what we are looking for? (We skip a lot files already!)
1974 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
1975 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
1977 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
1978 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
1980 // Walk through all entries
1981 foreach ($ds as $d) {
1982 // Generate proper FQFN
1983 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
1985 // Is it a file and readable?
1986 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
1987 if (isFileReadable($FQFN)) {
1988 // $FQFN is a readable file so extract the requested data from it
1989 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
1990 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
1992 // Is the file more recent?
1993 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
1994 // This file is newer as the file before
1995 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
1996 $last_changed['path_name'] = $FQFN;
1997 $last_changed[$lookFor] = $check;
2001 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2006 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2007 function handleFieldWithBraces ($field) {
2008 // Are there braces [] at the end?
2009 if (substr($field, -2, 2) == '[]') {
2011 * Try to find one and replace it. I do it this way to allow easy
2012 * extending of this code.
2014 foreach (array('admin_list_builder_id_value') as $key) {
2015 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2016 // Is the cache entry set?
2017 if (isset($GLOBALS[$key])) {
2019 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2022 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2032 // Converts a zero or NULL to word 'NULL'
2033 function convertZeroToNull ($number) {
2034 // Is it a valid username?
2035 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2037 $number = bigintval($number);
2039 // Is not valid or zero
2047 // Converts a NULL to zero
2048 function convertNullToZero ($number) {
2049 // Is it a valid username?
2050 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2052 $number = bigintval($number);
2054 // Is not valid or zero
2062 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2063 // Note: This function is cached
2064 function capitalizeUnderscoreString ($str) {
2066 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2067 // Init target string
2070 // Explode it with the underscore, but rewrite dashes to underscore before
2071 $strArray = explode('_', str_replace('-', '_', $str));
2073 // "Walk" through all elements and make them lower-case but first upper-case
2074 foreach ($strArray as $part) {
2075 // Capitalize the string part
2076 $capitalized .= firstCharUpperCase($part);
2079 // Store the converted string in cache array
2080 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2084 return $GLOBALS[__FUNCTION__][$str];
2087 // Generate admin links for mail order
2088 // mailType can be: 'mid' or 'bid'
2089 function generateAdminMailLinks ($mailType, $mailId) {
2094 // Default column for mail status is 'data_type'
2095 // @TODO Rename column data_type to e.g. mail_status
2096 $statusColumn = 'data_type';
2098 // Which mail do we have?
2099 switch ($mailType) {
2100 case 'bid': // Bonus mail
2104 case 'mid': // Member mail
2108 default: // Handle unsupported types
2109 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2110 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2114 // Is the mail type supported?
2115 if (!empty($table)) {
2116 // Query for the mail
2117 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2122 ), __FILE__, __LINE__);
2124 // Is there one entry there?
2125 if (SQL_NUMROWS($result) == 1) {
2127 $content = SQL_FETCHARRAY($result);
2129 // Add output and type
2130 $content['type'] = $mailType;
2131 $content['__output'] = '';
2134 $content = runFilterChain('generate_admin_mail_links', $content);
2137 $OUT = $content['__output'];
2141 SQL_FREERESULT($result);
2144 // Return generated HTML code
2150 * Determine if a string can represent a number in hexadecimal
2152 * @param $hex A string to check if it is hex-encoded
2153 * @return $foo True if the string is a hex, otherwise false
2154 * @author Marques Johansson
2155 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2157 function isHexadecimal ($hex) {
2158 // Make it lowercase
2159 $hex = strtolower(trim(ltrim($hex, '0')));
2161 // Fix empty strings to zero
2166 // Simply compare decode->encode result with original
2167 return ($hex == dechex(hexdec($hex)));
2171 * Replace chr(13) with "[r]" and chr(10) with "[n]" and add a final new-line to make
2172 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2173 * response handler functions.
2175 * @param $str String to overwork
2176 * @return $str Overworked string
2178 function replaceReturnNewLine ($str) {
2179 return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2182 // Converts a given string by splitting it up with given delimiter similar to
2183 // explode(), but appending the delimiter again
2184 function stringToArray ($delimiter, $string) {
2186 $strArray = array();
2188 // "Walk" through all entries
2189 foreach (explode($delimiter, $string) as $split) {
2190 // Append the delimiter and add it to the array
2191 array_push($strArray, $split . $delimiter);
2198 // Detects the prefix 'mb_' if a multi-byte string is given
2199 function detectMultiBytePrefix ($str) {
2200 // Default is without multi-byte
2203 // Detect multi-byte (strictly)
2204 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2205 // With multi-byte encoded string
2209 // Return the prefix
2213 // Searches given array for a sub-string match and returns all found keys in an array
2214 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2215 // Init array for all found keys
2218 // Now check all entries
2219 foreach ($needles as $key => $needle) {
2220 // Is there found a partial string?
2221 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2222 if (strpos($heystack, $needle, $offset) !== FALSE) {
2223 // Add the found key
2224 array_push($keys, $key);
2232 // Determines database column name from given subject and locked
2233 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2234 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2235 // Default is 'normal' points
2236 $pointsColumn = 'points';
2238 // Which points, locked or normal?
2239 if ($locked === TRUE) {
2240 $pointsColumn = 'locked_points';
2243 // Prepare array for filter
2244 $filterData = array(
2245 'subject' => $subject,
2246 'locked' => $locked,
2247 'column' => $pointsColumn
2251 $filterData = runFilterChain('determine_points_column_name', $filterData);
2253 // Extract column name from array
2254 $pointsColumn = $filterData['column'];
2257 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2258 return $pointsColumn;
2261 // Converts a boolean variable into 'Y' for true and 'N' for false
2262 function convertBooleanToYesNo ($boolean) {
2265 if ($boolean === TRUE) {
2274 // "Translates" 'true' to true and 'false' to false
2275 function convertStringToBoolean ($str) {
2276 // Debug message (to measure how often this function is called)
2277 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2280 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2281 // Trim it lower-case for validation
2282 $strTrimmed = trim(strtolower($str));
2285 if (!in_array($strTrimmed, array('true', 'false'))) {
2287 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2291 $GLOBALS[__FUNCTION__][$str] = (($strTrimmed == 'true') ? true : false);
2295 return $GLOBALS[__FUNCTION__][$str];
2299 * "Makes" a variable in given string parseable, this function will throw an
2300 * error if the first character is not a dollar sign.
2302 * @param $varString String which contains a variable
2303 * @return $return String with added single quotes for better parsing
2305 function makeParseableVariable ($varString) {
2306 // The first character must be a dollar sign
2307 if (substr($varString, 0, 1) != '$') {
2308 // Please report this
2309 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2313 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2314 // Snap them in, if [,] are there
2315 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2319 return $GLOBALS[__FUNCTION__][$varString];
2322 // "Getter" for random TAN
2323 function getRandomTan () {
2325 return mt_rand(0, 99999);
2328 // Removes any : from subject
2329 function removeDoubleDotFromSubject ($subject) {
2331 $subjectArray = explode(':', $subject);
2332 $subject = $subjectArray[0];
2333 unset($subjectArray);
2339 // Adds a given entry to the database
2340 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2347 // Set POST data generic userid
2348 setPostRequestElement('userid', getMemberId());
2350 // Call inner function
2351 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2353 // Entry has been added?
2354 if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2355 // Display success message
2356 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2358 // Display failed message
2359 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2363 // Edit rows by given id numbers
2364 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()) {
2365 // $tableName must be an array
2366 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2367 // No tableName specified
2368 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2369 } elseif (!is_array($idColumn)) {
2370 // $idColumn is no array
2371 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2372 } elseif (!is_array($userIdColumn)) {
2373 // $userIdColumn is no array
2374 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2375 } elseif (!is_array($editNow)) {
2376 // $editNow is no array
2377 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2380 // Shall we change here or list for editing?
2381 if ($editNow[0] === TRUE) {
2382 // Add generic userid field
2383 setPostRequestElement('userid', getMemberId());
2385 // Call generic change method
2386 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2389 if ($affected == countPostSelection($idColumn[0])) {
2391 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2393 // Some are still there :(
2394 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2398 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
2402 // Delete rows by given id numbers
2403 function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2404 // Do this only for members
2407 // $tableName must be an array
2408 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2409 // No tableName specified
2410 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2411 } elseif (!is_array($idColumn)) {
2412 // $idColumn is no array
2413 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2414 } elseif (!is_array($userIdColumn)) {
2415 // $userIdColumn is no array
2416 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2417 } elseif (!is_array($deleteNow)) {
2418 // $deleteNow is no array
2419 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2422 // Shall we delete here or list for deletion?
2423 if ($deleteNow[0] === TRUE) {
2424 // Add generic userid field
2425 setPostRequestElement('userid', getMemberId());
2427 // Call generic function
2428 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2431 if ($affected == countPostSelection($idColumn[0])) {
2433 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2435 // Some are still there :(
2436 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
2439 // List for deletion confirmation
2440 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
2444 // Build a special template list
2445 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
2446 // Do this only for logged in member
2449 // Call inner (general) function
2450 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId);
2453 // Checks whether given address is IPv4
2454 function isIp4AddressValid ($address) {
2456 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2458 $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);
2462 return $GLOBALS[__FUNCTION__][$address];
2465 // Returns the string if not empty or FALSE if empty
2466 function validateIsEmpty ($str) {
2468 $trimmed = trim($str);
2470 // Is the string empty?
2471 if (empty($trimmed)) {
2480 // ----------------------------------------------------------------------------
2481 // "Translatation" functions for points_data table
2482 // ----------------------------------------------------------------------------
2484 // Translates generically some data into a target string
2485 function translateGeneric ($messagePrefix, $data) {
2486 // Is the method null or empty?
2487 if (is_null($data)) {
2490 } elseif (empty($data)) {
2491 // Is empty (string)
2495 // Default column name is unknown
2496 $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
2498 // Construct message id
2499 $messageId = $messagePrefix . '_' . strtoupper($data);
2502 if (isMessageIdValid($messageId)) {
2503 // Then use it as message string
2504 $return = '{--' . $messageId . '--}';
2507 // Return the column name
2511 // Translates points subject to human-readable
2512 function translatePointsSubject ($subject) {
2514 $subject = removeDoubleDotFromSubject($subject);
2517 return translateGeneric('POINTS_SUBJECT', $subject);
2520 // "Translates" given points account type
2521 function translatePointsAccountType ($accountType) {
2523 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2526 // "Translates" given points "locked mode"
2527 function translatePointsLockedMode ($lockedMode) {
2529 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2532 // "Translates" given points payment method
2533 function translatePointsPaymentMethod ($paymentMethod) {
2535 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2538 // "Translates" given points account provider
2539 function translatePointsAccountProvider ($accountProvider) {
2541 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2544 // "Translates" given points notify recipient
2545 function translatePointsNotifyRecipient ($notifyRecipient) {
2547 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2550 // "Translates" given mode to a human-readable version
2551 function translatePointsMode ($pointsMode) {
2553 return translateGeneric('POINTS_MODE', $pointsMode);
2556 // "Translates" task type to a human-readable version
2557 function translateTaskType ($taskType) {
2559 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2562 //-----------------------------------------------------------------------------
2563 // Automatically re-created functions, all taken from user comments on www.php.net
2564 //-----------------------------------------------------------------------------
2565 if (!function_exists('html_entity_decode')) {
2566 // Taken from documentation on www.php.net
2567 function html_entity_decode ($string) {
2568 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2569 $trans_tbl = array_flip($trans_tbl);
2570 return strtr($string, $trans_tbl);