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 - 2013 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 ($file, $line, $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($file, $line, '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" Y/N into "de-/active"
198 function translateActivationStatus ($status) {
200 if (!isset($GLOBALS[__FUNCTION__][$status])) {
202 $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')';
204 case 'Y': $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}'; break;
205 case 'N': $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}'; break;
208 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $status));
214 return $GLOBALS[__FUNCTION__][$status];
217 // Translates the american decimal dot into a german comma
218 // OPPOMENT: convertCommaToDot()
219 function translateComma ($dotted, $cut = TRUE, $max = '0') {
220 // First, cast all to double, due to PHP changes
221 $dotted = (double) $dotted;
223 // Default is 3 you can change this in admin area "Settings -> Misc Options"
224 if (!isConfigEntrySet('max_comma')) {
225 setConfigEntry('max_comma', 3);
228 // Use from config is default
229 $maxComma = getConfig('max_comma');
231 // Use from parameter?
237 if (($cut === TRUE) && ($max == '0')) {
238 // Test for commata if in cut-mode
239 $com = explode('.', $dotted);
240 if (count($com) < 2) {
241 // Don't display commatas even if there are none... ;-)
249 $translated = $dotted;
250 switch (getLanguage()) {
251 case 'de': // German language
252 $translated = number_format($dotted, $maxComma, ',', '.');
255 default: // All others
256 $translated = number_format($dotted, $maxComma, '.', ',');
260 // Return translated value
261 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
265 // Translate Uni*-like gender to human-readable
266 function translateGender ($gender) {
268 $ret = '!' . $gender . '!';
270 // Male/female or company?
275 // Use generic function
276 $ret = translateGeneric('GENDER', $gender);
280 // Please report bugs on unknown genders
281 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
285 // Return translated gender
289 // "Translates" the user status
290 function translateUserStatus ($status) {
291 // Default status is unknown if something goes through
292 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
294 // Generate message depending on status
299 // Use generic function for all "normal" cases"
300 $ret = translateGeneric('ACCOUNT_STATUS', $status);
303 case '': // Account deleted
304 case NULL: // Account deleted
305 $ret = '{--ACCOUNT_STATUS_DELETED--}';
308 default: // Please report all unknown status
309 reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status)));
317 // "Translates" 'visible' and 'locked' to a CSS class
318 function translateMenuVisibleLocked ($content, $prefix = '') {
319 // Default is 'menu_unknown'
320 $content['visible_css'] = $prefix . 'menu_unknown';
322 // Translate 'visible' and keep an eye on the prefix
323 switch ($content['visible']) {
324 case 'Y': // Should be visible
325 $content['visible_css'] = $prefix . 'menu_visible';
328 case 'N': // Is invisible
329 $content['visible_css'] = $prefix . 'menu_invisible';
332 default: // Please report this
333 reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
337 // Translate 'locked' and keep an eye on the prefix
338 switch ($content['locked']) {
339 case 'Y': // Should be locked, only admins can call this
340 $content['locked_css'] = $prefix . 'menu_locked';
343 case 'N': // Is unlocked and visible to members/guests/sponsors
344 $content['locked_css'] = $prefix . 'menu_unlocked';
347 default: // Please report this
348 reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
352 // Return the resulting array
356 // Generates an URL for the dereferer
357 function generateDereferrerUrl ($url) {
358 // Don't de-refer our own links!
359 if ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
361 $encodedUrl = encodeString(compileUriCode($url));
364 $hash = generateHash($url . getSiteKey() . getDateKey());
366 // Log plain URL and hash
367 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
370 $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie($hash) . '&salt=' . substr($hash, 0, getSaltLength()) . '%}';
377 // Generates an URL for the frametester
378 function generateFrametesterUrl ($url) {
379 // Prepare frametester URL
380 $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
381 encodeString(compileUriCode($url))
384 // Return the new URL
385 return $frametesterUrl;
388 // Count entries from e.g. a selection box
389 function countSelection ($array) {
391 if (!is_array($array)) {
393 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
400 foreach ($array as $key => $selected) {
402 if (!empty($selected)) {
403 // Yes, then count it
408 // Return counted selections
412 // Generates a timestamp (some wrapper for mktime())
413 function makeTime ($hours, $minutes, $seconds, $stamp) {
414 // Extract day, month and year from given timestamp
415 $days = getDay($stamp);
416 $months = getMonth($stamp);
417 $years = getYear($stamp);
419 // Create timestamp for wished time which depends on extracted date
430 // Redirects to an URL and if neccessarry extends it with own base URL
431 function redirectToUrl ($url, $allowSpider = TRUE) {
432 // Is the output mode -2?
433 if (isAjaxOutputMode()) {
434 // This is always (!) an AJAX request and shall not be redirected
439 if (substr($url, 0, 6) == '{%url=') {
440 $url = substr($url, 6, -2);
444 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
446 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
447 $rel = ' rel="external"';
449 // Is there internal or external URL?
450 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
451 // Own (=internal) URL
455 // Three different ways to debug...
456 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
457 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
458 //* DEBUG: */ die($url);
460 // We should not sent a redirect if headers are already sent
461 if (!headers_sent()) {
462 // Load URL when headers are not sent
463 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE));
465 // Output error message
466 loadInclude('inc/header.php');
467 loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
468 loadInclude('inc/footer.php');
471 // Shut the mailer down here
475 /************************************************************************
477 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
478 * $a_sort sortiert: *
480 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
481 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
482 * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
483 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
484 * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
486 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
487 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
488 * Sie, dass es doch nicht so schwer ist! :-) *
490 ************************************************************************/
491 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
492 $temporaryArray = $array;
493 while ($primary_key < count($a_sort)) {
494 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
495 foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
497 if ($nums === FALSE) {
498 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
499 if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
500 } elseif ($key != $key2) {
501 // Sort numbers (E.g.: 9 < 10)
502 if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
503 if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
507 // We have found two different values, so let's sort whole array
508 foreach ($temporaryArray as $sort_key => $sort_val) {
509 $t = $temporaryArray[$sort_key][$key];
510 $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
511 $temporaryArray[$sort_key][$key2] = $t;
522 // Write back sorted array
523 $array = $temporaryArray;
528 // Deprecated : $length (still has one reference in this function)
529 // Optional : $extraData
531 function generateRandomCode ($length, $code, $userid, $extraData = '') {
532 // Build server string
533 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
536 $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
537 if (isConfigEntrySet('secret_key')) {
538 $keys .= getEncryptSeparator() . getSecretKey();
540 if (isConfigEntrySet('file_hash')) {
541 $keys .= getEncryptSeparator() . getFileHash();
543 $keys .= getEncryptSeparator() . getDateFromRepository();
544 if (isConfigEntrySet('master_salt')) {
545 $keys .= getEncryptSeparator() . getMasterSalt();
548 // Build string from misc data
549 $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
551 // Add more additional data
552 if (isSessionVariableSet('u_hash')) {
553 $data .= getEncryptSeparator() . getSession('u_hash');
556 // Add referral id, language, theme and userid
557 $data .= getEncryptSeparator() . determineReferralId();
558 $data .= getEncryptSeparator() . getLanguage();
559 $data .= getEncryptSeparator() . getCurrentTheme();
560 $data .= getEncryptSeparator() . getMemberId();
562 // Calculate number for generating the code
563 $a = $code + getConfig('_ADD') - 1;
565 if (isConfigEntrySet('master_salt')) {
566 // Generate hash with master salt from modula of number with the prime number and other data
567 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
569 // Generate hash with "hash of site key" from modula of number with the prime number and other data
570 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
573 // Create number from hash
574 $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
576 // At least 10 numbers shall be secure enought!
577 if (isExtensionActive('other')) {
578 $len = getCodeLength();
583 // Smaller 1 is not okay
589 // Cut off requested counts of number, but skip first digit (which is mostly a zero)
590 $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
592 // Done building code
596 // Does only allow numbers
597 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
598 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
599 // Filter all non-number chars out, so only number chars will remain
600 $ret = preg_replace('/[^0123456789]/', '', $num);
603 if ($castValue === TRUE) {
604 // Cast to biggest numeric type
605 $ret = (double) $ret;
608 // Has the whole value changed?
609 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
611 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
615 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
619 // Creates a Uni* timestamp from given selection data and prefix
620 function createEpocheTimeFromSelections ($prefix, $postData) {
621 // Initial return value
624 // Is there a leap year?
626 $TEST = getYear() / 4;
629 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
630 // 01 2 2 1 1 1 123 4 43 3 32 233 4 43 3 3210
631 if ((floor($TEST) == $TEST) && ($M1 == '02') && (((isset($postData[$prefix . '_mo'])) && ($postData[$prefix . '_mo'] > '02')) || ((isset($postData[$prefix . '_mn'])) && ($postData[$prefix . '_mn'] > '02')))) {
632 $SWITCH = getOneDay();
635 // First add years...
636 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
639 if (isset($postData[$prefix . '_mo'])) {
640 $ret += $postData[$prefix . '_mo'] * 2628000;
641 } elseif (isset($postData[$prefix . '_mn'])) {
642 $ret += $postData[$prefix . '_mn'] * 2628000;
646 $ret += $postData[$prefix . '_we'] * 604800;
649 $ret += $postData[$prefix . '_da'] * 86400;
652 $ret += $postData[$prefix . '_ho'] * 3600;
655 $ret += $postData[$prefix . '_mi'] * 60;
657 // And at last seconds...
658 $ret += $postData[$prefix . '_se'];
660 // Return calculated value
664 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
665 function createFancyTime ($stamp) {
666 // Get data array with years/months/weeks/days/...
667 $data = createTimeSelections($stamp, '', '', '', TRUE);
669 foreach ($data as $k => $v) {
671 // Value is greater than 0 "eval" data to return string
672 $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
677 // Is something there?
679 // Remove leading commata and space
680 $ret = substr($ret, 2);
683 $ret = '0 {--TIME_UNIT_SECOND--}';
686 // Return fancy time string
690 // Taken from www.php.net isInStringIgnoreCase() user comments
691 function isEmailValid ($email) {
692 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
695 if (!isset($GLOBALS[__FUNCTION__][$email])) {
696 // Check first part of email address
697 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
700 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
703 $regex = '@^' . $first . '\@' . $domain . '$@iU';
706 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
709 // Return check result
710 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
711 return $GLOBALS[__FUNCTION__][$email];;
714 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
715 function isUrlValid ($url, $compile = TRUE) {
717 $url = trim(urldecode($url));
718 //* DEBUG: */ debugOutput($url);
720 // Compile some chars out...
721 if ($compile === TRUE) {
722 $url = compileUriCode($url, FALSE, FALSE, FALSE);
724 //* DEBUG: */ debugOutput($url);
726 // Check for the extension filter
727 if (isExtensionActive('filter')) {
728 // Use the extension's filter set
729 return FILTER_VALIDATE_URL($url, FALSE);
733 * If not installed, perform a simple test. Just make it sure there is always a
734 * http:// or https:// in front of the URLs.
736 return isUrlValidSimple($url);
739 // Generate a hash for extra-security for all passwords
740 function generateHash ($plainText, $salt = '', $hash = TRUE) {
742 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
744 // Is the required extension 'sql_patches' there and a salt is not given?
745 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
746 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
747 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
748 if ($hash === TRUE) {
750 return md5($plainText);
757 // Is an arry element missing here?
758 if (!isConfigEntrySet('file_hash')) {
760 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
763 // When the salt is empty build a new one, else use the first x configured characters as the salt
765 // Build server string for more entropy
766 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
769 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
772 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
774 // Calculate number for generating the code
775 $a = time() + getConfig('_ADD') - 1;
777 // Generate SHA1 sum from modula of number and the prime number
778 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
779 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
780 $sha1 = scrambleString($sha1);
781 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
782 //* DEBUG: */ $sha1b = descrambleString($sha1);
783 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
785 // Generate the password salt string
786 $salt = substr($sha1, 0, getSaltLength());
787 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
790 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
791 $salt = substr($salt, 0, getSaltLength());
792 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
794 // Sanity check on salt
795 if (strlen($salt) != getSaltLength()) {
797 reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
801 // Generate final hash (for debug output)
802 $finalHash = $salt . sha1($salt . $plainText);
805 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
812 function scrambleString ($str) {
816 // Final check, in case of failure it will return unscrambled string
817 if (strlen($str) > 40) {
818 // The string is to long
820 } elseif (strlen($str) == 40) {
822 $scrambleNums = explode(':', getPassScramble());
824 // Generate new numbers
825 $scrambleNums = explode(':', genScrambleString(strlen($str)));
828 // Compare both lengths and abort if different
829 if (strlen($str) != count($scrambleNums)) {
833 // Scramble string here
834 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
835 for ($idx = 0; $idx < strlen($str); $idx++) {
836 // Get char on scrambled position
837 $char = substr($str, $scrambleNums[$idx], 1);
839 // Add it to final output string
843 // Return scrambled string
844 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
848 // De-scramble a string scrambled by scrambleString()
849 function descrambleString ($str) {
850 // Scramble only 40 chars long strings
851 if (strlen($str) != 40) {
855 // Load numbers from config
856 $scrambleNums = explode(':', getPassScramble());
859 if (count($scrambleNums) != 40) {
863 // Begin descrambling
864 $orig = str_repeat(' ', 40);
865 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
866 for ($idx = 0; $idx < 40; $idx++) {
867 $char = substr($str, $idx, 1);
868 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
871 // Return scrambled string
872 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
876 // Generated a "string" for scrambling
877 function genScrambleString ($len) {
878 // Prepare array for the numbers
879 $scrambleNumbers = array();
881 // First we need to setup randomized numbers from 0 to 31
882 for ($idx = 0; $idx < $len; $idx++) {
884 $rand = mt_rand(0, ($len - 1));
886 // Check for it by creating more numbers
887 while (array_key_exists($rand, $scrambleNumbers)) {
888 $rand = mt_rand(0, ($len - 1));
892 $scrambleNumbers[$rand] = $rand;
895 // So let's create the string for storing it in database
896 $scrambleString = implode(':', $scrambleNumbers);
897 return $scrambleString;
900 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
901 function encodeHashForCookie ($passHash) {
902 // Return vanilla password hash
905 // Is a secret key and master salt already initialized?
906 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
907 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
908 // Only calculate when the secret key is generated
909 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
910 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
911 // Both keys must have same length so return unencrypted
912 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
916 $newHash = ''; $start = 9;
917 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
918 for ($idx = 0; $idx < 20; $idx++) {
919 // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
920 $part1 = hexdec(substr($passHash , $start, 2));
921 $part2 = hexdec(substr(getSecretKey(), $start, 2));
923 // Default is hexadecimal of index if both are same
925 // Is part1 larger or part2 than its counter part?
926 if ($part1 > $part2) {
928 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
929 } elseif ($part2 > $part1) {
931 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
934 $mod = substr($mod, 0, 2);
935 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
936 $mod = padLeftZero($mod);
937 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
942 // Just copy it over, as the master salt is not really helpful here
943 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
948 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
952 // Fix "deleted" cookies
953 function fixDeletedCookies ($cookies) {
954 // Is this an array with entries?
955 if ((is_array($cookies)) && (count($cookies) > 0)) {
956 // Then check all cookies if they are marked as deleted!
957 foreach ($cookies as $cookieName) {
958 // Is the cookie set to "deleted"?
959 if (getSession($cookieName) == 'deleted') {
960 setSession($cookieName, '');
966 // Checks if a given apache module is loaded
967 function isApacheModuleLoaded ($apacheModule) {
968 // Check it and return result
969 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
972 // Get current theme name
973 function getCurrentTheme () {
974 // The default theme is 'default'... ;-)
977 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
978 if (isExtensionActive('theme')) {
980 $ret = getActualTheme();
981 } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) {
982 // Use value from POST data
983 $ret = postRequestElement('theme');
984 } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) {
985 // Use value from GET data
986 $ret = getRequestElement('theme');
987 } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) {
988 // Use value from GET data
989 $ret = getMailerTheme();
992 // Return theme value
996 // Generates an error code from given account status
997 function generateErrorCodeFromUserStatus ($status = '') {
998 // If no status is provided, use the default, cached
999 if ((empty($status)) && (isMember())) {
1001 $status = getUserData('status');
1004 // Default error code if unknown account status
1005 $errorCode = getCode('ACCOUNT_UNKNOWN');
1007 // Generate constant name
1008 $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
1010 // Is the constant there?
1011 if (isCodeSet($codeName)) {
1013 $errorCode = getCode($codeName);
1016 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1019 // Return error code
1023 // Back-ported from the new ship-simu engine. :-)
1024 function debug_get_printable_backtrace () {
1026 $backtrace = '<ol>';
1028 // Get and prepare backtrace for output
1029 $backtraceArray = debug_backtrace();
1030 foreach ($backtraceArray as $key => $trace) {
1031 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1032 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1033 if (!isset($trace['args'])) $trace['args'] = array();
1034 $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>';
1038 $backtrace .= '</ol>';
1040 // Return the backtrace
1044 // A mail-able backtrace
1045 function debug_get_mailable_backtrace () {
1049 // Get and prepare backtrace for output
1050 $backtraceArray = debug_backtrace();
1051 foreach ($backtraceArray as $key => $trace) {
1052 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1053 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1054 if (!isset($trace['args'])) $trace['args'] = array();
1055 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1058 // Return the backtrace
1062 // Generates a ***weak*** seed
1063 function generateSeed () {
1064 return microtime(TRUE) * 100000;
1067 // Converts a message code to a human-readable message
1068 function getMessageFromErrorCode ($code) {
1069 // Default is an unknown error code
1070 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1072 // Which code is provided?
1075 // No error code is bad coding practice
1076 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1079 // All error messages
1080 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1081 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1082 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1083 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1084 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1085 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1086 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1087 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1088 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1089 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1090 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1091 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1092 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1093 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1094 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1095 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1096 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1097 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1098 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1099 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1100 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1101 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1102 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1103 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1104 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1105 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1106 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1107 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1108 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1109 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1110 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1111 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1112 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1114 case getCode('ERROR_MAILID'):
1115 if (isExtensionActive('mailid', TRUE)) {
1116 $message = '{--ERROR_CONFIRMING_MAIL--}';
1118 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1122 case getCode('EXTENSION_PROBLEM'):
1123 if (isGetRequestElementSet('ext')) {
1124 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1126 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1130 case getCode('URL_TIME_LOCK'):
1131 // Load timestamp from last order
1132 $content = getPoolDataFromId(getRequestElement('id'));
1134 // Translate it for templates
1135 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1137 // Calculate hours...
1138 $content['hours'] = round(getUrlTlock() / 60 / 60);
1141 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1144 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1146 // Finally contruct the message
1147 $message = loadTemplate('tlock_message', TRUE, $content);
1151 // Log missing/invalid error codes
1152 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1156 // Return the message
1160 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1161 function isUrlValidSimple ($url) {
1162 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1164 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1166 // Allows http and https
1167 $http = "(http|https)+(:\/\/)";
1169 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1170 // Test double-domains (e.g. .de.vu)
1171 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1173 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1175 $dir = "((/)+([-_\.[:alnum:]])+)*";
1177 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1178 // ... and the string after and including question character
1179 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1180 // Pattern for URLs like http://url/dir/doc.html?var=value
1181 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1182 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1183 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1184 // Pattern for URLs like http://url/dir/?var=value
1185 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1186 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1187 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1188 // Pattern for URLs like http://url/dir/page.ext
1189 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1190 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1191 $pattern['ipdp'] = $http . $ip . $dir . $page;
1192 // Pattern for URLs like http://url/dir
1193 $pattern['d1d'] = $http . $domain1 . $dir;
1194 $pattern['d2d'] = $http . $domain2 . $dir;
1195 $pattern['ipd'] = $http . $ip . $dir;
1196 // Pattern for URLs like http://url/?var=value
1197 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1198 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1199 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1200 // Pattern for URLs like http://url?var=value
1201 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1202 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1203 $pattern['ipg12'] = $http . $ip . $getstring1;
1205 // Test all patterns
1207 foreach ($pattern as $key => $pat) {
1209 if (isDebugRegularExpressionEnabled()) {
1210 // @TODO Are these convertions still required?
1211 $pat = str_replace('.', '\.', $pat);
1212 $pat = str_replace('@', '\@', $pat);
1213 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1216 // Check if expression matches
1217 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1220 if ($reg === TRUE) {
1225 // Return true/false
1226 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1230 // Wtites data to a config.php-style file
1231 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1232 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek = 0) {
1233 // Initialize some variables
1239 // Is the file there and read-/write-able?
1240 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1241 $search = 'CFG: ' . $comment;
1242 $tmp = $FQFN . '.tmp';
1244 // Open the source file
1245 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1247 // Is the resource valid?
1248 if (is_resource($fp)) {
1249 // Open temporary file
1250 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1252 // Is the resource again valid?
1253 if (is_resource($fp_tmp)) {
1254 // Mark temporary file as readable
1255 $GLOBALS['file_readable'][$tmp] = TRUE;
1258 while (!feof($fp)) {
1259 // Read from source file
1260 $line = fgets($fp, 1024);
1262 if (isInString($search, $line)) {
1268 if ($next === $seek) {
1270 $line = $prefix . $inserted . $suffix . PHP_EOL;
1276 // Write to temp file
1277 fwrite($fp_tmp, $line);
1283 // Finished writing tmp file
1287 // Close source file
1290 if (($done === TRUE) && ($found === TRUE)) {
1291 // Copy back temporary->FQFN file and ...
1292 copyFileVerified($tmp, $FQFN, 0644);
1294 // ... delete temporay file :-)
1295 return removeFile($tmp);
1296 } elseif ($found === FALSE) {
1298 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!');
1300 // Temporary file not fully written
1301 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - Temporary file unfinished!');
1305 // File not found, not readable or writeable
1306 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN) . ',comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek);
1309 // An error was detected!
1313 // Debug message logger
1314 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1315 // Is debug mode enabled?
1316 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1318 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1320 // Log this message away
1321 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1325 // Handle extra values
1326 function handleExtraValues ($filterFunction, $value, $extraValue) {
1327 // Default is the value itself
1330 // Is there a special filter function?
1331 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1332 // Call-back function does not exist or is empty
1333 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1336 // Is there extra parameters here?
1337 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1338 // Put both parameters in one new array by default
1339 $args = array($value, $extraValue);
1341 // If we have an array simply use it and pre-extend it with our value
1342 if (is_array($extraValue)) {
1343 // Make the new args array
1344 $args = merge_array(array($value), $extraValue);
1347 // Call the multi-parameter call-back
1348 $ret = call_user_func_array($filterFunction, $args);
1351 if ($ret === TRUE) {
1352 // Test passed, so write direct value
1356 // One parameter call
1357 $ret = call_user_func($filterFunction, $value);
1358 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1361 if ($ret === TRUE) {
1362 // Test passed, so write direct value
1371 // Tries to determine if call-back functions and/or extra values shall be parsed
1372 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1373 // Debug mode enabled?
1374 if (isDebugModeEnabled()) {
1376 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1379 // Send data through the filter function if found
1380 if ($key === $userIdColumn[0]) {
1381 // Is the userid, we have to process it with convertZeroToNull()
1382 $entries = convertZeroToNull($entries);
1383 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1384 // Debug mode enabled?
1385 if (isDebugModeEnabled()) {
1387 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1390 // Filter function + extra value set
1391 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1393 // Debug mode enabled?
1394 if (isDebugModeEnabled()) {
1396 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1398 } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$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, $extraValues[$search]);
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));
1416 } elseif (!empty($filterFunctions[$search])) {
1417 // Debug mode enabled?
1418 if (isDebugModeEnabled()) {
1420 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1423 // Handle extra values
1424 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1426 // Debug mode enabled?
1427 if (isDebugModeEnabled()) {
1429 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1432 // Make sure entries is not bool, then something went wrong
1433 assert(!is_bool($entries));
1440 // Converts timestamp selections into a timestamp
1441 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1442 // Init test variable
1446 // Get last three chars
1447 $test = substr($id, -3);
1449 // Improved way of checking! :-)
1450 if (in_array($test, array('_ye', '_mo', '_mn', '_we', '_da', '_ho', '_mi', '_se'))) {
1451 // Found a multi-selection for timings?
1452 $test = substr($id, 0, -3);
1453 if ((isset($postData[$test . '_ye'])) && ((isset($postData[$test . '_mo'])) || (isset($postData[$test . '_mn']))) && (isset($postData[$test . '_we'])) && (isset($postData[$test . '_da'])) && (isset($postData[$test . '_ho'])) && (isset($postData[$test . '_mi'])) && (isset($postData[$test . '_se'])) && ($test != $test2)) {
1454 // Generate timestamp
1455 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1456 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1457 $GLOBALS['skip_config'][$test] = TRUE;
1459 // Remove data from array
1460 foreach (array('ye', 'mo', 'mn', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1461 unset($postData[$test . '_' . $rem]);
1472 // Reverts the german decimal comma into Computer decimal dot
1473 // OPPOMENT: translateComma()
1474 function convertCommaToDot ($str) {
1475 // Default float is not a float... ;-)
1478 // Which language is selected?
1479 switch (getLanguage()) {
1480 case 'de': // German language
1481 // Remove german thousand dots first
1482 $str = str_replace('.', '', $str);
1484 // Replace german commata with decimal dot and cast it
1485 $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str));
1488 default: // US and so on
1489 // Remove thousand commatas first and cast
1490 $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str));
1498 // Handle menu-depending failed logins and return the rendered content
1499 function handleLoginFailures ($accessLevel) {
1500 // Default output is empty ;-)
1503 // Is the session data set?
1504 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1505 // Ignore zero values
1506 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1507 // Non-guest has login failures found, get both data and prepare it for template
1508 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1510 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1511 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1515 $OUT = loadTemplate('login_failures', TRUE, $content);
1518 // Reset session data
1519 setSession('mailer_' . $accessLevel . '_failures', '');
1520 setSession('mailer_' . $accessLevel . '_last_failure', '');
1523 // Return rendered content
1528 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1530 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1532 // Shall I remove the cache file?
1533 if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1534 // Rebuild cache only in HTML output-mode
1535 // @TODO This should be rewritten not to load the cache file for just checking if it is there for save removal.
1536 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1538 $GLOBALS['cache_instance']->removeCacheFile($force);
1541 // Include file given?
1544 $inc = sprintf("inc/loader/load-%s.php", $inc);
1546 // Is the include there?
1547 if (isIncludeReadable($inc)) {
1548 // And rebuild it from scratch
1549 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1552 // Include not found
1553 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1559 // Determines the real remote address
1560 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1561 // Default is 127.0.0.1
1562 $address = '127.0.0.1';
1564 // Is a proxy in use?
1565 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1567 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1568 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1569 // Yet, another proxy
1570 $address = $_SERVER['HTTP_CLIENT_IP'];
1571 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1572 // The regular address when no proxy was used
1573 $address = $_SERVER['REMOTE_ADDR'];
1576 // This strips out the real address from proxy output
1577 if (strstr($address, ',')) {
1578 $addressArray = explode(',', $address);
1579 $address = $addressArray[0];
1582 // Return the result
1586 // Adds a bonus mail to the queue
1587 // This is a high-level function!
1588 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1589 // Use mode from data if not set and availble ;-)
1590 if ((empty($mode)) && (isset($data['mail_mode']))) {
1591 $mode = $data['mail_mode'];
1594 // Generate receiver list
1595 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1598 if (!empty($receiver)) {
1599 // Add bonus mail to queue
1600 addBonusMailToQueue(
1612 // Mail inserted into bonus pool
1613 if ($output === TRUE) {
1614 displayMessage('{--ADMIN_BONUS_SEND--}');
1616 } elseif ($output === TRUE) {
1617 // More entered than can be reached!
1618 displayMessage('{--ADMIN_MORE_SELECTED--}');
1621 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1625 // Enables the hourly reset mode and runs it
1626 function doHourly () {
1627 // Enable the hourly reset mode
1628 $GLOBALS['hourly_enabled'] = TRUE;
1630 // Run filters (one always!)
1631 runFilterChain('hourly');
1633 // Do not update in hourly debug mode
1634 if ((!isConfigEntrySet('DEBUG_HOURLY')) || (!isDebugHourlyEnabled())) {
1636 updateConfiguration('last_hourly', getHour());
1640 // Enables the daily reset mode and runs it
1641 function doDaily () {
1642 // Enable the reset mode
1643 $GLOBALS['daily_enabled'] = TRUE;
1646 runFilterChain('daily');
1648 // Do not update in daily debug mode
1649 if ((!isConfigEntrySet('DEBUG_DAILY')) || (!isDebugDailyEnabled())) {
1651 updateConfiguration('last_daily', getDay());
1655 // Enables the weekly reset mode and runs it
1656 function doWeekly () {
1657 // Enable the reset mode
1658 $GLOBALS['weekly_enabled'] = TRUE;
1661 runFilterChain('weekly');
1663 // Do not update in weekly debug mode
1664 if ((!isConfigEntrySet('DEBUG_WEEKLY')) || (!isDebugWeeklyEnabled())) {
1666 updateConfiguration('last_weekly', getWeek());
1670 // Enables the monthly reset mode and runs it
1671 function doMonthly () {
1672 // Enable the reset mode
1673 $GLOBALS['monthly_enabled'] = TRUE;
1676 runFilterChain('monthly');
1678 // Do not update in monthly debug mode
1679 if ((!isConfigEntrySet('DEBUG_MONTHLY')) || (!isDebugMonthlyEnabled())) {
1681 updateConfiguration('last_monthly', getMonth());
1685 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1686 function doShutdown () {
1687 // Call the filter chain 'shutdown'
1688 runFilterChain('shutdown', NULL);
1690 // Check if link is up
1691 if (isSqlLinkUp()) {
1693 sqlCloseLink(__FUNCTION__, __LINE__);
1694 } elseif (!isInstallationPhase()) {
1696 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1699 // Stop executing here
1704 function initMemberId () {
1705 $GLOBALS['member_id'] = '0';
1708 // Setter for member id
1709 function setMemberId ($memberId) {
1710 // We should not set member id to zero
1711 if (!isValidId($memberId)) {
1712 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1716 $GLOBALS['member_id'] = bigintval($memberId);
1719 // Getter for member id or returns zero
1720 function getMemberId () {
1721 // Default member id
1724 // Is the member id set?
1725 if (isMemberIdSet()) {
1727 $memberId = $GLOBALS['member_id'];
1734 // Checks ether the member id is set
1735 function isMemberIdSet () {
1736 return (isset($GLOBALS['member_id']));
1739 // Setter for extra title
1740 function setExtraTitle ($extraTitle) {
1741 $GLOBALS['extra_title'] = $extraTitle;
1744 // Getter for extra title
1745 function getExtraTitle () {
1746 // Is the extra title set?
1747 if (!isExtraTitleSet()) {
1748 // No, then abort here
1749 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1753 return $GLOBALS['extra_title'];
1756 // Checks if the extra title is set
1757 function isExtraTitleSet () {
1758 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1762 * Reads a directory recursively by default and searches for files not matching
1763 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1764 * a whole directory.
1766 * @param $baseDir Relative base directory to PATH to scan from
1767 * @param $prefix Prefix for all positive matches (which files should be found)
1768 * @param $fileIncludeDirs whether to include directories in the final output array
1769 * @param $addBaseDir whether to add $baseDir to all array entries
1770 * @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'
1771 * @param $extension File extension for all positive matches
1772 * @param $excludePattern Regular expression to exclude more files (preg_match())
1773 * @param $recursive whether to scan recursively
1774 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1775 * @param $withPrefixSuffix Whether to include prefix/suffix in found entries
1776 * @return $foundMatches All found positive matches for above criteria
1778 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '', $withPrefixSuffix = TRUE) {
1779 // Add default entries we should always exclude
1780 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1782 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1783 // Init found includes
1784 $foundMatches = array();
1787 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1790 while ($baseFile = readdir($dirPointer)) {
1791 // Exclude '.', '..' and entries in $excludeArray automatically
1792 if (in_array($baseFile, $excludeArray, TRUE)) {
1794 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1798 // Construct include filename and FQFN
1799 $fileName = $baseDir . $baseFile;
1800 $FQFN = getPath() . $fileName;
1802 // Remove double slashes
1803 $FQFN = str_replace('//', '/', $FQFN);
1805 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1806 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1808 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1814 // Skip also files with non-matching prefix genericly
1815 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1816 // Is a redirectory so read it as well
1817 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1819 // And skip further processing
1821 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1823 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1825 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1826 // Skip wrong suffix as well
1827 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1829 } elseif (!isFileReadable($FQFN)) {
1830 // Not readable so skip it
1831 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1832 } elseif (filesize($FQFN) < 50) {
1833 // Might be deprecated
1834 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1836 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1837 // This PHP script is deprecated
1838 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1842 // Get file' extension (last 4 chars)
1843 $fileExtension = substr($baseFile, -4, 4);
1845 // Is the file a PHP script or other?
1846 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1847 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1848 // Is this a valid include file?
1849 if ($extension == '.php') {
1850 // Remove both for extension name
1851 $extName = substr($baseFile, strlen($prefix), -4);
1853 // Add file with or without base path
1854 if ($addBaseDir === TRUE) {
1856 array_push($foundMatches, $fileName);
1857 } elseif ($withPrefixSuffix === FALSE) {
1859 array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1862 array_push($foundMatches, $baseFile);
1865 // We found .php file but should not search for them, why?
1866 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1868 } elseif ($fileExtension == $extension) {
1869 // Other, generic file found
1870 array_push($foundMatches, $fileName);
1875 closedir($dirPointer);
1878 sort($foundMatches);
1880 // Return array with include files
1881 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1882 return $foundMatches;
1885 // Checks whether $prefix is found in $fileName
1886 function isFilePrefixFound ($fileName, $prefix) {
1887 // @TODO Find a way to cache this
1888 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1891 // Maps a module name into a database table name
1892 function mapModuleToTable ($moduleName) {
1893 // Map only these, still lame code...
1894 switch ($moduleName) {
1895 case 'index': // 'index' is the guest's menu
1896 $moduleName = 'guest';
1899 case 'login': // ... and 'login' the member's menu
1900 $moduleName = 'member';
1902 // Anything else will not be mapped, silently.
1909 // Add SQL debug data to array for later output
1910 function addSqlToDebug ($result, $sqlString, $timing, $file, $line) {
1912 if (!isset($GLOBALS['debug_sql_available'])) {
1913 // Check it and cache it in $GLOBALS
1914 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1917 // Don't execute anything here if we don't need or ext-other is missing
1918 if ($GLOBALS['debug_sql_available'] === FALSE) {
1922 // Already executed?
1923 if (isset($GLOBALS['debug_sqls'][$file][$line][$sqlString])) {
1924 // Then abort here, we don't need to profile a query twice
1928 // Remeber this as profiled (or not, but we don't care here)
1929 $GLOBALS['debug_sqls'][$file][$line][$sqlString] = TRUE;
1933 'num_rows' => sqlNumRows($result),
1934 'affected' => sqlAffectedRows(),
1935 'sql_str' => $sqlString,
1936 'timing' => $timing,
1937 'file' => basename($file),
1942 array_push($GLOBALS['debug_sqls'], $record);
1945 // Initializes the cache instance
1946 function initCacheInstance () {
1947 // Check for double-initialization
1948 if (isset($GLOBALS['cache_instance'])) {
1949 // This should not happen and must be fixed
1950 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1953 // Load include for CacheSystem class
1954 loadIncludeOnce('inc/classes/cachesystem.class.php');
1956 // Initialize cache system only when it's needed
1957 $GLOBALS['cache_instance'] = new CacheSystem();
1960 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1961 // Failed to initialize cache sustem
1962 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1966 // Getter for message from array or raw message
1967 function getMessageFromIndexedArray ($message, $pos, $array) {
1968 // Check if the requested message was found in array
1969 if (isset($array[$pos])) {
1970 // ... if yes then use it!
1971 $ret = $array[$pos];
1973 // ... else use default message
1981 // Convert ';' to ', ' for e.g. receiver list
1982 function convertReceivers ($old) {
1983 return str_replace(';', ', ', $old);
1986 // Get a module from filename and access level
1987 function getModuleFromFileName ($file, $accessLevel) {
1988 // Default is 'invalid';
1989 $modCheck = 'invalid';
1991 // @TODO This is still very static, rewrite it somehow
1992 switch ($accessLevel) {
1994 $modCheck = 'admin';
2000 $modCheck = getModule();
2003 default: // Unsupported file name / access level
2004 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2012 // Encodes an URL for adding session id, etc.
2013 function encodeUrl ($url, $outputMode = '0') {
2014 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
2015 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
2016 // Raw output mode detected or session_name() found in URL
2020 // Is there a valid session?
2021 if ((!isSessionValid()) && (!isSpider())) {
2022 // Determine right separator
2023 $separator = '&';
2024 if (!isInString('?', $url)) {
2029 // Then add it to URL
2030 $url .= $separator . session_name() . '=' . session_id();
2034 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2036 $url = '{?URL?}/' . $url;
2040 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
2042 // Is there to decode entities?
2043 if (!isHtmlOutputMode()) {
2044 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
2045 // Decode them for e.g. JavaScript parts
2046 $url = decodeEntities($url);
2047 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
2051 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
2053 // Return the encoded URL
2057 // Simple check for spider
2058 function isSpider () {
2059 // Get the UA and trim it down
2060 $userAgent = trim(detectUserAgent(TRUE));
2062 // It should not be empty, if so it is better a browser
2063 if (empty($userAgent)) {
2064 // It is a browser that blocks its UA string
2069 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2072 // Function to search for the last modified file
2073 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2075 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2076 // Does it match what we are looking for? (We skip a lot files already!)
2077 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2078 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2080 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2081 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2083 // Walk through all entries
2084 foreach ($ds as $d) {
2085 // Generate proper FQFN
2086 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2088 // Is it a file and readable?
2089 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2090 if (isFileReadable($FQFN)) {
2091 // $FQFN is a readable file so extract the requested data from it
2092 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2093 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2095 // Is the file more recent?
2096 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2097 // This file is newer as the file before
2098 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2099 $last_changed['path_name'] = $FQFN;
2100 $last_changed[$lookFor] = $check;
2104 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2109 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2110 function handleFieldWithBraces ($field) {
2111 // Are there braces [] at the end?
2112 if (substr($field, -2, 2) == '[]') {
2114 * Try to find one and replace it. I do it this way to allow easy
2115 * extending of this code.
2117 foreach (array('admin_list_builder_id_value') as $key) {
2118 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2119 // Is the cache entry set?
2120 if (isset($GLOBALS[$key])) {
2122 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2125 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2135 // Converts a zero or NULL to word 'NULL'
2136 function convertZeroToNull ($number) {
2137 // Is it a valid username?
2138 if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2140 $number = bigintval($number);
2142 // Is not valid or zero
2150 // Converts a NULL|empty string|< 1 to zero
2151 function convertNullToZero ($number) {
2152 // Is it a valid username?
2153 if ((is_null($number)) || (empty($number)) || ($number < 1)) {
2154 // Is not valid or zero
2162 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2163 // Note: This function is cached
2164 function capitalizeUnderscoreString ($str) {
2166 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2167 // Init target string
2170 // Explode it with the underscore, but rewrite dashes to underscore before
2171 $strArray = explode('_', str_replace('-', '_', $str));
2173 // "Walk" through all elements and make them lower-case but first upper-case
2174 foreach ($strArray as $part) {
2175 // Capitalize the string part
2176 $capitalized .= firstCharUpperCase($part);
2179 // Store the converted string in cache array
2180 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2184 return $GLOBALS[__FUNCTION__][$str];
2187 // Generate admin links for mail order
2188 // mailType can be: 'normal' or 'bonus'
2189 function generateAdminMailLinks ($mailType, $mailId) {
2194 // Default column for mail status is 'data_type'
2195 // @TODO Rename column data_type to e.g. mail_status
2196 $statusColumn = 'data_type';
2198 // Which mail do we have?
2199 switch ($mailType) {
2200 case 'bonus': // Bonus mail
2204 case 'normal': // Member mail
2208 default: // Handle unsupported types
2209 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2210 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2214 // Is the mail type supported?
2215 if (!empty($table)) {
2216 // Query for the mail
2217 $result = sqlQueryEscaped("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2222 ), __FILE__, __LINE__);
2224 // Is there one entry there?
2225 if (sqlNumRows($result) == 1) {
2227 $content = sqlFetchArray($result);
2229 // Add output and type
2230 $content['type'] = $mailType;
2231 $content['__output'] = '';
2234 $content = runFilterChain('generate_admin_mail_links', $content);
2237 $OUT = $content['__output'];
2241 sqlFreeResult($result);
2244 // Return generated HTML code
2250 * Determine if a string can represent a number in hexadecimal
2252 * @param $hex A string to check if it is hex-encoded
2253 * @return $foo True if the string is a hex, otherwise false
2254 * @author Marques Johansson
2255 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2257 function isHexadecimal ($hex) {
2258 // Make it lowercase
2259 $hex = strtolower(trim(ltrim($hex, '0')));
2261 // Fix empty strings to zero
2266 // Simply compare decode->encode result with original
2267 return ($hex == dechex(hexdec($hex)));
2271 * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2272 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2273 * response handler functions.
2275 * @param $str String to overwork
2276 * @return $str Overworked string
2278 function replaceReturnNewLine ($str) {
2279 return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2282 // Converts a given string by splitting it up with given delimiter similar to
2283 // explode(), but appending the delimiter again
2284 function stringToArray ($delimiter, $string) {
2286 $strArray = array();
2288 // "Walk" through all entries
2289 foreach (explode($delimiter, $string) as $split) {
2290 // Append the delimiter and add it to the array
2291 array_push($strArray, $split . $delimiter);
2298 // Detects the prefix 'mb_' if a multi-byte string is given
2299 function detectMultiBytePrefix ($str) {
2300 // Default is without multi-byte
2303 // Detect multi-byte (strictly)
2304 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2305 // With multi-byte encoded string
2309 // Return the prefix
2313 // Searches given array for a sub-string match and returns all found keys in an array
2314 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2315 // Init array for all found keys
2318 // Now check all entries
2319 foreach ($needles as $key => $needle) {
2320 // Is there found a partial string?
2321 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2322 if (strpos($heystack, $needle, $offset) !== FALSE) {
2323 // Add the found key
2324 array_push($keys, $key);
2332 // Determines database column name from given subject and locked
2333 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2334 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2335 // Default is 'normal' points
2336 $pointsColumn = 'points';
2338 // Which points, locked or normal?
2339 if ($locked === TRUE) {
2340 $pointsColumn = 'locked_points';
2343 // Prepare array for filter
2344 $filterData = array(
2345 'subject' => $subject,
2346 'locked' => $locked,
2347 'column' => $pointsColumn
2351 $filterData = runFilterChain('determine_points_column_name', $filterData);
2353 // Extract column name from array
2354 $pointsColumn = $filterData['column'];
2357 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2358 return $pointsColumn;
2361 // Converts a boolean variable into 'Y' for true and 'N' for false
2362 function convertBooleanToYesNo ($boolean) {
2365 if ($boolean === TRUE) {
2374 // "Translates" 'true' to true and 'false' to false
2375 function convertStringToBoolean ($str) {
2376 // Debug message (to measure how often this function is called)
2377 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2380 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2381 // Trim it lower-case for validation
2382 $strTrimmed = trim(strtolower($str));
2385 if (!in_array($strTrimmed, array('true', 'false'))) {
2387 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2391 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2395 return $GLOBALS[__FUNCTION__][$str];
2399 * "Makes" a variable in given string parseable, this function will throw an
2400 * error if the first character is not a dollar sign.
2402 * @param $varString String which contains a variable
2403 * @return $return String with added single quotes for better parsing
2405 function makeParseableVariable ($varString) {
2406 // The first character must be a dollar sign
2407 if (substr($varString, 0, 1) != '$') {
2408 // Please report this
2409 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2413 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2414 // Snap them in, if [,] are there
2415 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2419 return $GLOBALS[__FUNCTION__][$varString];
2422 // "Getter" for random TAN
2423 function getRandomTan () {
2425 return mt_rand(0, 99999);
2428 // Removes any : from subject
2429 function removeDoubleDotFromSubject ($subject) {
2431 $subjectArray = explode(':', $subject);
2432 $subject = $subjectArray[0];
2433 unset($subjectArray);
2439 // Adds a given entry to the database
2440 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2447 // Set POST data generic userid
2448 setPostRequestElement('userid', getMemberId());
2450 // Call inner function
2451 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2453 // Entry has been added?
2454 if ((!ifSqlHasZeroAffectedRows()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2455 // Display success message
2456 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2458 // Display failed message
2459 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2463 // Edit rows by given id numbers
2464 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()) {
2465 // $tableName must be an array
2466 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2467 // No tableName specified
2468 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2469 } elseif (!is_array($idColumn)) {
2470 // $idColumn is no array
2471 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2472 } elseif (!is_array($userIdColumn)) {
2473 // $userIdColumn is no array
2474 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2475 } elseif (!is_array($editNow)) {
2476 // $editNow is no array
2477 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2480 // Shall we change here or list for editing?
2481 if ($editNow[0] === TRUE) {
2482 // Add generic userid field
2483 setPostRequestElement('userid', getMemberId());
2485 // Call generic change method
2486 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2489 if ($affected == countPostSelection($idColumn[0])) {
2491 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2493 // Some are still there :(
2494 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2498 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2502 // Delete rows by given id numbers
2503 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()) {
2504 // Do this only for members
2507 // $tableName must be an array
2508 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2509 // No tableName specified
2510 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2511 } elseif (!is_array($idColumn)) {
2512 // $idColumn is no array
2513 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2514 } elseif (!is_array($userIdColumn)) {
2515 // $userIdColumn is no array
2516 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2517 } elseif (!is_array($deleteNow)) {
2518 // $deleteNow is no array
2519 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2522 // Shall we delete here or list for deletion?
2523 if ($deleteNow[0] === TRUE) {
2524 // Add generic userid field
2525 setPostRequestElement('userid', getMemberId());
2527 // Call generic function
2528 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2531 if ($affected == countPostSelection($idColumn[0])) {
2533 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2535 // Some are still there :(
2536 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), sqlAffectedRows(), countPostSelection($idColumn[0])));
2539 // List for deletion confirmation
2540 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2544 // Build a special template list
2545 // @TODO cacheFiles is not yet supported
2546 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2547 // Do this only for logged in member
2550 // Call inner (general) function
2551 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2554 // Checks whether given address is IPv4
2555 function isIp4AddressValid ($address) {
2557 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2559 $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);
2563 return $GLOBALS[__FUNCTION__][$address];
2566 // Returns the string if not empty or FALSE if empty
2567 function validateIsEmpty ($str) {
2569 $trimmed = trim($str);
2571 // Is the string empty?
2572 if (empty($trimmed)) {
2581 // "Getter" for seconds from given time unit
2582 function getSecondsFromTimeUnit ($timeUnit) {
2583 // Default is not found
2587 switch ($timeUnit) {
2588 case 's': // Seconds = 1
2592 case 'm': // Minutes
2601 $seconds = 60*60*24;
2605 $seconds = 60*60*24*7;
2608 default: // Unsupported
2609 reportBug(__FUNCTION__, __LINE__, 'Unsupported time unit ' . $timeUnit . ' detected.');
2617 // Calulates value for given seconds and time unit
2618 function caluculateTimeUnitValue ($seconds, $timeUnit) {
2620 return ($seconds / getSecondsFromTimeUnit($timeUnit));
2623 // "Getter" for an array from given one but only one index of it
2624 function getArrayFromArrayIndex ($array, $key) {
2625 // Some simple validation
2626 assert(isset($array[0][$key]));
2629 $newArray = array();
2631 // "Walk" through all elements
2632 foreach ($array as $element) {
2633 $newArray[] = $element[$key];
2641 * Compress given data and encodes it into BASE64 to be stored in database with
2644 * @param $data Data to be compressed and encoded
2645 * @return $data Compressed+encoded data
2647 function compress ($data) {
2649 return base64_encode(gzcompress($data));
2653 * Decompress given data previously compressed with compress().
2655 * @param $data Data compressed with compress()
2656 * @reurn $data Uncompressed data
2658 function decompress ($data) {
2660 return gzuncompress(base64_decode($data));
2664 * Converts given charset in given string to UTF-8 if not UTF-8. This function
2665 * is currently limited to iconv().
2667 * @param $str String to convert charset in
2668 * @param $charset Charset to convert from
2669 * @return $str Converted string
2671 function convertCharsetToUtf8 ($str, $charset) {
2672 // Is iconv() available?
2673 if (!function_exists('iconv')) {
2674 // Please make it sure
2675 reportBug(__FUNCTION__, __LINE__, 'PHP function iconv() is currently required to do charset convertion.');
2678 // Is the charset not UTF-8?
2679 if (strtoupper($charset) != 'UTF-8') {
2680 // Convert it to UTF-8
2681 $str = iconv(strtoupper($charset), 'UTF-8//TRANSLIT', $str);
2684 // Return converted string
2688 // ----------------------------------------------------------------------------
2689 // "Translatation" functions for points_data table
2690 // ----------------------------------------------------------------------------
2692 // Translates generically some data into a target string
2693 function translateGeneric ($messagePrefix, $data, $messageSuffix = '') {
2694 // Is the method null or empty?
2695 if (is_null($data)) {
2698 } elseif (empty($data)) {
2699 // Is empty (string)
2703 // Default column name is unknown
2704 $return = '{%message,' . $messagePrefix . '_UNKNOWN' . $messageSuffix . '=' . strtoupper($data) . '%}';
2706 // Construct message id
2707 $messageId = $messagePrefix . '_' . strtoupper($data) . $messageSuffix;
2710 if (isMessageIdValid($messageId)) {
2711 // Then use it as message string
2712 $return = '{--' . $messageId . '--}';
2715 // Return the column name
2719 // Translates points subject to human-readable
2720 function translatePointsSubject ($subject) {
2722 $subject = removeDoubleDotFromSubject($subject);
2725 return translateGeneric('POINTS_SUBJECT', $subject);
2728 // "Translates" given points account type
2729 function translatePointsAccountType ($accountType) {
2731 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2734 // "Translates" given points "locked mode"
2735 function translatePointsLockedMode ($lockedMode) {
2737 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2740 // "Translates" given points payment method
2741 function translatePointsPaymentMethod ($paymentMethod) {
2743 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2746 // "Translates" given points account provider
2747 function translatePointsAccountProvider ($accountProvider) {
2749 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2752 // "Translates" given points notify recipient
2753 function translatePointsNotifyRecipient ($notifyRecipient) {
2755 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2758 // "Translates" given mode to a human-readable version
2759 function translatePointsMode ($pointsMode) {
2761 return translateGeneric('POINTS_MODE', $pointsMode);
2764 // "Translates" task type to a human-readable version
2765 function translateTaskType ($taskType) {
2767 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2770 // "Translates" task status to a human-readable version
2771 function translateTaskStatus ($taskStatus) {
2773 return translateGeneric('ADMIN_TASK_STATUS', $taskStatus);
2777 *-----------------------------------------------------------------------------
2778 * Automatically re-created functions, all taken from user comments on
2780 *-----------------------------------------------------------------------------
2782 if (!function_exists('html_entity_decode')) {
2783 // Taken from documentation on www.php.net
2784 function html_entity_decode ($string) {
2785 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2786 $trans_tbl = array_flip($trans_tbl);
2787 return strtr($string, $trans_tbl);