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 ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
336 $encodedUrl = encodeString(compileUriCode($url));
339 $hash = generateHash($url . getSiteKey() . getDateKey());
341 // Log plain URL and hash
342 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
345 $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie($hash) . '&salt=' . substr($hash, 0, getSaltLength()) . '%}';
352 // Generates an URL for the frametester
353 function generateFrametesterUrl ($url) {
354 // Prepare frametester URL
355 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
356 encodeString(compileUriCode($url))
359 // Return the new URL
360 return $frametesterUrl;
363 // Count entries from e.g. a selection box
364 function countSelection ($array) {
366 if (!is_array($array)) {
368 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
375 foreach ($array as $key => $selected) {
377 if (!empty($selected)) {
378 // Yes, then count it
383 // Return counted selections
387 // Generates a timestamp (some wrapper for mktime())
388 function makeTime ($hours, $minutes, $seconds, $stamp) {
389 // Extract day, month and year from given timestamp
390 $days = getDay($stamp);
391 $months = getMonth($stamp);
392 $years = getYear($stamp);
394 // Create timestamp for wished time which depends on extracted date
405 // Redirects to an URL and if neccessarry extends it with own base URL
406 function redirectToUrl ($url, $allowSpider = TRUE) {
407 // Is the output mode -2?
408 if (isAjaxOutputMode()) {
409 // This is always (!) an AJAX request and shall not be redirected
414 if (substr($url, 0, 6) == '{%url=') {
415 $url = substr($url, 6, -2);
419 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
421 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
422 $rel = ' rel="external"';
424 // Is there internal or external URL?
425 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
426 // Own (=internal) URL
430 // Three different ways to debug...
431 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
432 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
433 //* DEBUG: */ die($url);
435 // We should not sent a redirect if headers are already sent
436 if (!headers_sent()) {
437 // Load URL when headers are not sent
438 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE));
440 // Output error message
441 loadInclude('inc/header.php');
442 loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
443 loadInclude('inc/footer.php');
446 // Shut the mailer down here
450 /************************************************************************
452 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
453 * $a_sort sortiert: *
455 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
456 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
457 * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
458 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
459 * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
461 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
462 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
463 * Sie, dass es doch nicht so schwer ist! :-) *
465 ************************************************************************/
466 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
467 $temporaryArray = $array;
468 while ($primary_key < count($a_sort)) {
469 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
470 foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
472 if ($nums === FALSE) {
473 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
474 if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
475 } elseif ($key != $key2) {
476 // Sort numbers (E.g.: 9 < 10)
477 if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
478 if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
482 // We have found two different values, so let's sort whole array
483 foreach ($temporaryArray as $sort_key => $sort_val) {
484 $t = $temporaryArray[$sort_key][$key];
485 $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
486 $temporaryArray[$sort_key][$key2] = $t;
497 // Write back sorted array
498 $array = $temporaryArray;
503 // Deprecated : $length (still has one reference in this function)
504 // Optional : $extraData
506 function generateRandomCode ($length, $code, $userid, $extraData = '') {
507 // Build server string
508 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
511 $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
512 if (isConfigEntrySet('secret_key')) {
513 $keys .= getEncryptSeparator() . getSecretKey();
515 if (isConfigEntrySet('file_hash')) {
516 $keys .= getEncryptSeparator() . getFileHash();
518 $keys .= getEncryptSeparator() . getDateFromRepository();
519 if (isConfigEntrySet('master_salt')) {
520 $keys .= getEncryptSeparator() . getMasterSalt();
523 // Build string from misc data
524 $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
526 // Add more additional data
527 if (isSessionVariableSet('u_hash')) {
528 $data .= getEncryptSeparator() . getSession('u_hash');
531 // Add referral id, language, theme and userid
532 $data .= getEncryptSeparator() . determineReferralId();
533 $data .= getEncryptSeparator() . getLanguage();
534 $data .= getEncryptSeparator() . getCurrentTheme();
535 $data .= getEncryptSeparator() . getMemberId();
537 // Calculate number for generating the code
538 $a = $code + getConfig('_ADD') - 1;
540 if (isConfigEntrySet('master_salt')) {
541 // Generate hash with master salt 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, getMasterSalt());
544 // Generate hash with "hash of site key" from modula of number with the prime number and other data
545 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
548 // Create number from hash
549 $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
551 // At least 10 numbers shall be secure enought!
552 if (isExtensionActive('other')) {
553 $len = getCodeLength();
558 // Smaller 1 is not okay
564 // Cut off requested counts of number, but skip first digit (which is mostly a zero)
565 $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
567 // Done building code
571 // Does only allow numbers
572 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
573 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
574 // Filter all non-number chars out, so only number chars will remain
575 $ret = preg_replace('/[^0123456789]/', '', $num);
578 if ($castValue === TRUE) {
579 // Cast to biggest numeric type
580 $ret = (double) $ret;
583 // Has the whole value changed?
584 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
586 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
590 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
594 // Creates a Uni* timestamp from given selection data and prefix
595 function createEpocheTimeFromSelections ($prefix, $postData) {
596 // Initial return value
599 // Is there a leap year?
601 $TEST = getYear() / 4;
604 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
605 if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) {
606 $SWITCH = getOneDay();
609 // First add years...
610 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
613 $ret += $postData[$prefix . '_mo'] * 2628000;
616 $ret += $postData[$prefix . '_we'] * 604800;
619 $ret += $postData[$prefix . '_da'] * 86400;
622 $ret += $postData[$prefix . '_ho'] * 3600;
625 $ret += $postData[$prefix . '_mi'] * 60;
627 // And at last seconds...
628 $ret += $postData[$prefix . '_se'];
630 // Return calculated value
634 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
635 function createFancyTime ($stamp) {
636 // Get data array with years/months/weeks/days/...
637 $data = createTimeSelections($stamp, '', '', '', TRUE);
639 foreach ($data as $k => $v) {
641 // Value is greater than 0 "eval" data to return string
642 $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
647 // Is something there?
648 if (strlen($ret) > 0) {
649 // Remove leading commata and space
650 $ret = substr($ret, 2);
653 $ret = '0 {--TIME_UNIT_SECOND--}';
656 // Return fancy time string
660 // Taken from www.php.net isInStringIgnoreCase() user comments
661 function isEmailValid ($email) {
662 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
665 if (!isset($GLOBALS[__FUNCTION__][$email])) {
666 // Check first part of email address
667 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
670 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
673 $regex = '@^' . $first . '\@' . $domain . '$@iU';
676 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
679 // Return check result
680 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
681 return $GLOBALS[__FUNCTION__][$email];;
684 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
685 function isUrlValid ($url, $compile = TRUE) {
687 $url = trim(urldecode($url));
688 //* DEBUG: */ debugOutput($url);
690 // Compile some chars out...
691 if ($compile === TRUE) {
692 $url = compileUriCode($url, FALSE, FALSE, FALSE);
694 //* DEBUG: */ debugOutput($url);
696 // Check for the extension filter
697 if (isExtensionActive('filter')) {
698 // Use the extension's filter set
699 return FILTER_VALIDATE_URL($url, FALSE);
703 * If not installed, perform a simple test. Just make it sure there is always a
704 * http:// or https:// in front of the URLs.
706 return isUrlValidSimple($url);
709 // Generate a hash for extra-security for all passwords
710 function generateHash ($plainText, $salt = '', $hash = TRUE) {
712 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
714 // Is the required extension 'sql_patches' there and a salt is not given?
715 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
716 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
717 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
718 if ($hash === TRUE) {
720 return md5($plainText);
727 // Is an arry element missing here?
728 if (!isConfigEntrySet('file_hash')) {
730 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
733 // When the salt is empty build a new one, else use the first x configured characters as the salt
735 // Build server string for more entropy
736 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
739 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
742 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
744 // Calculate number for generating the code
745 $a = time() + getConfig('_ADD') - 1;
747 // Generate SHA1 sum from modula of number and the prime number
748 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
749 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
750 $sha1 = scrambleString($sha1);
751 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
752 //* DEBUG: */ $sha1b = descrambleString($sha1);
753 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
755 // Generate the password salt string
756 $salt = substr($sha1, 0, getSaltLength());
757 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
760 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
761 $salt = substr($salt, 0, getSaltLength());
762 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
764 // Sanity check on salt
765 if (strlen($salt) != getSaltLength()) {
767 reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
771 // Generate final hash (for debug output)
772 $finalHash = $salt . sha1($salt . $plainText);
775 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
782 function scrambleString ($str) {
786 // Final check, in case of failure it will return unscrambled string
787 if (strlen($str) > 40) {
788 // The string is to long
790 } elseif (strlen($str) == 40) {
792 $scrambleNums = explode(':', getPassScramble());
794 // Generate new numbers
795 $scrambleNums = explode(':', genScrambleString(strlen($str)));
798 // Compare both lengths and abort if different
799 if (strlen($str) != count($scrambleNums)) return $str;
801 // Scramble string here
802 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
803 for ($idx = 0; $idx < strlen($str); $idx++) {
804 // Get char on scrambled position
805 $char = substr($str, $scrambleNums[$idx], 1);
807 // Add it to final output string
811 // Return scrambled string
812 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
816 // De-scramble a string scrambled by scrambleString()
817 function descrambleString ($str) {
818 // Scramble only 40 chars long strings
819 if (strlen($str) != 40) {
823 // Load numbers from config
824 $scrambleNums = explode(':', getPassScramble());
827 if (count($scrambleNums) != 40) {
831 // Begin descrambling
832 $orig = str_repeat(' ', 40);
833 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
834 for ($idx = 0; $idx < 40; $idx++) {
835 $char = substr($str, $idx, 1);
836 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
839 // Return scrambled string
840 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
844 // Generated a "string" for scrambling
845 function genScrambleString ($len) {
846 // Prepare array for the numbers
847 $scrambleNumbers = array();
849 // First we need to setup randomized numbers from 0 to 31
850 for ($idx = 0; $idx < $len; $idx++) {
852 $rand = mt_rand(0, ($len - 1));
854 // Check for it by creating more numbers
855 while (array_key_exists($rand, $scrambleNumbers)) {
856 $rand = mt_rand(0, ($len - 1));
860 $scrambleNumbers[$rand] = $rand;
863 // So let's create the string for storing it in database
864 $scrambleString = implode(':', $scrambleNumbers);
865 return $scrambleString;
868 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
869 function encodeHashForCookie ($passHash) {
870 // Return vanilla password hash
873 // Is a secret key and master salt already initialized?
874 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
875 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
876 // Only calculate when the secret key is generated
877 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
878 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
879 // Both keys must have same length so return unencrypted
880 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
884 $newHash = ''; $start = 9;
885 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
886 for ($idx = 0; $idx < 20; $idx++) {
887 // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
888 $part1 = hexdec(substr($passHash , $start, 2));
889 $part2 = hexdec(substr(getSecretKey(), $start, 2));
891 // Default is hexadecimal of index if both are same
893 // Is part1 larger or part2 than its counter part?
894 if ($part1 > $part2) {
896 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
897 } elseif ($part2 > $part1) {
899 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
902 $mod = substr($mod, 0, 2);
903 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
904 $mod = str_repeat('0', (2 - strlen($mod))) . $mod;
905 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
910 // Just copy it over, as the master salt is not really helpful here
911 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
916 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
920 // Fix "deleted" cookies
921 function fixDeletedCookies ($cookies) {
922 // Is this an array with entries?
923 if ((is_array($cookies)) && (count($cookies) > 0)) {
924 // Then check all cookies if they are marked as deleted!
925 foreach ($cookies as $cookieName) {
926 // Is the cookie set to "deleted"?
927 if (getSession($cookieName) == 'deleted') {
928 setSession($cookieName, '');
934 // Checks if a given apache module is loaded
935 function isApacheModuleLoaded ($apacheModule) {
936 // Check it and return result
937 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
940 // Get current theme name
941 function getCurrentTheme () {
942 // The default theme is 'default'... ;-)
945 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
946 if (isExtensionActive('theme')) {
948 $ret = getActualTheme();
949 } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) {
950 // Use value from POST data
951 $ret = postRequestElement('theme');
952 } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) {
953 // Use value from GET data
954 $ret = getRequestElement('theme');
955 } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) {
956 // Use value from GET data
957 $ret = getMailerTheme();
960 // Return theme value
964 // Generates an error code from given account status
965 function generateErrorCodeFromUserStatus ($status = '') {
966 // If no status is provided, use the default, cached
967 if ((empty($status)) && (isMember())) {
969 $status = getUserData('status');
972 // Default error code if unknown account status
973 $errorCode = getCode('ACCOUNT_UNKNOWN');
975 // Generate constant name
976 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
978 // Is the constant there?
979 if (isCodeSet($codeName)) {
981 $errorCode = getCode($codeName);
984 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
991 // Back-ported from the new ship-simu engine. :-)
992 function debug_get_printable_backtrace () {
996 // Get and prepare backtrace for output
997 $backtraceArray = debug_backtrace();
998 foreach ($backtraceArray as $key => $trace) {
999 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1000 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1001 if (!isset($trace['args'])) $trace['args'] = array();
1002 $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>';
1006 $backtrace .= '</ol>';
1008 // Return the backtrace
1012 // A mail-able backtrace
1013 function debug_get_mailable_backtrace () {
1017 // Get and prepare backtrace for output
1018 $backtraceArray = debug_backtrace();
1019 foreach ($backtraceArray as $key => $trace) {
1020 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1021 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1022 if (!isset($trace['args'])) $trace['args'] = array();
1023 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1026 // Return the backtrace
1030 // Generates a ***weak*** seed
1031 function generateSeed () {
1032 return microtime(TRUE) * 100000;
1035 // Converts a message code to a human-readable message
1036 function getMessageFromErrorCode ($code) {
1037 // Default is an unknown error code
1038 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1040 // Which code is provided?
1043 // No error code is bad coding practice
1044 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1047 // All error messages
1048 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1049 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1050 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1051 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1052 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1053 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1054 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1055 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1056 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1057 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1058 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1059 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1060 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1061 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1062 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1063 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1064 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1065 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1066 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1067 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1068 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1069 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1070 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1071 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1072 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1073 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1074 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1075 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1076 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1077 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1078 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1079 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1080 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1082 case getCode('ERROR_MAILID'):
1083 if (isExtensionActive('mailid', TRUE)) {
1084 $message = '{--ERROR_CONFIRMING_MAIL--}';
1086 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1090 case getCode('EXTENSION_PROBLEM'):
1091 if (isGetRequestElementSet('ext')) {
1092 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1094 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1098 case getCode('URL_TIME_LOCK'):
1099 // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1100 $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1101 array(bigintval(getRequestElement('id'))), __FUNCTION__, __LINE__);
1103 // Load timestamp from last order
1104 $content = SQL_FETCHARRAY($result);
1107 SQL_FREERESULT($result);
1109 // Translate it for templates
1110 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1112 // Calculate hours...
1113 $content['hours'] = round(getUrlTlock() / 60 / 60);
1116 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1119 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1121 // Finally contruct the message
1122 $message = loadTemplate('tlock_message', TRUE, $content);
1126 // Log missing/invalid error codes
1127 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1131 // Return the message
1135 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1136 function isUrlValidSimple ($url) {
1137 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1139 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1141 // Allows http and https
1142 $http = "(http|https)+(:\/\/)";
1144 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1145 // Test double-domains (e.g. .de.vu)
1146 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1148 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1150 $dir = "((/)+([-_\.[:alnum:]])+)*";
1152 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1153 // ... and the string after and including question character
1154 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1155 // Pattern for URLs like http://url/dir/doc.html?var=value
1156 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1157 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1158 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1159 // Pattern for URLs like http://url/dir/?var=value
1160 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1161 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1162 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1163 // Pattern for URLs like http://url/dir/page.ext
1164 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1165 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1166 $pattern['ipdp'] = $http . $ip . $dir . $page;
1167 // Pattern for URLs like http://url/dir
1168 $pattern['d1d'] = $http . $domain1 . $dir;
1169 $pattern['d2d'] = $http . $domain2 . $dir;
1170 $pattern['ipd'] = $http . $ip . $dir;
1171 // Pattern for URLs like http://url/?var=value
1172 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1173 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1174 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1175 // Pattern for URLs like http://url?var=value
1176 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1177 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1178 $pattern['ipg12'] = $http . $ip . $getstring1;
1180 // Test all patterns
1182 foreach ($pattern as $key => $pat) {
1184 if (isDebugRegularExpressionEnabled()) {
1185 // @TODO Are these convertions still required?
1186 $pat = str_replace('.', '\.', $pat);
1187 $pat = str_replace('@', '\@', $pat);
1188 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1191 // Check if expression matches
1192 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1195 if ($reg === TRUE) {
1200 // Return true/false
1201 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1205 // Wtites data to a config.php-style file
1206 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1207 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0) {
1208 // Initialize some variables
1214 // Is the file there and read-/write-able?
1215 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1216 $search = 'CFG: ' . $comment;
1217 $tmp = $FQFN . '.tmp';
1219 // Open the source file
1220 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1222 // Is the resource valid?
1223 if (is_resource($fp)) {
1224 // Open temporary file
1225 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1227 // Is the resource again valid?
1228 if (is_resource($fp_tmp)) {
1229 // Mark temporary file as readable
1230 $GLOBALS['file_readable'][$tmp] = TRUE;
1233 while (!feof($fp)) {
1234 // Read from source file
1235 $line = fgets ($fp, 1024);
1237 if (isInString($search, $line)) {
1243 if ($next === $seek) {
1245 $line = $prefix . $inserted . $suffix . chr(10);
1251 // Write to temp file
1252 fwrite($fp_tmp, $line);
1258 // Finished writing tmp file
1262 // Close source file
1265 if (($done === TRUE) && ($found === TRUE)) {
1266 // Copy back tmp file and delete tmp :-)
1267 copyFileVerified($tmp, $FQFN, 0644);
1268 return removeFile($tmp);
1269 } elseif ($found === FALSE) {
1270 outputHtml('<strong>CHANGE:</strong> 404!');
1272 outputHtml('<strong>TMP:</strong> UNDONE!');
1276 // File not found, not readable or writeable
1277 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN));
1280 // An error was detected!
1284 // Debug message logger
1285 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1286 // Is debug mode enabled?
1287 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1289 $message = str_replace(array(chr(13), chr(10)), array('', ''), $message);
1291 // Log this message away
1292 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1296 // Handle extra values
1297 function handleExtraValues ($filterFunction, $value, $extraValue) {
1298 // Default is the value itself
1301 // Is there a special filter function?
1302 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1303 // Call-back function does not exist or is empty
1304 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1307 // Is there extra parameters here?
1308 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1309 // Put both parameters in one new array by default
1310 $args = array($value, $extraValue);
1312 // If we have an array simply use it and pre-extend it with our value
1313 if (is_array($extraValue)) {
1314 // Make the new args array
1315 $args = merge_array(array($value), $extraValue);
1318 // Call the multi-parameter call-back
1319 $ret = call_user_func_array($filterFunction, $args);
1322 if ($ret === TRUE) {
1323 // Test passed, so write direct value
1327 // One parameter call
1328 $ret = call_user_func($filterFunction, $value);
1329 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1332 if ($ret === TRUE) {
1333 // Test passed, so write direct value
1342 // Tries to determine if call-back functions and/or extra values shall be parsed
1343 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search) {
1345 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1347 // Send data through the filter function if found
1348 if ($key == $userIdColumn[0]) {
1349 // Is the userid, we have to process it with convertZeroToNull()
1350 $entries = convertZeroToNull($entries);
1351 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1352 // Debug mode enabled?
1353 if (isDebugModeEnabled()) {
1355 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1358 // Filter function + extra value set
1359 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1361 // Debug mode enabled?
1362 if (isDebugModeEnabled()) {
1364 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1366 } elseif (!empty($filterFunctions[$search])) {
1367 // Debug mode enabled?
1368 if (isDebugModeEnabled()) {
1370 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1373 // Handle extra values
1374 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1376 // Debug mode enabled?
1377 if (isDebugModeEnabled()) {
1379 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1382 // Make sure entries is not bool, then something went wrong
1383 assert(!is_bool($entries));
1390 // Converts timestamp selections into a timestamp
1391 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1392 // Init test variable
1396 // Get last three chars
1397 $test = substr($id, -3);
1399 // Improved way of checking! :-)
1400 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1401 // Found a multi-selection for timings?
1402 $test = substr($id, 0, -3);
1403 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)) {
1404 // Generate timestamp
1405 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1406 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1407 $GLOBALS['skip_config'][$test] = TRUE;
1409 // Remove data from array
1410 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1411 unset($postData[$test . '_' . $rem]);
1422 // Reverts the german decimal comma into Computer decimal dot
1423 // OPPOMENT: translateComma()
1424 function convertCommaToDot ($str) {
1425 // Default float is not a float... ;-)
1428 // Which language is selected?
1429 switch (getLanguage()) {
1430 case 'de': // German language
1431 // Remove german thousand dots first
1432 $str = str_replace('.', '', $str);
1434 // Replace german commata with decimal dot and cast it
1435 $float = (float) str_replace(',', '.', $str);
1438 default: // US and so on
1439 // Remove thousand commatas first and cast
1440 $float = (float) str_replace(',', '', $str);
1448 // Handle menu-depending failed logins and return the rendered content
1449 function handleLoginFailures ($accessLevel) {
1450 // Default output is empty ;-)
1453 // Is the session data set?
1454 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1455 // Ignore zero values
1456 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1457 // Non-guest has login failures found, get both data and prepare it for template
1458 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1460 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1461 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1465 $OUT = loadTemplate('login_failures', TRUE, $content);
1468 // Reset session data
1469 setSession('mailer_' . $accessLevel . '_failures', '');
1470 setSession('mailer_' . $accessLevel . '_last_failure', '');
1473 // Return rendered content
1478 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1480 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1482 // Shall I remove the cache file?
1483 if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1484 // Rebuild cache only in HTML output-mode
1485 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1487 $GLOBALS['cache_instance']->removeCacheFile($force);
1490 // Include file given?
1493 $inc = sprintf("inc/loader/load-%s.php", $inc);
1495 // Is the include there?
1496 if (isIncludeReadable($inc)) {
1497 // And rebuild it from scratch
1498 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1501 // Include not found
1502 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1508 // Determines the real remote address
1509 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1510 // Default is 127.0.0.1
1511 $address = '127.0.0.1';
1513 // Is a proxy in use?
1514 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1516 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1517 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1518 // Yet, another proxy
1519 $address = $_SERVER['HTTP_CLIENT_IP'];
1520 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1521 // The regular address when no proxy was used
1522 $address = $_SERVER['REMOTE_ADDR'];
1525 // This strips out the real address from proxy output
1526 if (strstr($address, ',')) {
1527 $addressArray = explode(',', $address);
1528 $address = $addressArray[0];
1531 // Return the result
1535 // Adds a bonus mail to the queue
1536 // This is a high-level function!
1537 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1538 // Use mode from data if not set and availble ;-)
1539 if ((empty($mode)) && (isset($data['mail_mode']))) {
1540 $mode = $data['mail_mode'];
1543 // Generate receiver list
1544 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1547 if (!empty($receiver)) {
1548 // Add bonus mail to queue
1549 addBonusMailToQueue(
1561 // Mail inserted into bonus pool
1562 if ($output === TRUE) {
1563 displayMessage('{--ADMIN_BONUS_SEND--}');
1565 } elseif ($output === TRUE) {
1566 // More entered than can be reached!
1567 displayMessage('{--ADMIN_MORE_SELECTED--}');
1570 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1574 // Enables the reset mode and runs it
1575 function doReset () {
1576 // Enable the reset mode
1577 $GLOBALS['reset_enabled'] = TRUE;
1580 runFilterChain('reset');
1583 // Enables the reset mode (hourly, weekly and monthly) and runs it
1584 function doHourly () {
1585 // Enable the hourly reset mode
1586 $GLOBALS['hourly_enabled'] = TRUE;
1588 // Run filters (one always!)
1589 runFilterChain('hourly');
1592 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1593 function doShutdown () {
1594 // Call the filter chain 'shutdown'
1595 runFilterChain('shutdown', NULL);
1597 // Check if not in installation phase and the link is up
1598 if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1600 SQL_CLOSE(__FUNCTION__, __LINE__);
1601 } elseif (!isInstallationPhase()) {
1603 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1606 // Stop executing here
1611 function initMemberId () {
1612 $GLOBALS['member_id'] = '0';
1615 // Setter for member id
1616 function setMemberId ($memberid) {
1617 // We should not set member id to zero
1618 if ($memberid == '0') {
1619 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1623 $GLOBALS['member_id'] = bigintval($memberid);
1626 // Getter for member id or returns zero
1627 function getMemberId () {
1628 // Default member id
1631 // Is the member id set?
1632 if (isMemberIdSet()) {
1634 $memberid = $GLOBALS['member_id'];
1641 // Checks ether the member id is set
1642 function isMemberIdSet () {
1643 return (isset($GLOBALS['member_id']));
1646 // Setter for extra title
1647 function setExtraTitle ($extraTitle) {
1648 $GLOBALS['extra_title'] = $extraTitle;
1651 // Getter for extra title
1652 function getExtraTitle () {
1653 // Is the extra title set?
1654 if (!isExtraTitleSet()) {
1655 // No, then abort here
1656 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1660 return $GLOBALS['extra_title'];
1663 // Checks if the extra title is set
1664 function isExtraTitleSet () {
1665 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1669 * Reads a directory recursively by default and searches for files not matching
1670 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1671 * a whole directory.
1673 * @param $baseDir Relative base directory to PATH to scan from
1674 * @param $prefix Prefix for all positive matches (which files should be found)
1675 * @param $fileIncludeDirs whether to include directories in the final output array
1676 * @param $addBaseDir whether to add $baseDir to all array entries
1677 * @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'
1678 * @param $extension File extension for all positive matches
1679 * @param $excludePattern Regular expression to exclude more files (preg_match())
1680 * @param $recursive whether to scan recursively
1681 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1682 * @return $foundMatches All found positive matches for above criteria
1684 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
1685 // Add default entries we should always exclude
1686 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1688 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1689 // Init found includes
1690 $foundMatches = array();
1693 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1696 while ($baseFile = readdir($dirPointer)) {
1697 // Exclude '.', '..' and entries in $excludeArray automatically
1698 if (in_array($baseFile, $excludeArray, TRUE)) {
1700 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1704 // Construct include filename and FQFN
1705 $fileName = $baseDir . $baseFile;
1706 $FQFN = getPath() . $fileName;
1708 // Remove double slashes
1709 $FQFN = str_replace('//', '/', $FQFN);
1711 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1712 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1714 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1720 // Skip also files with non-matching prefix genericly
1721 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1722 // Is a redirectory so read it as well
1723 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1725 // And skip further processing
1727 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1729 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1731 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1732 // Skip wrong suffix as well
1733 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1735 } elseif (!isFileReadable($FQFN)) {
1736 // Not readable so skip it
1737 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1738 } elseif (filesize($FQFN) < 50) {
1739 // Might be deprecated
1740 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1742 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1743 // This PHP script is deprecated
1744 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1748 // Get file' extension (last 4 chars)
1749 $fileExtension = substr($baseFile, -4, 4);
1751 // Is the file a PHP script or other?
1752 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1753 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1754 // Is this a valid include file?
1755 if ($extension == '.php') {
1756 // Remove both for extension name
1757 $extName = substr($baseFile, strlen($prefix), -4);
1759 // Add file with or without base path
1760 if ($addBaseDir === TRUE) {
1762 array_push($foundMatches, $fileName);
1765 array_push($foundMatches, $baseFile);
1768 // We found .php file but should not search for them, why?
1769 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1771 } elseif ($fileExtension == $extension) {
1772 // Other, generic file found
1773 array_push($foundMatches, $fileName);
1778 closedir($dirPointer);
1781 sort($foundMatches);
1783 // Return array with include files
1784 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1785 return $foundMatches;
1788 // Checks whether $prefix is found in $fileName
1789 function isFilePrefixFound ($fileName, $prefix) {
1790 // @TODO Find a way to cache this
1791 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1794 // Maps a module name into a database table name
1795 function mapModuleToTable ($moduleName) {
1796 // Map only these, still lame code...
1797 switch ($moduleName) {
1798 case 'index': // 'index' is the guest's menu
1799 $moduleName = 'guest';
1802 case 'login': // ... and 'login' the member's menu
1803 $moduleName = 'member';
1806 // Anything else will not be mapped, silently.
1813 // Add SQL debug data to array for later output
1814 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1816 if (!isset($GLOBALS['debug_sql_available'])) {
1817 // Check it and cache it in $GLOBALS
1818 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1821 // Don't execute anything here if we don't need or ext-other is missing
1822 if ($GLOBALS['debug_sql_available'] === FALSE) {
1826 // Already executed?
1827 if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1828 // Then abort here, we don't need to profile a query twice
1832 // Remeber this as profiled (or not, but we don't care here)
1833 $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
1837 'num_rows' => SQL_NUMROWS($result),
1838 'affected' => SQL_AFFECTEDROWS(),
1839 'sql_str' => $sqlString,
1840 'timing' => $timing,
1841 'file' => basename($F),
1846 array_push($GLOBALS['debug_sqls'], $record);
1849 // Initializes the cache instance
1850 function initCacheInstance () {
1851 // Check for double-initialization
1852 if (isset($GLOBALS['cache_instance'])) {
1853 // This should not happen and must be fixed
1854 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1857 // Load include for CacheSystem class
1858 loadIncludeOnce('inc/classes/cachesystem.class.php');
1860 // Initialize cache system only when it's needed
1861 $GLOBALS['cache_instance'] = new CacheSystem();
1864 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1865 // Failed to initialize cache sustem
1866 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1870 // Getter for message from array or raw message
1871 function getMessageFromIndexedArray ($message, $pos, $array) {
1872 // Check if the requested message was found in array
1873 if (isset($array[$pos])) {
1874 // ... if yes then use it!
1875 $ret = $array[$pos];
1877 // ... else use default message
1885 // Convert ';' to ', ' for e.g. receiver list
1886 function convertReceivers ($old) {
1887 return str_replace(';', ', ', $old);
1890 // Get a module from filename and access level
1891 function getModuleFromFileName ($file, $accessLevel) {
1892 // Default is 'invalid';
1893 $modCheck = 'invalid';
1895 // @TODO This is still very static, rewrite it somehow
1896 switch ($accessLevel) {
1898 $modCheck = 'admin';
1904 $modCheck = getModule();
1907 default: // Unsupported file name / access level
1908 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1916 // Encodes an URL for adding session id, etc.
1917 function encodeUrl ($url, $outputMode = '0') {
1918 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
1919 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1920 // Raw output mode detected or session_name() found in URL
1924 // Is there a valid session?
1925 if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === FALSE) || (!isset($_COOKIE[session_name()]))) && (isSpider() === FALSE)) {
1926 // Determine right separator
1927 $separator = '&';
1928 if (!isInString('?', $url)) {
1933 // Is the session id set?
1934 if (session_id() != '') {
1935 // Then add it to URL
1936 $url .= $separator . session_name() . '=' . session_id();
1941 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1943 $url = '{?URL?}/' . $url;
1947 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
1949 // Is there to decode entities?
1950 if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
1951 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
1952 // Decode them for e.g. JavaScript parts
1953 $url = decodeEntities($url);
1954 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
1958 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
1960 // Return the encoded URL
1964 // Simple check for spider
1965 function isSpider () {
1966 // Get the UA and trim it down
1967 $userAgent = trim(detectUserAgent(TRUE));
1969 // It should not be empty, if so it is better a browser
1970 if (empty($userAgent)) {
1971 // It is a browser that blocks its UA string
1976 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
1979 // Function to search for the last modified file
1980 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
1982 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
1983 // Does it match what we are looking for? (We skip a lot files already!)
1984 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
1985 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
1987 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
1988 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
1990 // Walk through all entries
1991 foreach ($ds as $d) {
1992 // Generate proper FQFN
1993 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
1995 // Is it a file and readable?
1996 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
1997 if (isFileReadable($FQFN)) {
1998 // $FQFN is a readable file so extract the requested data from it
1999 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2000 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2002 // Is the file more recent?
2003 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2004 // This file is newer as the file before
2005 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2006 $last_changed['path_name'] = $FQFN;
2007 $last_changed[$lookFor] = $check;
2011 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2016 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2017 function handleFieldWithBraces ($field) {
2018 // Are there braces [] at the end?
2019 if (substr($field, -2, 2) == '[]') {
2021 * Try to find one and replace it. I do it this way to allow easy
2022 * extending of this code.
2024 foreach (array('admin_list_builder_id_value') as $key) {
2025 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2026 // Is the cache entry set?
2027 if (isset($GLOBALS[$key])) {
2029 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2032 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2042 // Converts a zero or NULL to word 'NULL'
2043 function convertZeroToNull ($number) {
2044 // Is it a valid username?
2045 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2047 $number = bigintval($number);
2049 // Is not valid or zero
2057 // Converts a NULL to zero
2058 function convertNullToZero ($number) {
2059 // Is it a valid username?
2060 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2062 $number = bigintval($number);
2064 // Is not valid or zero
2072 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2073 // Note: This function is cached
2074 function capitalizeUnderscoreString ($str) {
2076 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2077 // Init target string
2080 // Explode it with the underscore, but rewrite dashes to underscore before
2081 $strArray = explode('_', str_replace('-', '_', $str));
2083 // "Walk" through all elements and make them lower-case but first upper-case
2084 foreach ($strArray as $part) {
2085 // Capitalize the string part
2086 $capitalized .= firstCharUpperCase($part);
2089 // Store the converted string in cache array
2090 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2094 return $GLOBALS[__FUNCTION__][$str];
2097 // Generate admin links for mail order
2098 // mailType can be: 'mid' or 'bid'
2099 function generateAdminMailLinks ($mailType, $mailId) {
2104 // Default column for mail status is 'data_type'
2105 // @TODO Rename column data_type to e.g. mail_status
2106 $statusColumn = 'data_type';
2108 // Which mail do we have?
2109 switch ($mailType) {
2110 case 'bid': // Bonus mail
2114 case 'mid': // Member mail
2118 default: // Handle unsupported types
2119 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2120 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2124 // Is the mail type supported?
2125 if (!empty($table)) {
2126 // Query for the mail
2127 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2132 ), __FILE__, __LINE__);
2134 // Is there one entry there?
2135 if (SQL_NUMROWS($result) == 1) {
2137 $content = SQL_FETCHARRAY($result);
2139 // Add output and type
2140 $content['type'] = $mailType;
2141 $content['__output'] = '';
2144 $content = runFilterChain('generate_admin_mail_links', $content);
2147 $OUT = $content['__output'];
2151 SQL_FREERESULT($result);
2154 // Return generated HTML code
2160 * Determine if a string can represent a number in hexadecimal
2162 * @param $hex A string to check if it is hex-encoded
2163 * @return $foo True if the string is a hex, otherwise false
2164 * @author Marques Johansson
2165 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2167 function isHexadecimal ($hex) {
2168 // Make it lowercase
2169 $hex = strtolower(trim(ltrim($hex, '0')));
2171 // Fix empty strings to zero
2176 // Simply compare decode->encode result with original
2177 return ($hex == dechex(hexdec($hex)));
2181 * Replace chr(13) with "[r]" and chr(10) with "[n]" and add a final new-line to make
2182 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2183 * response handler functions.
2185 * @param $str String to overwork
2186 * @return $str Overworked string
2188 function replaceReturnNewLine ($str) {
2189 return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2192 // Converts a given string by splitting it up with given delimiter similar to
2193 // explode(), but appending the delimiter again
2194 function stringToArray ($delimiter, $string) {
2196 $strArray = array();
2198 // "Walk" through all entries
2199 foreach (explode($delimiter, $string) as $split) {
2200 // Append the delimiter and add it to the array
2201 array_push($strArray, $split . $delimiter);
2208 // Detects the prefix 'mb_' if a multi-byte string is given
2209 function detectMultiBytePrefix ($str) {
2210 // Default is without multi-byte
2213 // Detect multi-byte (strictly)
2214 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2215 // With multi-byte encoded string
2219 // Return the prefix
2223 // Searches given array for a sub-string match and returns all found keys in an array
2224 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2225 // Init array for all found keys
2228 // Now check all entries
2229 foreach ($needles as $key => $needle) {
2230 // Is there found a partial string?
2231 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2232 if (strpos($heystack, $needle, $offset) !== FALSE) {
2233 // Add the found key
2234 array_push($keys, $key);
2242 // Determines database column name from given subject and locked
2243 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2244 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2245 // Default is 'normal' points
2246 $pointsColumn = 'points';
2248 // Which points, locked or normal?
2249 if ($locked === TRUE) {
2250 $pointsColumn = 'locked_points';
2253 // Prepare array for filter
2254 $filterData = array(
2255 'subject' => $subject,
2256 'locked' => $locked,
2257 'column' => $pointsColumn
2261 $filterData = runFilterChain('determine_points_column_name', $filterData);
2263 // Extract column name from array
2264 $pointsColumn = $filterData['column'];
2267 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2268 return $pointsColumn;
2271 // Converts a boolean variable into 'Y' for true and 'N' for false
2272 function convertBooleanToYesNo ($boolean) {
2275 if ($boolean === TRUE) {
2284 // "Translates" 'true' to true and 'false' to false
2285 function convertStringToBoolean ($str) {
2286 // Debug message (to measure how often this function is called)
2287 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2290 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2291 // Trim it lower-case for validation
2292 $strTrimmed = trim(strtolower($str));
2295 if (!in_array($strTrimmed, array('true', 'false'))) {
2297 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2301 $GLOBALS[__FUNCTION__][$str] = (($strTrimmed == 'true') ? true : false);
2305 return $GLOBALS[__FUNCTION__][$str];
2309 * "Makes" a variable in given string parseable, this function will throw an
2310 * error if the first character is not a dollar sign.
2312 * @param $varString String which contains a variable
2313 * @return $return String with added single quotes for better parsing
2315 function makeParseableVariable ($varString) {
2316 // The first character must be a dollar sign
2317 if (substr($varString, 0, 1) != '$') {
2318 // Please report this
2319 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2323 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2324 // Snap them in, if [,] are there
2325 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2329 return $GLOBALS[__FUNCTION__][$varString];
2332 // "Getter" for random TAN
2333 function getRandomTan () {
2335 return mt_rand(0, 99999);
2338 // Removes any : from subject
2339 function removeDoubleDotFromSubject ($subject) {
2341 $subjectArray = explode(':', $subject);
2342 $subject = $subjectArray[0];
2343 unset($subjectArray);
2349 // Adds a given entry to the database
2350 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2357 // Set POST data generic userid
2358 setPostRequestElement('userid', getMemberId());
2360 // Call inner function
2361 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2363 // Entry has been added?
2364 if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2365 // Display success message
2366 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2368 // Display failed message
2369 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2373 // Edit rows by given id numbers
2374 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()) {
2375 // $tableName must be an array
2376 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2377 // No tableName specified
2378 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2379 } elseif (!is_array($idColumn)) {
2380 // $idColumn is no array
2381 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2382 } elseif (!is_array($userIdColumn)) {
2383 // $userIdColumn is no array
2384 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2385 } elseif (!is_array($editNow)) {
2386 // $editNow is no array
2387 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2390 // Shall we change here or list for editing?
2391 if ($editNow[0] === TRUE) {
2392 // Add generic userid field
2393 setPostRequestElement('userid', getMemberId());
2395 // Call generic change method
2396 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2399 if ($affected == countPostSelection($idColumn[0])) {
2401 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2403 // Some are still there :(
2404 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2408 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
2412 // Delete rows by given id numbers
2413 function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2414 // Do this only for members
2417 // $tableName must be an array
2418 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2419 // No tableName specified
2420 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2421 } elseif (!is_array($idColumn)) {
2422 // $idColumn is no array
2423 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2424 } elseif (!is_array($userIdColumn)) {
2425 // $userIdColumn is no array
2426 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2427 } elseif (!is_array($deleteNow)) {
2428 // $deleteNow is no array
2429 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2432 // Shall we delete here or list for deletion?
2433 if ($deleteNow[0] === TRUE) {
2434 // Add generic userid field
2435 setPostRequestElement('userid', getMemberId());
2437 // Call generic function
2438 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2441 if ($affected == countPostSelection($idColumn[0])) {
2443 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2445 // Some are still there :(
2446 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
2449 // List for deletion confirmation
2450 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
2454 // Build a special template list
2455 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
2456 // Do this only for logged in member
2459 // Call inner (general) function
2460 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId);
2463 // Checks whether given address is IPv4
2464 function isIp4AddressValid ($address) {
2466 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2468 $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);
2472 return $GLOBALS[__FUNCTION__][$address];
2475 // Returns the string if not empty or FALSE if empty
2476 function validateIsEmpty ($str) {
2478 $trimmed = trim($str);
2480 // Is the string empty?
2481 if (empty($trimmed)) {
2490 // ----------------------------------------------------------------------------
2491 // "Translatation" functions for points_data table
2492 // ----------------------------------------------------------------------------
2494 // Translates generically some data into a target string
2495 function translateGeneric ($messagePrefix, $data) {
2496 // Is the method null or empty?
2497 if (is_null($data)) {
2500 } elseif (empty($data)) {
2501 // Is empty (string)
2505 // Default column name is unknown
2506 $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
2508 // Construct message id
2509 $messageId = $messagePrefix . '_' . strtoupper($data);
2512 if (isMessageIdValid($messageId)) {
2513 // Then use it as message string
2514 $return = '{--' . $messageId . '--}';
2517 // Return the column name
2521 // Translates points subject to human-readable
2522 function translatePointsSubject ($subject) {
2524 $subject = removeDoubleDotFromSubject($subject);
2527 return translateGeneric('POINTS_SUBJECT', $subject);
2530 // "Translates" given points account type
2531 function translatePointsAccountType ($accountType) {
2533 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2536 // "Translates" given points "locked mode"
2537 function translatePointsLockedMode ($lockedMode) {
2539 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2542 // "Translates" given points payment method
2543 function translatePointsPaymentMethod ($paymentMethod) {
2545 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2548 // "Translates" given points account provider
2549 function translatePointsAccountProvider ($accountProvider) {
2551 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2554 // "Translates" given points notify recipient
2555 function translatePointsNotifyRecipient ($notifyRecipient) {
2557 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2560 // "Translates" given mode to a human-readable version
2561 function translatePointsMode ($pointsMode) {
2563 return translateGeneric('POINTS_MODE', $pointsMode);
2566 // "Translates" task type to a human-readable version
2567 function translateTaskType ($taskType) {
2569 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2572 //-----------------------------------------------------------------------------
2573 // Automatically re-created functions, all taken from user comments on www.php.net
2574 //-----------------------------------------------------------------------------
2575 if (!function_exists('html_entity_decode')) {
2576 // Taken from documentation on www.php.net
2577 function html_entity_decode ($string) {
2578 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2579 $trans_tbl = array_flip($trans_tbl);
2580 return strtr($string, $trans_tbl);