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']);
79 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - FROM ARRAY');
83 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - EXIT!');
87 // Generate a password in a specified length or use default password length
88 function generatePassword ($length = '0', $exclude = array()) {
89 // Auto-fix invalid length of zero
91 $length = getPassLen();
94 // Exclude some entries
95 $localAbc = array_diff($GLOBALS['_abc'], $exclude);
97 // $localAbc must have at least 10 entries
98 assert(count($localAbc) >= 10);
100 // Start creating password
102 while (strlen($password) < $length) {
103 $password .= $localAbc[mt_rand(0, count($localAbc) -1)];
107 * When the size is below 40 we can also add additional security by
108 * scrambling it. Otherwise the hash may corrupted..
110 if (strlen($password) <= 40) {
111 // Also scramble the password
112 $password = scrambleString($password);
115 // Return the password
119 // Generates a human-readable timestamp from the Uni* stamp
120 function generateDateTime ($time, $mode = '0') {
122 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
124 return $GLOBALS[__FUNCTION__][$time][$mode];
127 // If the stamp is zero it mostly didn't "happen"
128 if (($time == '0') || (is_null($time))) {
130 return '{--NEVER_HAPPENED--}';
133 // Filter out numbers
134 $timeSecured = bigintval($time);
137 switch (getLanguage()) {
138 case 'de': // German date / time format
140 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break;
141 case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break;
142 case '2': $ret = date('d.m.Y|H:i', $timeSecured); break;
143 case '3': $ret = date('d.m.Y', $timeSecured); break;
144 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
145 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
146 case '6': $ret = date('Ymd', $timeSecured); break;
147 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
149 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
154 default: // Default is the US date / time format!
156 case '0': $ret = date('r', $timeSecured); break;
157 case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break;
158 case '2': $ret = date('y-m-d|H:i', $timeSecured); break;
159 case '3': $ret = date('y-m-d', $timeSecured); break;
160 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
161 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
162 case '6': $ret = date('Ymd', $timeSecured); break;
163 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
165 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
171 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
177 // Translates Y/N to yes/no
178 function translateYesNo ($yn) {
180 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
182 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
184 case 'Y': $GLOBALS[__FUNCTION__][$yn] = '{--YES--}'; break;
185 case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break;
188 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $yn));
194 return $GLOBALS[__FUNCTION__][$yn];
197 // Translates the american decimal dot into a german comma
198 // OPPOMENT: convertCommaToDot()
199 function translateComma ($dotted, $cut = TRUE, $max = '0') {
200 // First, cast all to double, due to PHP changes
201 $dotted = (double) $dotted;
203 // Default is 3 you can change this in admin area "Settings -> Misc Options"
204 if (!isConfigEntrySet('max_comma')) {
205 setConfigEntry('max_comma', 3);
208 // Use from config is default
209 $maxComma = getConfig('max_comma');
211 // Use from parameter?
217 if (($cut === TRUE) && ($max == '0')) {
218 // Test for commata if in cut-mode
219 $com = explode('.', $dotted);
220 if (count($com) < 2) {
221 // Don't display commatas even if there are none... ;-)
229 $translated = $dotted;
230 switch (getLanguage()) {
231 case 'de': // German language
232 $translated = number_format($dotted, $maxComma, ',', '.');
235 default: // All others
236 $translated = number_format($dotted, $maxComma, '.', ',');
240 // Return translated value
241 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
245 // Translate Uni*-like gender to human-readable
246 function translateGender ($gender) {
248 $ret = '!' . $gender . '!';
250 // Male/female or company?
255 // Use generic function
256 $ret = translateGeneric('GENDER', $gender);
260 // Please report bugs on unknown genders
261 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
265 // Return translated gender
269 // "Translates" the user status
270 function translateUserStatus ($status) {
271 // Default status is unknown if something goes through
272 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
274 // Generate message depending on status
279 // Use generic function for all "normal" cases"
280 $ret = translateGeneric('ACCOUNT_STATUS', $status);
283 case '': // Account deleted
284 case NULL: // Account deleted
285 $ret = '{--ACCOUNT_STATUS_DELETED--}';
288 default: // Please report all unknown status
289 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
297 // "Translates" 'visible' and 'locked' to a CSS class
298 function translateMenuVisibleLocked ($content, $prefix = '') {
299 // Default is 'menu_unknown'
300 $content['visible_css'] = $prefix . 'menu_unknown';
302 // Translate 'visible' and keep an eye on the prefix
303 switch ($content['visible']) {
304 case 'Y': // Should be visible
305 $content['visible_css'] = $prefix . 'menu_visible';
308 case 'N': // Is invisible
309 $content['visible_css'] = $prefix . 'menu_invisible';
312 default: // Please report this
313 reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
317 // Translate 'locked' and keep an eye on the prefix
318 switch ($content['locked']) {
319 case 'Y': // Should be locked, only admins can call this
320 $content['locked_css'] = $prefix . 'menu_locked';
323 case 'N': // Is unlocked and visible to members/guests/sponsors
324 $content['locked_css'] = $prefix . 'menu_unlocked';
327 default: // Please report this
328 reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
332 // Return the resulting array
336 // Generates an URL for the dereferer
337 function generateDereferrerUrl ($url) {
338 // Don't de-refer our own links!
339 if ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
341 $encodedUrl = encodeString(compileUriCode($url));
344 $hash = generateHash($url . getSiteKey() . getDateKey());
346 // Log plain URL and hash
347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
350 $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie($hash) . '&salt=' . substr($hash, 0, getSaltLength()) . '%}';
357 // Generates an URL for the frametester
358 function generateFrametesterUrl ($url) {
359 // Prepare frametester URL
360 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
361 encodeString(compileUriCode($url))
364 // Return the new URL
365 return $frametesterUrl;
368 // Count entries from e.g. a selection box
369 function countSelection ($array) {
371 if (!is_array($array)) {
373 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
380 foreach ($array as $key => $selected) {
382 if (!empty($selected)) {
383 // Yes, then count it
388 // Return counted selections
392 // Generates a timestamp (some wrapper for mktime())
393 function makeTime ($hours, $minutes, $seconds, $stamp) {
394 // Extract day, month and year from given timestamp
395 $days = getDay($stamp);
396 $months = getMonth($stamp);
397 $years = getYear($stamp);
399 // Create timestamp for wished time which depends on extracted date
410 // Redirects to an URL and if neccessarry extends it with own base URL
411 function redirectToUrl ($url, $allowSpider = TRUE) {
412 // Is the output mode -2?
413 if (isAjaxOutputMode()) {
414 // This is always (!) an AJAX request and shall not be redirected
419 if (substr($url, 0, 6) == '{%url=') {
420 $url = substr($url, 6, -2);
424 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
426 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
427 $rel = ' rel="external"';
429 // Is there internal or external URL?
430 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
431 // Own (=internal) URL
435 // Three different ways to debug...
436 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
437 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
438 //* DEBUG: */ die($url);
440 // We should not sent a redirect if headers are already sent
441 if (!headers_sent()) {
442 // Load URL when headers are not sent
443 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE));
445 // Output error message
446 loadInclude('inc/header.php');
447 loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
448 loadInclude('inc/footer.php');
451 // Shut the mailer down here
455 /************************************************************************
457 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
458 * $a_sort sortiert: *
460 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
461 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
462 * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
463 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
464 * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
466 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
467 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
468 * Sie, dass es doch nicht so schwer ist! :-) *
470 ************************************************************************/
471 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
472 $temporaryArray = $array;
473 while ($primary_key < count($a_sort)) {
474 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
475 foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
477 if ($nums === FALSE) {
478 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
479 if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
480 } elseif ($key != $key2) {
481 // Sort numbers (E.g.: 9 < 10)
482 if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
483 if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
487 // We have found two different values, so let's sort whole array
488 foreach ($temporaryArray as $sort_key => $sort_val) {
489 $t = $temporaryArray[$sort_key][$key];
490 $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
491 $temporaryArray[$sort_key][$key2] = $t;
502 // Write back sorted array
503 $array = $temporaryArray;
508 // Deprecated : $length (still has one reference in this function)
509 // Optional : $extraData
511 function generateRandomCode ($length, $code, $userid, $extraData = '') {
512 // Build server string
513 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
516 $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
517 if (isConfigEntrySet('secret_key')) {
518 $keys .= getEncryptSeparator() . getSecretKey();
520 if (isConfigEntrySet('file_hash')) {
521 $keys .= getEncryptSeparator() . getFileHash();
523 $keys .= getEncryptSeparator() . getDateFromRepository();
524 if (isConfigEntrySet('master_salt')) {
525 $keys .= getEncryptSeparator() . getMasterSalt();
528 // Build string from misc data
529 $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
531 // Add more additional data
532 if (isSessionVariableSet('u_hash')) {
533 $data .= getEncryptSeparator() . getSession('u_hash');
536 // Add referral id, language, theme and userid
537 $data .= getEncryptSeparator() . determineReferralId();
538 $data .= getEncryptSeparator() . getLanguage();
539 $data .= getEncryptSeparator() . getCurrentTheme();
540 $data .= getEncryptSeparator() . getMemberId();
542 // Calculate number for generating the code
543 $a = $code + getConfig('_ADD') - 1;
545 if (isConfigEntrySet('master_salt')) {
546 // Generate hash with master salt from modula of number with the prime number and other data
547 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
549 // Generate hash with "hash of site key" from modula of number with the prime number and other data
550 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
553 // Create number from hash
554 $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
556 // At least 10 numbers shall be secure enought!
557 if (isExtensionActive('other')) {
558 $len = getCodeLength();
563 // Smaller 1 is not okay
569 // Cut off requested counts of number, but skip first digit (which is mostly a zero)
570 $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
572 // Done building code
576 // Does only allow numbers
577 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
578 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
579 // Filter all non-number chars out, so only number chars will remain
580 $ret = preg_replace('/[^0123456789]/', '', $num);
583 if ($castValue === TRUE) {
584 // Cast to biggest numeric type
585 $ret = (double) $ret;
588 // Has the whole value changed?
589 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
591 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
595 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
599 // Creates a Uni* timestamp from given selection data and prefix
600 function createEpocheTimeFromSelections ($prefix, $postData) {
601 // Initial return value
604 // Is there a leap year?
606 $TEST = getYear() / 4;
609 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
610 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) {
611 $SWITCH = getOneDay();
614 // First add years...
615 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
618 $ret += $postData[$prefix . '_mo'] * 2628000;
621 $ret += $postData[$prefix . '_we'] * 604800;
624 $ret += $postData[$prefix . '_da'] * 86400;
627 $ret += $postData[$prefix . '_ho'] * 3600;
630 $ret += $postData[$prefix . '_mi'] * 60;
632 // And at last seconds...
633 $ret += $postData[$prefix . '_se'];
635 // Return calculated value
639 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
640 function createFancyTime ($stamp) {
641 // Get data array with years/months/weeks/days/...
642 $data = createTimeSelections($stamp, '', '', '', TRUE);
644 foreach ($data as $k => $v) {
646 // Value is greater than 0 "eval" data to return string
647 $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
652 // Is something there?
654 // Remove leading commata and space
655 $ret = substr($ret, 2);
658 $ret = '0 {--TIME_UNIT_SECOND--}';
661 // Return fancy time string
665 // Taken from www.php.net isInStringIgnoreCase() user comments
666 function isEmailValid ($email) {
667 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
670 if (!isset($GLOBALS[__FUNCTION__][$email])) {
671 // Check first part of email address
672 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
675 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
678 $regex = '@^' . $first . '\@' . $domain . '$@iU';
681 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
684 // Return check result
685 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
686 return $GLOBALS[__FUNCTION__][$email];;
689 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
690 function isUrlValid ($url, $compile = TRUE) {
692 $url = trim(urldecode($url));
693 //* DEBUG: */ debugOutput($url);
695 // Compile some chars out...
696 if ($compile === TRUE) {
697 $url = compileUriCode($url, FALSE, FALSE, FALSE);
699 //* DEBUG: */ debugOutput($url);
701 // Check for the extension filter
702 if (isExtensionActive('filter')) {
703 // Use the extension's filter set
704 return FILTER_VALIDATE_URL($url, FALSE);
708 * If not installed, perform a simple test. Just make it sure there is always a
709 * http:// or https:// in front of the URLs.
711 return isUrlValidSimple($url);
714 // Generate a hash for extra-security for all passwords
715 function generateHash ($plainText, $salt = '', $hash = TRUE) {
717 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
719 // Is the required extension 'sql_patches' there and a salt is not given?
720 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
721 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
722 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
723 if ($hash === TRUE) {
725 return md5($plainText);
732 // Is an arry element missing here?
733 if (!isConfigEntrySet('file_hash')) {
735 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
738 // When the salt is empty build a new one, else use the first x configured characters as the salt
740 // Build server string for more entropy
741 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
744 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
747 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
749 // Calculate number for generating the code
750 $a = time() + getConfig('_ADD') - 1;
752 // Generate SHA1 sum from modula of number and the prime number
753 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
754 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
755 $sha1 = scrambleString($sha1);
756 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
757 //* DEBUG: */ $sha1b = descrambleString($sha1);
758 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
760 // Generate the password salt string
761 $salt = substr($sha1, 0, getSaltLength());
762 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
765 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
766 $salt = substr($salt, 0, getSaltLength());
767 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
769 // Sanity check on salt
770 if (strlen($salt) != getSaltLength()) {
772 reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
776 // Generate final hash (for debug output)
777 $finalHash = $salt . sha1($salt . $plainText);
780 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
787 function scrambleString ($str) {
791 // Final check, in case of failure it will return unscrambled string
792 if (strlen($str) > 40) {
793 // The string is to long
795 } elseif (strlen($str) == 40) {
797 $scrambleNums = explode(':', getPassScramble());
799 // Generate new numbers
800 $scrambleNums = explode(':', genScrambleString(strlen($str)));
803 // Compare both lengths and abort if different
804 if (strlen($str) != count($scrambleNums)) {
808 // Scramble string here
809 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
810 for ($idx = 0; $idx < strlen($str); $idx++) {
811 // Get char on scrambled position
812 $char = substr($str, $scrambleNums[$idx], 1);
814 // Add it to final output string
818 // Return scrambled string
819 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
823 // De-scramble a string scrambled by scrambleString()
824 function descrambleString ($str) {
825 // Scramble only 40 chars long strings
826 if (strlen($str) != 40) {
830 // Load numbers from config
831 $scrambleNums = explode(':', getPassScramble());
834 if (count($scrambleNums) != 40) {
838 // Begin descrambling
839 $orig = str_repeat(' ', 40);
840 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
841 for ($idx = 0; $idx < 40; $idx++) {
842 $char = substr($str, $idx, 1);
843 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
846 // Return scrambled string
847 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
851 // Generated a "string" for scrambling
852 function genScrambleString ($len) {
853 // Prepare array for the numbers
854 $scrambleNumbers = array();
856 // First we need to setup randomized numbers from 0 to 31
857 for ($idx = 0; $idx < $len; $idx++) {
859 $rand = mt_rand(0, ($len - 1));
861 // Check for it by creating more numbers
862 while (array_key_exists($rand, $scrambleNumbers)) {
863 $rand = mt_rand(0, ($len - 1));
867 $scrambleNumbers[$rand] = $rand;
870 // So let's create the string for storing it in database
871 $scrambleString = implode(':', $scrambleNumbers);
872 return $scrambleString;
875 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
876 function encodeHashForCookie ($passHash) {
877 // Return vanilla password hash
880 // Is a secret key and master salt already initialized?
881 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
882 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
883 // Only calculate when the secret key is generated
884 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
885 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
886 // Both keys must have same length so return unencrypted
887 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
891 $newHash = ''; $start = 9;
892 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
893 for ($idx = 0; $idx < 20; $idx++) {
894 // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
895 $part1 = hexdec(substr($passHash , $start, 2));
896 $part2 = hexdec(substr(getSecretKey(), $start, 2));
898 // Default is hexadecimal of index if both are same
900 // Is part1 larger or part2 than its counter part?
901 if ($part1 > $part2) {
903 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
904 } elseif ($part2 > $part1) {
906 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
909 $mod = substr($mod, 0, 2);
910 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
911 $mod = str_pad($mod, 2, '0', STR_PAD_LEFT);
912 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
917 // Just copy it over, as the master salt is not really helpful here
918 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
923 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
927 // Fix "deleted" cookies
928 function fixDeletedCookies ($cookies) {
929 // Is this an array with entries?
930 if ((is_array($cookies)) && (count($cookies) > 0)) {
931 // Then check all cookies if they are marked as deleted!
932 foreach ($cookies as $cookieName) {
933 // Is the cookie set to "deleted"?
934 if (getSession($cookieName) == 'deleted') {
935 setSession($cookieName, '');
941 // Checks if a given apache module is loaded
942 function isApacheModuleLoaded ($apacheModule) {
943 // Check it and return result
944 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
947 // Get current theme name
948 function getCurrentTheme () {
949 // The default theme is 'default'... ;-)
952 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
953 if (isExtensionActive('theme')) {
955 $ret = getActualTheme();
956 } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) {
957 // Use value from POST data
958 $ret = postRequestElement('theme');
959 } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) {
960 // Use value from GET data
961 $ret = getRequestElement('theme');
962 } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) {
963 // Use value from GET data
964 $ret = getMailerTheme();
967 // Return theme value
971 // Generates an error code from given account status
972 function generateErrorCodeFromUserStatus ($status = '') {
973 // If no status is provided, use the default, cached
974 if ((empty($status)) && (isMember())) {
976 $status = getUserData('status');
979 // Default error code if unknown account status
980 $errorCode = getCode('ACCOUNT_UNKNOWN');
982 // Generate constant name
983 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
985 // Is the constant there?
986 if (isCodeSet($codeName)) {
988 $errorCode = getCode($codeName);
991 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
998 // Back-ported from the new ship-simu engine. :-)
999 function debug_get_printable_backtrace () {
1001 $backtrace = '<ol>';
1003 // Get and prepare backtrace for output
1004 $backtraceArray = debug_backtrace();
1005 foreach ($backtraceArray as $key => $trace) {
1006 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1007 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1008 if (!isset($trace['args'])) $trace['args'] = array();
1009 $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>';
1013 $backtrace .= '</ol>';
1015 // Return the backtrace
1019 // A mail-able backtrace
1020 function debug_get_mailable_backtrace () {
1024 // Get and prepare backtrace for output
1025 $backtraceArray = debug_backtrace();
1026 foreach ($backtraceArray as $key => $trace) {
1027 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1028 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1029 if (!isset($trace['args'])) $trace['args'] = array();
1030 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1033 // Return the backtrace
1037 // Generates a ***weak*** seed
1038 function generateSeed () {
1039 return microtime(TRUE) * 100000;
1042 // Converts a message code to a human-readable message
1043 function getMessageFromErrorCode ($code) {
1044 // Default is an unknown error code
1045 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1047 // Which code is provided?
1050 // No error code is bad coding practice
1051 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1054 // All error messages
1055 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1056 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1057 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1058 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1059 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1060 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1061 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1062 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1063 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1064 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1065 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1066 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1067 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1068 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1069 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1070 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1071 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1072 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1073 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1074 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1075 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1076 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1077 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1078 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1079 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1080 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1081 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1082 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1083 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1084 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1085 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1086 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1087 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1089 case getCode('ERROR_MAILID'):
1090 if (isExtensionActive('mailid', TRUE)) {
1091 $message = '{--ERROR_CONFIRMING_MAIL--}';
1093 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1097 case getCode('EXTENSION_PROBLEM'):
1098 if (isGetRequestElementSet('ext')) {
1099 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1101 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1105 case getCode('URL_TIME_LOCK'):
1106 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1107 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1108 array(bigintval(getRequestElement('id'))), __FUNCTION__, __LINE__);
1110 // Load timestamp from last order
1111 $content = SQL_FETCHARRAY($result);
1114 SQL_FREERESULT($result);
1116 // Translate it for templates
1117 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1119 // Calculate hours...
1120 $content['hours'] = round(getUrlTlock() / 60 / 60);
1123 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1126 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1128 // Finally contruct the message
1129 $message = loadTemplate('tlock_message', TRUE, $content);
1133 // Log missing/invalid error codes
1134 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1138 // Return the message
1142 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1143 function isUrlValidSimple ($url) {
1144 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1146 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1148 // Allows http and https
1149 $http = "(http|https)+(:\/\/)";
1151 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1152 // Test double-domains (e.g. .de.vu)
1153 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1155 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1157 $dir = "((/)+([-_\.[:alnum:]])+)*";
1159 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1160 // ... and the string after and including question character
1161 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1162 // Pattern for URLs like http://url/dir/doc.html?var=value
1163 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1164 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1165 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1166 // Pattern for URLs like http://url/dir/?var=value
1167 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1168 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1169 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1170 // Pattern for URLs like http://url/dir/page.ext
1171 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1172 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1173 $pattern['ipdp'] = $http . $ip . $dir . $page;
1174 // Pattern for URLs like http://url/dir
1175 $pattern['d1d'] = $http . $domain1 . $dir;
1176 $pattern['d2d'] = $http . $domain2 . $dir;
1177 $pattern['ipd'] = $http . $ip . $dir;
1178 // Pattern for URLs like http://url/?var=value
1179 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1180 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1181 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1182 // Pattern for URLs like http://url?var=value
1183 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1184 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1185 $pattern['ipg12'] = $http . $ip . $getstring1;
1187 // Test all patterns
1189 foreach ($pattern as $key => $pat) {
1191 if (isDebugRegularExpressionEnabled()) {
1192 // @TODO Are these convertions still required?
1193 $pat = str_replace('.', '\.', $pat);
1194 $pat = str_replace('@', '\@', $pat);
1195 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1198 // Check if expression matches
1199 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1202 if ($reg === TRUE) {
1207 // Return true/false
1208 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1212 // Wtites data to a config.php-style file
1213 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1214 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek = 0) {
1215 // Initialize some variables
1221 // Is the file there and read-/write-able?
1222 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1223 $search = 'CFG: ' . $comment;
1224 $tmp = $FQFN . '.tmp';
1226 // Open the source file
1227 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1229 // Is the resource valid?
1230 if (is_resource($fp)) {
1231 // Open temporary file
1232 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1234 // Is the resource again valid?
1235 if (is_resource($fp_tmp)) {
1236 // Mark temporary file as readable
1237 $GLOBALS['file_readable'][$tmp] = TRUE;
1240 while (!feof($fp)) {
1241 // Read from source file
1242 $line = fgets($fp, 1024);
1244 if (isInString($search, $line)) {
1250 if ($next === $seek) {
1252 $line = $prefix . $inserted . $suffix . PHP_EOL;
1258 // Write to temp file
1259 fwrite($fp_tmp, $line);
1265 // Finished writing tmp file
1269 // Close source file
1272 if (($done === TRUE) && ($found === TRUE)) {
1273 // Copy back temporary->FQFN file and ...
1274 copyFileVerified($tmp, $FQFN, 0644);
1276 // ... delete temporay file :-)
1277 return removeFile($tmp);
1278 } elseif ($found === FALSE) {
1280 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!');
1282 // Temporary file not fully written
1283 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - Temporary file unfinished!');
1287 // File not found, not readable or writeable
1288 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN) . ',comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek);
1291 // An error was detected!
1295 // Debug message logger
1296 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1297 // Is debug mode enabled?
1298 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1300 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1302 // Log this message away
1303 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1307 // Handle extra values
1308 function handleExtraValues ($filterFunction, $value, $extraValue) {
1309 // Default is the value itself
1312 // Is there a special filter function?
1313 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1314 // Call-back function does not exist or is empty
1315 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1318 // Is there extra parameters here?
1319 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1320 // Put both parameters in one new array by default
1321 $args = array($value, $extraValue);
1323 // If we have an array simply use it and pre-extend it with our value
1324 if (is_array($extraValue)) {
1325 // Make the new args array
1326 $args = merge_array(array($value), $extraValue);
1329 // Call the multi-parameter call-back
1330 $ret = call_user_func_array($filterFunction, $args);
1333 if ($ret === TRUE) {
1334 // Test passed, so write direct value
1338 // One parameter call
1339 $ret = call_user_func($filterFunction, $value);
1340 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1343 if ($ret === TRUE) {
1344 // Test passed, so write direct value
1353 // Tries to determine if call-back functions and/or extra values shall be parsed
1354 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1355 // Debug mode enabled?
1356 if (isDebugModeEnabled()) {
1358 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1361 // Send data through the filter function if found
1362 if ($key === $userIdColumn[0]) {
1363 // Is the userid, we have to process it with convertZeroToNull()
1364 $entries = convertZeroToNull($entries);
1365 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1366 // Debug mode enabled?
1367 if (isDebugModeEnabled()) {
1369 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1372 // Filter function + extra value set
1373 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1375 // Debug mode enabled?
1376 if (isDebugModeEnabled()) {
1378 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1380 } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1381 // Debug mode enabled?
1382 if (isDebugModeEnabled()) {
1384 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1387 // Handle extra values
1388 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1390 // Debug mode enabled?
1391 if (isDebugModeEnabled()) {
1393 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1396 // Make sure entries is not bool, then something went wrong
1397 assert(!is_bool($entries));
1398 } elseif (!empty($filterFunctions[$search])) {
1399 // Debug mode enabled?
1400 if (isDebugModeEnabled()) {
1402 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1405 // Handle extra values
1406 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1408 // Debug mode enabled?
1409 if (isDebugModeEnabled()) {
1411 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1414 // Make sure entries is not bool, then something went wrong
1415 assert(!is_bool($entries));
1422 // Converts timestamp selections into a timestamp
1423 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1424 // Init test variable
1428 // Get last three chars
1429 $test = substr($id, -3);
1431 // Improved way of checking! :-)
1432 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1433 // Found a multi-selection for timings?
1434 $test = substr($id, 0, -3);
1435 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)) {
1436 // Generate timestamp
1437 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1438 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1439 $GLOBALS['skip_config'][$test] = TRUE;
1441 // Remove data from array
1442 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1443 unset($postData[$test . '_' . $rem]);
1454 // Reverts the german decimal comma into Computer decimal dot
1455 // OPPOMENT: translateComma()
1456 function convertCommaToDot ($str) {
1457 // Default float is not a float... ;-)
1460 // Which language is selected?
1461 switch (getLanguage()) {
1462 case 'de': // German language
1463 // Remove german thousand dots first
1464 $str = str_replace('.', '', $str);
1466 // Replace german commata with decimal dot and cast it
1467 $float = sprintf('%01.5f', str_replace(',', '.', $str));
1470 default: // US and so on
1471 // Remove thousand commatas first and cast
1472 $float = sprintf('%01.5f', str_replace(',', '', $str));
1480 // Handle menu-depending failed logins and return the rendered content
1481 function handleLoginFailures ($accessLevel) {
1482 // Default output is empty ;-)
1485 // Is the session data set?
1486 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1487 // Ignore zero values
1488 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1489 // Non-guest has login failures found, get both data and prepare it for template
1490 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1492 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1493 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1497 $OUT = loadTemplate('login_failures', TRUE, $content);
1500 // Reset session data
1501 setSession('mailer_' . $accessLevel . '_failures', '');
1502 setSession('mailer_' . $accessLevel . '_last_failure', '');
1505 // Return rendered content
1510 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1512 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1514 // Shall I remove the cache file?
1515 if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1516 // Rebuild cache only in HTML output-mode
1517 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1519 $GLOBALS['cache_instance']->removeCacheFile($force);
1522 // Include file given?
1525 $inc = sprintf("inc/loader/load-%s.php", $inc);
1527 // Is the include there?
1528 if (isIncludeReadable($inc)) {
1529 // And rebuild it from scratch
1530 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1533 // Include not found
1534 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1540 // Determines the real remote address
1541 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1542 // Default is 127.0.0.1
1543 $address = '127.0.0.1';
1545 // Is a proxy in use?
1546 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1548 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1549 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1550 // Yet, another proxy
1551 $address = $_SERVER['HTTP_CLIENT_IP'];
1552 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1553 // The regular address when no proxy was used
1554 $address = $_SERVER['REMOTE_ADDR'];
1557 // This strips out the real address from proxy output
1558 if (strstr($address, ',')) {
1559 $addressArray = explode(',', $address);
1560 $address = $addressArray[0];
1563 // Return the result
1567 // Adds a bonus mail to the queue
1568 // This is a high-level function!
1569 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1570 // Use mode from data if not set and availble ;-)
1571 if ((empty($mode)) && (isset($data['mail_mode']))) {
1572 $mode = $data['mail_mode'];
1575 // Generate receiver list
1576 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1579 if (!empty($receiver)) {
1580 // Add bonus mail to queue
1581 addBonusMailToQueue(
1593 // Mail inserted into bonus pool
1594 if ($output === TRUE) {
1595 displayMessage('{--ADMIN_BONUS_SEND--}');
1597 } elseif ($output === TRUE) {
1598 // More entered than can be reached!
1599 displayMessage('{--ADMIN_MORE_SELECTED--}');
1602 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1606 // Enables the reset mode and runs it
1607 function doReset () {
1608 // Enable the reset mode
1609 $GLOBALS['reset_enabled'] = TRUE;
1612 runFilterChain('reset');
1615 // Enables the reset mode (hourly, weekly and monthly) and runs it
1616 function doHourly () {
1617 // Enable the hourly reset mode
1618 $GLOBALS['hourly_enabled'] = TRUE;
1620 // Run filters (one always!)
1621 runFilterChain('hourly');
1624 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1625 function doShutdown () {
1626 // Call the filter chain 'shutdown'
1627 runFilterChain('shutdown', NULL);
1629 // Check if link is up
1630 if (SQL_IS_LINK_UP()) {
1632 SQL_CLOSE(__FUNCTION__, __LINE__);
1633 } elseif (!isInstallationPhase()) {
1635 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1638 // Stop executing here
1643 function initMemberId () {
1644 $GLOBALS['member_id'] = '0';
1647 // Setter for member id
1648 function setMemberId ($memberid) {
1649 // We should not set member id to zero
1650 if ($memberid == '0') {
1651 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1655 $GLOBALS['member_id'] = bigintval($memberid);
1658 // Getter for member id or returns zero
1659 function getMemberId () {
1660 // Default member id
1663 // Is the member id set?
1664 if (isMemberIdSet()) {
1666 $memberid = $GLOBALS['member_id'];
1673 // Checks ether the member id is set
1674 function isMemberIdSet () {
1675 return (isset($GLOBALS['member_id']));
1678 // Setter for extra title
1679 function setExtraTitle ($extraTitle) {
1680 $GLOBALS['extra_title'] = $extraTitle;
1683 // Getter for extra title
1684 function getExtraTitle () {
1685 // Is the extra title set?
1686 if (!isExtraTitleSet()) {
1687 // No, then abort here
1688 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1692 return $GLOBALS['extra_title'];
1695 // Checks if the extra title is set
1696 function isExtraTitleSet () {
1697 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1701 * Reads a directory recursively by default and searches for files not matching
1702 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1703 * a whole directory.
1705 * @param $baseDir Relative base directory to PATH to scan from
1706 * @param $prefix Prefix for all positive matches (which files should be found)
1707 * @param $fileIncludeDirs whether to include directories in the final output array
1708 * @param $addBaseDir whether to add $baseDir to all array entries
1709 * @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'
1710 * @param $extension File extension for all positive matches
1711 * @param $excludePattern Regular expression to exclude more files (preg_match())
1712 * @param $recursive whether to scan recursively
1713 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1714 * @return $foundMatches All found positive matches for above criteria
1716 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
1717 // Add default entries we should always exclude
1718 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1720 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1721 // Init found includes
1722 $foundMatches = array();
1725 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1728 while ($baseFile = readdir($dirPointer)) {
1729 // Exclude '.', '..' and entries in $excludeArray automatically
1730 if (in_array($baseFile, $excludeArray, TRUE)) {
1732 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1736 // Construct include filename and FQFN
1737 $fileName = $baseDir . $baseFile;
1738 $FQFN = getPath() . $fileName;
1740 // Remove double slashes
1741 $FQFN = str_replace('//', '/', $FQFN);
1743 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1744 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1746 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1752 // Skip also files with non-matching prefix genericly
1753 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1754 // Is a redirectory so read it as well
1755 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1757 // And skip further processing
1759 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1761 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1763 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1764 // Skip wrong suffix as well
1765 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1767 } elseif (!isFileReadable($FQFN)) {
1768 // Not readable so skip it
1769 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1770 } elseif (filesize($FQFN) < 50) {
1771 // Might be deprecated
1772 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1774 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1775 // This PHP script is deprecated
1776 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1780 // Get file' extension (last 4 chars)
1781 $fileExtension = substr($baseFile, -4, 4);
1783 // Is the file a PHP script or other?
1784 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1785 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1786 // Is this a valid include file?
1787 if ($extension == '.php') {
1788 // Remove both for extension name
1789 $extName = substr($baseFile, strlen($prefix), -4);
1791 // Add file with or without base path
1792 if ($addBaseDir === TRUE) {
1794 array_push($foundMatches, $fileName);
1797 array_push($foundMatches, $baseFile);
1800 // We found .php file but should not search for them, why?
1801 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1803 } elseif ($fileExtension == $extension) {
1804 // Other, generic file found
1805 array_push($foundMatches, $fileName);
1810 closedir($dirPointer);
1813 sort($foundMatches);
1815 // Return array with include files
1816 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1817 return $foundMatches;
1820 // Checks whether $prefix is found in $fileName
1821 function isFilePrefixFound ($fileName, $prefix) {
1822 // @TODO Find a way to cache this
1823 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1826 // Maps a module name into a database table name
1827 function mapModuleToTable ($moduleName) {
1828 // Map only these, still lame code...
1829 switch ($moduleName) {
1830 case 'index': // 'index' is the guest's menu
1831 $moduleName = 'guest';
1834 case 'login': // ... and 'login' the member's menu
1835 $moduleName = 'member';
1837 // Anything else will not be mapped, silently.
1844 // Add SQL debug data to array for later output
1845 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1847 if (!isset($GLOBALS['debug_sql_available'])) {
1848 // Check it and cache it in $GLOBALS
1849 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1852 // Don't execute anything here if we don't need or ext-other is missing
1853 if ($GLOBALS['debug_sql_available'] === FALSE) {
1857 // Already executed?
1858 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1859 // Then abort here, we don't need to profile a query twice
1863 // Remeber this as profiled (or not, but we don't care here)
1864 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
1868 'num_rows' => SQL_NUMROWS($result),
1869 'affected' => SQL_AFFECTEDROWS(),
1870 'sql_str' => $sqlString,
1871 'timing' => $timing,
1872 'file' => basename($F),
1877 array_push($GLOBALS['debug_sqls'], $record);
1880 // Initializes the cache instance
1881 function initCacheInstance () {
1882 // Check for double-initialization
1883 if (isset($GLOBALS['cache_instance'])) {
1884 // This should not happen and must be fixed
1885 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1888 // Load include for CacheSystem class
1889 loadIncludeOnce('inc/classes/cachesystem.class.php');
1891 // Initialize cache system only when it's needed
1892 $GLOBALS['cache_instance'] = new CacheSystem();
1895 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1896 // Failed to initialize cache sustem
1897 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1901 // Getter for message from array or raw message
1902 function getMessageFromIndexedArray ($message, $pos, $array) {
1903 // Check if the requested message was found in array
1904 if (isset($array[$pos])) {
1905 // ... if yes then use it!
1906 $ret = $array[$pos];
1908 // ... else use default message
1916 // Convert ';' to ', ' for e.g. receiver list
1917 function convertReceivers ($old) {
1918 return str_replace(';', ', ', $old);
1921 // Get a module from filename and access level
1922 function getModuleFromFileName ($file, $accessLevel) {
1923 // Default is 'invalid';
1924 $modCheck = 'invalid';
1926 // @TODO This is still very static, rewrite it somehow
1927 switch ($accessLevel) {
1929 $modCheck = 'admin';
1935 $modCheck = getModule();
1938 default: // Unsupported file name / access level
1939 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1947 // Encodes an URL for adding session id, etc.
1948 function encodeUrl ($url, $outputMode = '0') {
1949 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
1950 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1951 // Raw output mode detected or session_name() found in URL
1955 // Is there a valid session?
1956 if ((!isSessionValid()) && (!isSpider())) {
1957 // Determine right separator
1958 $separator = '&';
1959 if (!isInString('?', $url)) {
1964 // Then add it to URL
1965 $url .= $separator . session_name() . '=' . session_id();
1969 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1971 $url = '{?URL?}/' . $url;
1975 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
1977 // Is there to decode entities?
1978 if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
1979 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
1980 // Decode them for e.g. JavaScript parts
1981 $url = decodeEntities($url);
1982 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
1986 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
1988 // Return the encoded URL
1992 // Simple check for spider
1993 function isSpider () {
1994 // Get the UA and trim it down
1995 $userAgent = trim(detectUserAgent(TRUE));
1997 // It should not be empty, if so it is better a browser
1998 if (empty($userAgent)) {
1999 // It is a browser that blocks its UA string
2004 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2007 // Function to search for the last modified file
2008 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2010 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2011 // Does it match what we are looking for? (We skip a lot files already!)
2012 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2013 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2015 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2016 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2018 // Walk through all entries
2019 foreach ($ds as $d) {
2020 // Generate proper FQFN
2021 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2023 // Is it a file and readable?
2024 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2025 if (isFileReadable($FQFN)) {
2026 // $FQFN is a readable file so extract the requested data from it
2027 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2028 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2030 // Is the file more recent?
2031 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2032 // This file is newer as the file before
2033 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2034 $last_changed['path_name'] = $FQFN;
2035 $last_changed[$lookFor] = $check;
2039 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2044 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2045 function handleFieldWithBraces ($field) {
2046 // Are there braces [] at the end?
2047 if (substr($field, -2, 2) == '[]') {
2049 * Try to find one and replace it. I do it this way to allow easy
2050 * extending of this code.
2052 foreach (array('admin_list_builder_id_value') as $key) {
2053 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2054 // Is the cache entry set?
2055 if (isset($GLOBALS[$key])) {
2057 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2060 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2070 // Converts a zero or NULL to word 'NULL'
2071 function convertZeroToNull ($number) {
2072 // Is it a valid username?
2073 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2075 $number = bigintval($number);
2077 // Is not valid or zero
2085 // Converts a NULL to zero
2086 function convertNullToZero ($number) {
2087 // Is it a valid username?
2088 if ((is_null($number)) || (empty($number)) || ($number < 1)) {
2089 // Is not valid or zero
2097 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2098 // Note: This function is cached
2099 function capitalizeUnderscoreString ($str) {
2101 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2102 // Init target string
2105 // Explode it with the underscore, but rewrite dashes to underscore before
2106 $strArray = explode('_', str_replace('-', '_', $str));
2108 // "Walk" through all elements and make them lower-case but first upper-case
2109 foreach ($strArray as $part) {
2110 // Capitalize the string part
2111 $capitalized .= firstCharUpperCase($part);
2114 // Store the converted string in cache array
2115 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2119 return $GLOBALS[__FUNCTION__][$str];
2122 // Generate admin links for mail order
2123 // mailType can be: 'mid' or 'bid'
2124 function generateAdminMailLinks ($mailType, $mailId) {
2129 // Default column for mail status is 'data_type'
2130 // @TODO Rename column data_type to e.g. mail_status
2131 $statusColumn = 'data_type';
2133 // Which mail do we have?
2134 switch ($mailType) {
2135 case 'bid': // Bonus mail
2139 case 'mid': // Member mail
2143 default: // Handle unsupported types
2144 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2145 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2149 // Is the mail type supported?
2150 if (!empty($table)) {
2151 // Query for the mail
2152 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2157 ), __FILE__, __LINE__);
2159 // Is there one entry there?
2160 if (SQL_NUMROWS($result) == 1) {
2162 $content = SQL_FETCHARRAY($result);
2164 // Add output and type
2165 $content['type'] = $mailType;
2166 $content['__output'] = '';
2169 $content = runFilterChain('generate_admin_mail_links', $content);
2172 $OUT = $content['__output'];
2176 SQL_FREERESULT($result);
2179 // Return generated HTML code
2185 * Determine if a string can represent a number in hexadecimal
2187 * @param $hex A string to check if it is hex-encoded
2188 * @return $foo True if the string is a hex, otherwise false
2189 * @author Marques Johansson
2190 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2192 function isHexadecimal ($hex) {
2193 // Make it lowercase
2194 $hex = strtolower(trim(ltrim($hex, '0')));
2196 // Fix empty strings to zero
2201 // Simply compare decode->encode result with original
2202 return ($hex == dechex(hexdec($hex)));
2206 * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2207 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2208 * response handler functions.
2210 * @param $str String to overwork
2211 * @return $str Overworked string
2213 function replaceReturnNewLine ($str) {
2214 return str_replace(array(chr(13), PHP_EOL), array('[r]', '[n]'), $str);
2217 // Converts a given string by splitting it up with given delimiter similar to
2218 // explode(), but appending the delimiter again
2219 function stringToArray ($delimiter, $string) {
2221 $strArray = array();
2223 // "Walk" through all entries
2224 foreach (explode($delimiter, $string) as $split) {
2225 // Append the delimiter and add it to the array
2226 array_push($strArray, $split . $delimiter);
2233 // Detects the prefix 'mb_' if a multi-byte string is given
2234 function detectMultiBytePrefix ($str) {
2235 // Default is without multi-byte
2238 // Detect multi-byte (strictly)
2239 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2240 // With multi-byte encoded string
2244 // Return the prefix
2248 // Searches given array for a sub-string match and returns all found keys in an array
2249 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2250 // Init array for all found keys
2253 // Now check all entries
2254 foreach ($needles as $key => $needle) {
2255 // Is there found a partial string?
2256 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2257 if (strpos($heystack, $needle, $offset) !== FALSE) {
2258 // Add the found key
2259 array_push($keys, $key);
2267 // Determines database column name from given subject and locked
2268 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2269 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2270 // Default is 'normal' points
2271 $pointsColumn = 'points';
2273 // Which points, locked or normal?
2274 if ($locked === TRUE) {
2275 $pointsColumn = 'locked_points';
2278 // Prepare array for filter
2279 $filterData = array(
2280 'subject' => $subject,
2281 'locked' => $locked,
2282 'column' => $pointsColumn
2286 $filterData = runFilterChain('determine_points_column_name', $filterData);
2288 // Extract column name from array
2289 $pointsColumn = $filterData['column'];
2292 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2293 return $pointsColumn;
2296 // Converts a boolean variable into 'Y' for true and 'N' for false
2297 function convertBooleanToYesNo ($boolean) {
2300 if ($boolean === TRUE) {
2309 // "Translates" 'true' to true and 'false' to false
2310 function convertStringToBoolean ($str) {
2311 // Debug message (to measure how often this function is called)
2312 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2315 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2316 // Trim it lower-case for validation
2317 $strTrimmed = trim(strtolower($str));
2320 if (!in_array($strTrimmed, array('true', 'false'))) {
2322 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2326 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2330 return $GLOBALS[__FUNCTION__][$str];
2334 * "Makes" a variable in given string parseable, this function will throw an
2335 * error if the first character is not a dollar sign.
2337 * @param $varString String which contains a variable
2338 * @return $return String with added single quotes for better parsing
2340 function makeParseableVariable ($varString) {
2341 // The first character must be a dollar sign
2342 if (substr($varString, 0, 1) != '$') {
2343 // Please report this
2344 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2348 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2349 // Snap them in, if [,] are there
2350 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2354 return $GLOBALS[__FUNCTION__][$varString];
2357 // "Getter" for random TAN
2358 function getRandomTan () {
2360 return mt_rand(0, 99999);
2363 // Removes any : from subject
2364 function removeDoubleDotFromSubject ($subject) {
2366 $subjectArray = explode(':', $subject);
2367 $subject = $subjectArray[0];
2368 unset($subjectArray);
2374 // Adds a given entry to the database
2375 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2382 // Set POST data generic userid
2383 setPostRequestElement('userid', getMemberId());
2385 // Call inner function
2386 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2388 // Entry has been added?
2389 if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2390 // Display success message
2391 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2393 // Display failed message
2394 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2398 // Edit rows by given id numbers
2399 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()) {
2400 // $tableName must be an array
2401 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2402 // No tableName specified
2403 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2404 } elseif (!is_array($idColumn)) {
2405 // $idColumn is no array
2406 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2407 } elseif (!is_array($userIdColumn)) {
2408 // $userIdColumn is no array
2409 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2410 } elseif (!is_array($editNow)) {
2411 // $editNow is no array
2412 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2415 // Shall we change here or list for editing?
2416 if ($editNow[0] === TRUE) {
2417 // Add generic userid field
2418 setPostRequestElement('userid', getMemberId());
2420 // Call generic change method
2421 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2424 if ($affected == countPostSelection($idColumn[0])) {
2426 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2428 // Some are still there :(
2429 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2433 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2437 // Delete rows by given id numbers
2438 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()) {
2439 // Do this only for members
2442 // $tableName must be an array
2443 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2444 // No tableName specified
2445 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2446 } elseif (!is_array($idColumn)) {
2447 // $idColumn is no array
2448 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2449 } elseif (!is_array($userIdColumn)) {
2450 // $userIdColumn is no array
2451 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2452 } elseif (!is_array($deleteNow)) {
2453 // $deleteNow is no array
2454 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2457 // Shall we delete here or list for deletion?
2458 if ($deleteNow[0] === TRUE) {
2459 // Add generic userid field
2460 setPostRequestElement('userid', getMemberId());
2462 // Call generic function
2463 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2466 if ($affected == countPostSelection($idColumn[0])) {
2468 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2470 // Some are still there :(
2471 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
2474 // List for deletion confirmation
2475 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2479 // Build a special template list
2480 // @TODO cacheFiles is not yet supported
2481 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2482 // Do this only for logged in member
2485 // Call inner (general) function
2486 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2489 // Checks whether given address is IPv4
2490 function isIp4AddressValid ($address) {
2492 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2494 $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);
2498 return $GLOBALS[__FUNCTION__][$address];
2501 // Returns the string if not empty or FALSE if empty
2502 function validateIsEmpty ($str) {
2504 $trimmed = trim($str);
2506 // Is the string empty?
2507 if (empty($trimmed)) {
2516 // ----------------------------------------------------------------------------
2517 // "Translatation" functions for points_data table
2518 // ----------------------------------------------------------------------------
2520 // Translates generically some data into a target string
2521 function translateGeneric ($messagePrefix, $data) {
2522 // Is the method null or empty?
2523 if (is_null($data)) {
2526 } elseif (empty($data)) {
2527 // Is empty (string)
2531 // Default column name is unknown
2532 $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
2534 // Construct message id
2535 $messageId = $messagePrefix . '_' . strtoupper($data);
2538 if (isMessageIdValid($messageId)) {
2539 // Then use it as message string
2540 $return = '{--' . $messageId . '--}';
2543 // Return the column name
2547 // Translates points subject to human-readable
2548 function translatePointsSubject ($subject) {
2550 $subject = removeDoubleDotFromSubject($subject);
2553 return translateGeneric('POINTS_SUBJECT', $subject);
2556 // "Translates" given points account type
2557 function translatePointsAccountType ($accountType) {
2559 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2562 // "Translates" given points "locked mode"
2563 function translatePointsLockedMode ($lockedMode) {
2565 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2568 // "Translates" given points payment method
2569 function translatePointsPaymentMethod ($paymentMethod) {
2571 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2574 // "Translates" given points account provider
2575 function translatePointsAccountProvider ($accountProvider) {
2577 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2580 // "Translates" given points notify recipient
2581 function translatePointsNotifyRecipient ($notifyRecipient) {
2583 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2586 // "Translates" given mode to a human-readable version
2587 function translatePointsMode ($pointsMode) {
2589 return translateGeneric('POINTS_MODE', $pointsMode);
2592 // "Translates" task type to a human-readable version
2593 function translateTaskType ($taskType) {
2595 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2598 //-----------------------------------------------------------------------------
2599 // Automatically re-created functions, all taken from user comments on www.php.net
2600 //-----------------------------------------------------------------------------
2601 if (!function_exists('html_entity_decode')) {
2602 // Taken from documentation on www.php.net
2603 function html_entity_decode ($string) {
2604 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2605 $trans_tbl = array_flip($trans_tbl);
2606 return strtr($string, $trans_tbl);