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 * -------------------------------------------------------------------- *
13 * Copyright (c) 2003 - 2009 by Roland Haeder *
14 * Copyright (c) 2009 - 2013 by Mailer Developer Team *
15 * For more information visit: http://mxchange.org *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the Free Software *
29 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
31 ************************************************************************/
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
38 // Init fatal message array
39 function initFatalMessages () {
40 $GLOBALS['fatal_messages'] = array();
43 // Getter for whole fatal error messages
44 function getFatalArray () {
45 return $GLOBALS['fatal_messages'];
48 // Add a fatal error message to the queue array
49 function addFatalMessage ($file, $line, $message, $extra = '') {
50 if (is_array($extra)) {
51 // Multiple extras for a message with masks
52 $message = call_user_func_array('sprintf', $extra);
53 } elseif (!empty($extra)) {
54 // $message is text with a mask plus extras to insert into the text
55 $message = sprintf($message, $extra);
58 // Add message to $GLOBALS['fatal_messages']
59 array_push($GLOBALS['fatal_messages'], $message);
61 // Log fatal messages away
62 logDebugMessage($file, $line, 'Fatal error message: ' . compileCode($message));
65 // Getter for total fatal message count
66 function getTotalFatalErrors () {
70 // Is there at least the first entry?
71 if (!empty($GLOBALS['fatal_messages'][0])) {
73 $count = count($GLOBALS['fatal_messages']);
74 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - FROM ARRAY');
78 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - EXIT!');
82 // Generate a password in a specified length or use default password length
83 function generatePassword ($length = '0', $exclude = array()) {
84 // Auto-fix invalid length of zero
86 $length = getMinPasswordLength();
89 // Exclude some entries
90 $localAbc = array_diff($GLOBALS['_abc'], $exclude);
92 // $localAbc must have at least 10 entries
93 assert(count($localAbc) >= 10);
95 // Start creating password
97 while (strlen($password) < $length) {
98 $password .= $localAbc[mt_rand(0, count($localAbc) -1)];
102 * When the length of the password is below 40 characters additional
103 * security can be added by scrambling it. Otherwise the hash may
106 if (strlen($password) <= 40) {
107 // Also scramble the password
108 $password = scrambleString($password);
111 // Return the password
115 // Generates a human-readable timestamp from the Uni* stamp
116 function generateDateTime ($time, $mode = '0') {
118 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
120 return $GLOBALS[__FUNCTION__][$time][$mode];
123 // If the stamp is zero it mostly didn't "happen"
124 if (($time == '0') || (is_null($time))) {
126 return '{--NEVER_HAPPENED--}';
129 // Filter out numbers
130 $timeSecured = bigintval($time);
133 switch (getLanguage()) {
134 case 'de': // German date / time format
136 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break;
137 case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break;
138 case '2': $ret = date('d.m.Y|H:i', $timeSecured); break;
139 case '3': $ret = date('d.m.Y', $timeSecured); break;
140 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
141 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
142 case '6': $ret = date('Ymd', $timeSecured); break;
143 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
145 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
150 default: // Default is the US date / time format!
152 case '0': $ret = date('r', $timeSecured); break;
153 case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break;
154 case '2': $ret = date('y-m-d|H:i', $timeSecured); break;
155 case '3': $ret = date('y-m-d', $timeSecured); break;
156 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
157 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
158 case '6': $ret = date('Ymd', $timeSecured); break;
159 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
161 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
167 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
173 // Translates Y/N to yes/no
174 function translateYesNo ($yn) {
176 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
178 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
181 $GLOBALS[__FUNCTION__][$yn] = '{--YES--}';
185 $GLOBALS[__FUNCTION__][$yn] = '{--NO--}';
188 default: // Log unknown value
189 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $yn));
195 return $GLOBALS[__FUNCTION__][$yn];
198 // "Translates" Y/N into "de-/active"
199 function translateActivationStatus ($status) {
201 if (!isset($GLOBALS[__FUNCTION__][$status])) {
203 $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')';
205 case 'Y': // Activated
206 $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}';
209 case 'N': // Deactivated
210 $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}';
213 default: // Log unknown value
214 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $status));
220 return $GLOBALS[__FUNCTION__][$status];
223 // Translates the american decimal dot into a german comma
224 // OPPOMENT: convertCommaToDot()
225 function translateComma ($dotted, $cut = TRUE, $max = '0') {
226 // First, cast all to double, due to PHP changes
227 $dotted = (double) $dotted;
229 // Default is 3 you can change this in admin area "Settings -> Misc Options"
230 if (!isConfigEntrySet('max_comma')) {
231 setConfigEntry('max_comma', 3);
234 // Use from config is default
235 $maxComma = getConfig('max_comma');
237 // Use from parameter?
243 if (($cut === TRUE) && ($max == '0')) {
244 // Test for commata if in cut-mode
245 $com = explode('.', $dotted);
246 if (count($com) < 2) {
247 // Don't display commatas even if there are none... ;-)
255 $translated = $dotted;
256 switch (getLanguage()) {
257 case 'de': // German language
258 $translated = number_format($dotted, $maxComma, ',', '.');
261 default: // All others
262 $translated = number_format($dotted, $maxComma, '.', ',');
266 // Return translated value
267 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
271 // Translate Uni*-like gender to human-readable
272 function translateGender ($gender) {
274 $ret = '!' . $gender . '!';
276 // Male/female or company?
281 // Use generic function
282 $ret = translateGeneric('GENDER', $gender);
286 // Please report bugs on unknown genders
287 reportBug(__FUNCTION__, __LINE__, sprintf('Unknown gender %s detected.', $gender));
291 // Return translated gender
295 // "Translates" the user status
296 function translateUserStatus ($status) {
297 // Default status is unknown if something goes through
298 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
300 // Generate message depending on status
305 // Use generic function for all "normal" cases
306 $ret = translateGeneric('ACCOUNT_STATUS', $status);
309 case '': // Account deleted
310 case NULL: // Account deleted
311 $ret = '{--ACCOUNT_STATUS_DELETED--}';
314 default: // Please report all unknown status
315 reportBug(__FUNCTION__, __LINE__, sprintf('Unknown status %s(%s) detected.', $status, gettype($status)));
323 // "Translates" 'visible' and 'locked' to a CSS class
324 function translateMenuVisibleLocked ($content, $prefix = '') {
325 // Default is 'menu_unknown'
326 $content['visible_css'] = $prefix . 'menu_unknown';
328 // Translate 'visible' and keep an eye on the prefix
329 switch ($content['visible']) {
330 case 'Y': // Should be visible
331 $content['visible_css'] = $prefix . 'menu_visible';
334 case 'N': // Is invisible
335 $content['visible_css'] = $prefix . 'menu_invisible';
338 default: // Please report this
339 reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
343 // Translate 'locked' and keep an eye on the prefix
344 switch ($content['locked']) {
345 case 'Y': // Should be locked, only admins can call this
346 $content['locked_css'] = $prefix . 'menu_locked';
349 case 'N': // Is unlocked and visible to members/guests/sponsors
350 $content['locked_css'] = $prefix . 'menu_unlocked';
353 default: // Please report this
354 reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
358 // Return the resulting array
362 // Generates an URL for the dereferer
363 function generateDereferrerUrl ($url) {
364 // Don't de-refer our own links!
365 if ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
367 $encodedUrl = encodeString(compileUriCode($url));
370 $hash = generateHash($url . getSiteKey() . getDateKey());
372 // Log plain URL and hash
373 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
376 $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie($hash) . '&salt=' . substr($hash, 0, getSaltLength()) . '%}';
383 // Generates an URL for the frametester
384 function generateFrametesterUrl ($url) {
385 // Prepare frametester URL
386 $frametesterUrl = sprintf('{%%url=modules.php?module=frametester&url=%s%%}',
387 encodeString(compileUriCode($url))
390 // Return the new URL
391 return $frametesterUrl;
394 // Count entries from e.g. a selection box
395 function countSelection ($array) {
397 if (!is_array($array)) {
399 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
406 foreach ($array as $key => $selected) {
408 if (!empty($selected)) {
409 // Yes, then count it
414 // Return counted selections
418 // Generates a timestamp (some wrapper for mktime())
419 function makeTime ($hours, $minutes, $seconds, $stamp) {
420 // Extract day, month and year from given timestamp
421 $days = getDay($stamp);
422 $months = getMonth($stamp);
423 $years = getYear($stamp);
425 // Create timestamp for wished time which depends on extracted date
436 // Redirects to an URL and if neccessarry extends it with own base URL
437 function redirectToUrl ($url, $allowSpider = TRUE) {
438 // Is the output mode -2?
439 if (isAjaxOutputMode()) {
440 // This is always (!) an AJAX request and shall not be redirected
445 if (substr($url, 0, 6) == '{%url=') {
446 $url = substr($url, 6, -2);
450 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
452 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
453 $rel = ' rel="external"';
455 // Is there internal or external URL?
456 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
457 // Own (=internal) URL
461 // Three different ways to debug...
462 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
463 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
464 //* DEBUG: */ die($url);
466 // We should not sent a redirect if headers are already sent
467 if (!headers_sent()) {
468 // Load URL when headers are not sent
469 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE));
471 // Output error message
473 loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
477 // Shut the mailer down here
481 /************************************************************************
483 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
484 * $a_sort sortiert: *
486 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
487 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
488 * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
489 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
490 * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
492 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
493 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
494 * Sie, dass es doch nicht so schwer ist! :-) *
496 ************************************************************************/
497 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
498 $temporaryArray = $array;
499 while ($primary_key < count($a_sort)) {
500 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
501 foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
503 if ($nums === FALSE) {
504 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
505 if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
506 } elseif ($key != $key2) {
507 // Sort numbers (E.g.: 9 < 10)
508 if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
509 if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
513 // We have found two different values, so let's sort whole array
514 foreach ($temporaryArray as $sort_key => $sort_val) {
515 $t = $temporaryArray[$sort_key][$key];
516 $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
517 $temporaryArray[$sort_key][$key2] = $t;
528 // Write back sorted array
529 $array = $temporaryArray;
534 // Deprecated : $length (still has one reference in this function)
535 // Optional : $extraData
537 function generateRandomCode ($length, $code, $userid, $extraData = '') {
538 // Build server string
539 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
542 $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
543 if (isConfigEntrySet('secret_key')) {
544 $keys .= getEncryptSeparator() . getSecretKey();
546 if (isConfigEntrySet('file_hash')) {
547 $keys .= getEncryptSeparator() . getFileHash();
550 if (isConfigEntrySet('master_salt')) {
551 $keys .= getEncryptSeparator() . getMasterSalt();
554 // Build string from misc data
555 $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
557 // Add more additional data
558 if (isSessionVariableSet('u_hash')) {
559 $data .= getEncryptSeparator() . getSession('u_hash');
562 // Add referral id, language, theme and userid
563 $data .= getEncryptSeparator() . determineReferralId();
564 $data .= getEncryptSeparator() . getLanguage();
565 $data .= getEncryptSeparator() . getCurrentTheme();
566 $data .= getEncryptSeparator() . getMemberId();
568 // Calculate number for generating the code
569 $a = $code + getConfig('_ADD') - 1;
571 if (isConfigEntrySet('master_salt')) {
572 // Generate hash with master salt from modula of number with the prime number and other data
573 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
575 // Generate hash with "hash of site key" from modula of number with the prime number and other data
576 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
579 // Create number from hash
580 $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
582 // At least 10 numbers shall be secure enought!
583 if (isExtensionActive('other')) {
584 $len = getCodeLength();
589 // Smaller 1 is not okay
595 // Cut off requested counts of number, but skip first digit (which is mostly a zero)
596 $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
598 // Done building code
602 // Does only allow numbers
603 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
604 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
605 // Filter all non-number chars out, so only number chars will remain
606 $ret = preg_replace('/[^0123456789]/', '', $num);
609 if ($castValue === TRUE) {
610 // Cast to biggest numeric type
611 $ret = (double) $ret;
614 // Has the whole value changed?
615 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
617 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
621 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
625 // Creates a Uni* timestamp from given selection data and prefix
626 function createEpocheTimeFromSelections ($prefix, $postData) {
627 // Assert on typical array element (maybe all?)
628 assert(isset($postData[$prefix . '_ye']));
630 // Initial return value
633 // Is there a leap year?
635 $TEST = getYear() / 4;
638 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
639 // 01 2 2 1 1 1 123 4 43 3 32 233 4 43 3 3210
640 if ((floor($TEST) == $TEST) && ($M1 == '02') && (((isset($postData[$prefix . '_mo'])) && ($postData[$prefix . '_mo'] > '02')) || ((isset($postData[$prefix . '_mn'])) && ($postData[$prefix . '_mn'] > '02')))) {
641 $SWITCH = getOneDay();
644 // First add years...
645 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
648 if (isset($postData[$prefix . '_mo'])) {
649 $ret += $postData[$prefix . '_mo'] * 2628000;
650 } elseif (isset($postData[$prefix . '_mn'])) {
651 $ret += $postData[$prefix . '_mn'] * 2628000;
655 $ret += $postData[$prefix . '_we'] * 604800;
658 $ret += $postData[$prefix . '_da'] * 86400;
661 $ret += $postData[$prefix . '_ho'] * 3600;
664 $ret += $postData[$prefix . '_mi'] * 60;
666 // And at last seconds...
667 $ret += $postData[$prefix . '_se'];
669 // Return calculated value
673 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
674 function createFancyTime ($stamp) {
675 // Get data array with years/months/weeks/days/...
676 $data = createTimeSelections($stamp, '', '', '', TRUE);
678 foreach ($data as $k => $v) {
680 // Value is greater than 0 "eval" data to return string
681 $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
686 // Is something there?
688 // Remove leading commata and space
689 $ret = substr($ret, 2);
692 $ret = '0 {--TIME_UNIT_SECOND--}';
695 // Return fancy time string
699 // Taken from www.php.net isInStringIgnoreCase() user comments
700 function isEmailValid ($email) {
701 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
704 if (!isset($GLOBALS[__FUNCTION__][$email])) {
705 // Check first part of email address
706 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
709 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
712 $regex = '@^' . $first . '\@' . $domain . '$@iU';
715 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
718 // Return check result
719 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
720 return $GLOBALS[__FUNCTION__][$email];
723 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
724 function isUrlValid ($url, $compile = TRUE) {
726 $url = trim(urldecode($url));
727 //* DEBUG: */ debugOutput($url);
729 // Compile some chars out...
730 if ($compile === TRUE) {
731 $url = compileUriCode($url, FALSE, FALSE, FALSE);
733 //* DEBUG: */ debugOutput($url);
735 // Check for the extension filter
736 if (isExtensionActive('filter')) {
737 // Use the extension's filter set
738 return FILTER_VALIDATE_URL($url, FALSE);
742 * If not installed, perform a simple test. Just make it sure there is always a
743 * http:// or https:// in front of the URLs.
745 return isUrlValidSimple($url);
748 // Generate a hash for extra-security for all passwords
749 function generateHash ($plainText, $salt = '', $hash = TRUE) {
751 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
753 // Is the required extension 'sql_patches' there and a salt is not given?
754 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
755 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
756 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
757 if ($hash === TRUE) {
759 return md5($plainText);
766 // Is an arry element missing here?
767 if (!isConfigEntrySet('file_hash')) {
769 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
772 // When the salt is empty build a new one, else use the first x configured characters as the salt
774 // Build server string for more entropy
775 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
778 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getMasterSalt();
780 // Is the secret_key config entry set?
781 if (isConfigEntrySet('secret_key')) {
783 $keys .= getEncryptSeparator() . getSecretKey();
787 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
789 // Calculate number for generating the code
790 $a = time() + getConfig('_ADD') - 1;
792 // Generate SHA1 sum from modula of number and the prime number
793 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
794 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
795 $sha1 = scrambleString($sha1);
796 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
797 //* DEBUG: */ $sha1b = descrambleString($sha1);
798 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
800 // Generate the password salt string
801 $salt = substr($sha1, 0, getSaltLength());
802 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
805 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
806 $salt = substr($salt, 0, getSaltLength());
807 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
809 // Sanity check on salt
810 if (strlen($salt) != getSaltLength()) {
812 reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
816 // Generate final hash (for debug output)
817 $finalHash = $salt . sha1($salt . $plainText);
820 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
827 function scrambleString ($str) {
831 // Final check, in case of failure it will return unscrambled string
832 if (strlen($str) > 40) {
833 // The string is to long
835 } elseif (strlen($str) == 40) {
837 $scrambleNums = explode(':', getPassScramble());
839 // Generate new numbers
840 $scrambleNums = explode(':', genScrambleString(strlen($str)));
843 // Assert on both lengths
844 assert(strlen($str) == count($scrambleNums));
846 // Scramble string here
847 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
848 for ($idx = 0; $idx < strlen($str); $idx++) {
849 // Get char on scrambled position
850 $char = substr($str, $scrambleNums[$idx], 1);
852 // Add it to final output string
856 // Return scrambled string
857 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
861 // De-scramble a string scrambled by scrambleString()
862 function descrambleString ($str) {
863 // Scramble only 40 chars long strings
864 if (strlen($str) != 40) {
868 // Load numbers from config
869 $scrambleNums = explode(':', getPassScramble());
872 if (count($scrambleNums) != 40) {
876 // Begin descrambling
877 $orig = str_repeat(' ', 40);
878 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
879 for ($idx = 0; $idx < 40; $idx++) {
880 $char = substr($str, $idx, 1);
881 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
884 // Return scrambled string
885 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
889 // Generated a "string" for scrambling
890 function genScrambleString ($len) {
891 // Prepare array for the numbers
892 $scrambleNumbers = array();
894 // First we need to setup randomized numbers from 0 to 31
895 for ($idx = 0; $idx < $len; $idx++) {
897 $rand = mt_rand(0, ($len - 1));
899 // Check for it by creating more numbers
900 while (array_key_exists($rand, $scrambleNumbers)) {
901 $rand = mt_rand(0, ($len - 1));
905 $scrambleNumbers[$rand] = $rand;
908 // So let's create the string for storing it in database
909 $scrambleString = implode(':', $scrambleNumbers);
912 return $scrambleString;
915 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
916 function encodeHashForCookie ($passHash) {
917 // Return vanilla password hash
920 // Is a secret key and master salt already initialized?
921 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
922 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
923 // Only calculate when the secret key is generated
924 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
925 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
926 // Both keys must have same length so return unencrypted
927 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
931 $newHash = ''; $start = 9;
932 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
933 for ($idx = 0; $idx < 20; $idx++) {
934 // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
935 $part1 = hexdec(substr($passHash , $start, 2));
936 $part2 = hexdec(substr(getSecretKey(), $start, 2));
938 // Default is hexadecimal of index if both are same
941 // Is part1 larger or part2 than its counter part?
942 if ($part1 > $part2) {
944 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
945 } elseif ($part2 > $part1) {
947 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
950 $mod = substr($mod, 0, 2);
951 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
952 $mod = padLeftZero($mod, 2);
953 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
958 // Just copy it over, as the master salt is not really helpful here
959 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
964 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
968 // Fix "deleted" cookies
969 function fixDeletedCookies ($cookies) {
970 // Is this an array with entries?
971 if (isFilledArray($cookies)) {
972 // Then check all cookies if they are marked as deleted!
973 foreach ($cookies as $cookieName) {
974 // Is the cookie set to "deleted"?
975 if (getSession($cookieName) == 'deleted') {
976 setSession($cookieName, '');
982 // Checks if a given apache module is loaded
983 function isApacheModuleLoaded ($apacheModule) {
984 // Check it and return result
985 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
988 // Get current theme name
989 function getCurrentTheme () {
990 // The default theme is 'default'... ;-)
993 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
994 if (isExtensionActive('theme')) {
996 $ret = getActualTheme();
997 } elseif ((isPostRequestElementSet('theme')) && (isThemeReadable(postRequestElement('theme')))) {
998 // Use value from POST data
999 $ret = postRequestElement('theme');
1000 } elseif ((isGetRequestElementSet('theme')) && (isThemeReadable(getRequestElement('theme')))) {
1001 // Use value from GET data
1002 $ret = getRequestElement('theme');
1003 } elseif ((isMailerThemeSet()) && (isThemeReadable(getMailerTheme()))) {
1004 // Use value from GET data
1005 $ret = getMailerTheme();
1008 // Return theme value
1012 // Generates an error code from given account status
1013 function generateErrorCodeFromUserStatus ($status = '') {
1014 // If no status is provided, use the default, cached
1015 if ((empty($status)) && (isMember())) {
1017 $status = getUserData('status');
1020 // Default error code if unknown account status
1021 $errorCode = getCode('ACCOUNT_UNKNOWN');
1023 // Generate constant name
1024 $codeName = sprintf('ACCOUNT_%s', strtoupper($status));
1026 // Is the constant there?
1027 if (isCodeSet($codeName)) {
1029 $errorCode = getCode($codeName);
1032 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown error status %s detected.', $status));
1035 // Return error code
1039 // Back-ported from the new ship-simu engine. :-)
1040 function debug_get_printable_backtrace () {
1042 $backtrace = '<ol>';
1044 // Get and prepare backtrace for output
1045 $backtraceArray = debug_backtrace();
1046 foreach ($backtraceArray as $key => $trace) {
1047 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1048 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1049 if (!isset($trace['args'])) $trace['args'] = array();
1050 $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>';
1054 $backtrace .= '</ol>';
1056 // Return the backtrace
1060 // A mail-able backtrace
1061 function debug_get_mailable_backtrace () {
1065 // Get and prepare backtrace for output
1066 $backtraceArray = debug_backtrace();
1067 foreach ($backtraceArray as $key => $trace) {
1068 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1069 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1070 if (!isset($trace['args'])) $trace['args'] = array();
1071 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1074 // Return the backtrace
1078 // Generates a ***weak*** seed
1079 function generateSeed () {
1080 return microtime(TRUE) * 100000;
1083 // Converts a message code to a human-readable message
1084 function getMessageFromErrorCode ($code) {
1085 // Default is an unknown error code
1086 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1088 // Which code is provided?
1091 // No error code is bad coding practice
1092 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1095 // All error messages
1096 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1097 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1098 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1099 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1100 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1101 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1102 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1103 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1104 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1105 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1106 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1107 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1108 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1109 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1110 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1111 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1112 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1113 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1114 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1115 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1116 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1117 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1118 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1119 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1120 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1121 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1122 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1123 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1124 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1125 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1126 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1127 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1128 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1130 case getCode('ERROR_MAILID'):
1131 if (isExtensionActive('mailid', TRUE)) {
1132 $message = '{--ERROR_CONFIRMING_MAIL--}';
1134 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1138 case getCode('EXTENSION_PROBLEM'):
1139 if (isGetRequestElementSet('ext')) {
1140 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1142 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1146 case getCode('URL_TIME_LOCK'):
1147 // Load timestamp from last order
1148 $content = getPoolDataFromId(getRequestElement('id'));
1150 // Translate it for templates
1151 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1153 // Calculate hours...
1154 $content['hours'] = round(getUrlTlock() / 60 / 60);
1157 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1160 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1162 // Finally contruct the message
1163 $message = loadTemplate('tlock_message', TRUE, $content);
1167 // Log missing/invalid error codes
1168 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1172 // Return the message
1176 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1177 function isUrlValidSimple ($url) {
1178 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1180 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1182 // Allows http and https
1183 $http = "(http|https)+(:\/\/)";
1185 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1186 // Test double-domains (e.g. .de.vu)
1187 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1189 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1191 $dir = "((/)+([-_\.[:alnum:]])+)*";
1193 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1194 // ... and the string after and including question character
1195 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1196 // Pattern for URLs like http://url/dir/doc.html?var=value
1197 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1198 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1199 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1200 // Pattern for URLs like http://url/dir/?var=value
1201 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1202 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1203 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1204 // Pattern for URLs like http://url/dir/page.ext
1205 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1206 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1207 $pattern['ipdp'] = $http . $ip . $dir . $page;
1208 // Pattern for URLs like http://url/dir
1209 $pattern['d1d'] = $http . $domain1 . $dir;
1210 $pattern['d2d'] = $http . $domain2 . $dir;
1211 $pattern['ipd'] = $http . $ip . $dir;
1212 // Pattern for URLs like http://url/?var=value
1213 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1214 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1215 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1216 // Pattern for URLs like http://url?var=value
1217 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1218 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1219 $pattern['ipg12'] = $http . $ip . $getstring1;
1221 // Test all patterns
1223 foreach ($pattern as $key => $pat) {
1225 if (isDebugRegularExpressionEnabled()) {
1226 // @TODO Are these convertions still required?
1227 $pat = str_replace('.', '\.', $pat);
1228 $pat = str_replace('@', '\@', $pat);
1229 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1232 // Check if expression matches
1233 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1236 if ($reg === TRUE) {
1241 // Return true/false
1242 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1246 // Wtites data to a config.php-style file
1247 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1248 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek = 0) {
1249 // Initialize some variables
1255 // Is the file there and read-/write-able?
1256 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1257 $search = 'CFG: ' . $comment;
1258 $tmp = $FQFN . '.tmp';
1260 // Open the source file
1261 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1263 // Is the resource valid?
1264 if (is_resource($fp)) {
1265 // Open temporary file
1266 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1268 // Is the resource again valid?
1269 if (is_resource($fp_tmp)) {
1270 // Mark temporary file as readable
1271 $GLOBALS['file_readable'][$tmp] = TRUE;
1274 while (!feof($fp)) {
1275 // Read from source file
1276 $line = fgets($fp, 1024);
1278 if (isInString($search, $line)) {
1284 if ($next === $seek) {
1286 $line = $prefix . $inserted . $suffix . PHP_EOL;
1292 // Write to temp file
1293 fwrite($fp_tmp, $line);
1299 // Finished writing tmp file
1303 // Close source file
1306 if (($done === TRUE) && ($found === TRUE)) {
1307 // Copy back temporary->FQFN file and ...
1308 copyFileVerified($tmp, $FQFN, 0644);
1310 // ... delete temporay file :-)
1311 return removeFile($tmp);
1312 } elseif ($found === FALSE) {
1314 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!');
1316 // Temporary file not fully written
1317 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - Temporary file unfinished!');
1321 // File not found, not readable or writeable
1322 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN) . ',comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek);
1325 // An error was detected!
1329 // Debug message logger
1330 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1331 // Is debug mode enabled?
1332 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1334 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1336 // Log this message away
1337 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1341 // Handle extra values
1342 function handleExtraValues ($filterFunction, $value, $extraValue) {
1343 // Default is the value itself
1346 // Is there a special filter function?
1347 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1348 // Call-back function does not exist or is empty
1349 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1352 // Is there extra parameters here?
1353 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1354 // Put both parameters in one new array by default
1355 $args = array($value, $extraValue);
1357 // If we have an array simply use it and pre-extend it with our value
1358 if (is_array($extraValue)) {
1359 // Make the new args array
1360 $args = merge_array(array($value), $extraValue);
1363 // Call the multi-parameter call-back
1364 $ret = call_user_func_array($filterFunction, $args);
1367 if ($ret === TRUE) {
1368 // Test passed, so write direct value
1372 // One parameter call
1373 $ret = call_user_func($filterFunction, $value);
1374 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1377 if ($ret === TRUE) {
1378 // Test passed, so write direct value
1387 // Tries to determine if call-back functions and/or extra values shall be parsed
1388 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1389 // Debug mode enabled?
1390 if (isDebugModeEnabled()) {
1392 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1395 // Send data through the filter function if found
1396 if ($key === $userIdColumn[0]) {
1397 // Is the userid, we have to process it with convertZeroToNull()
1398 $entries = convertZeroToNull($entries);
1399 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1400 // Debug mode enabled?
1401 if (isDebugModeEnabled()) {
1403 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1406 // Filter function + extra value set
1407 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1409 // Debug mode enabled?
1410 if (isDebugModeEnabled()) {
1412 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1414 } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1415 // Debug mode enabled?
1416 if (isDebugModeEnabled()) {
1418 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1421 // Handle extra values
1422 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1424 // Debug mode enabled?
1425 if (isDebugModeEnabled()) {
1427 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1430 // Make sure entries is not bool, then something went wrong
1431 assert(!is_bool($entries));
1432 } elseif (!empty($filterFunctions[$search])) {
1433 // Debug mode enabled?
1434 if (isDebugModeEnabled()) {
1436 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1439 // Handle extra values
1440 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1442 // Debug mode enabled?
1443 if (isDebugModeEnabled()) {
1445 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1448 // Make sure entries is not bool, then something went wrong
1449 assert(!is_bool($entries));
1456 // Converts timestamp selections into a timestamp
1457 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1458 // Init test variable
1462 // Get last three chars
1463 $test = substr($id, -3);
1465 // Improved way of checking! :-)
1466 if (in_array($test, array('_ye', '_mo', '_mn', '_we', '_da', '_ho', '_mi', '_se'))) {
1467 // Found a multi-selection for timings?
1468 $test = substr($id, 0, -3);
1469 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)) {
1470 // Generate timestamp
1471 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1472 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1473 $GLOBALS['skip_config'][$test] = TRUE;
1475 // Remove data from array
1476 foreach (array('ye', 'mo', 'mn', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1477 unset($postData[$test . '_' . $rem]);
1488 // Reverts the german decimal comma into Computer decimal dot
1489 // OPPOMENT: translateComma()
1490 function convertCommaToDot ($str) {
1491 // Default float is not a float... ;-)
1494 // Which language is selected?
1495 switch (getLanguage()) {
1496 case 'de': // German language
1497 // Remove german thousand dots first
1498 $str = str_replace('.', '', $str);
1500 // Replace german commata with decimal dot and cast it
1501 $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str));
1504 default: // US and so on
1505 // Remove thousand commatas first and cast
1506 $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str));
1514 // Handle menu-depending failed logins and return the rendered content
1515 function handleLoginFailures ($accessLevel) {
1516 // Default output is empty ;-)
1519 // Is the session data set?
1520 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1521 // Ignore zero values
1522 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1523 // Non-guest has login failures found, get both data and prepare it for template
1524 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1526 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1527 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1531 $OUT = loadTemplate('login_failures', TRUE, $content);
1534 // Reset session data
1535 setSession('mailer_' . $accessLevel . '_failures', '');
1536 setSession('mailer_' . $accessLevel . '_last_failure', '');
1539 // Return rendered content
1544 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1546 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1548 // Shall I remove the cache file?
1549 if ((isExtensionInstalled('cache')) && (isValidCacheInstance()) && (isHtmlOutputMode())) {
1550 // Rebuild cache only in HTML output-mode
1551 // @TODO This should be rewritten not to load the cache file for just checking if it is there for save removal.
1552 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1554 $GLOBALS['cache_instance']->removeCacheFile($force);
1557 // Include file given?
1560 $inc = sprintf('inc/loader/load-%s.php', $inc);
1562 // Is the include there?
1563 if (isIncludeReadable($inc)) {
1564 // And rebuild it from scratch
1565 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1568 // Include not found, which needs now tracing
1569 reportBug(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1575 // Determines the real remote address
1576 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1577 // Default is 127.0.0.1
1578 $address = '127.0.0.1';
1580 // Is a proxy in use?
1581 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1583 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1584 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1585 // Yet, another proxy
1586 $address = $_SERVER['HTTP_CLIENT_IP'];
1587 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1588 // The regular address when no proxy was used
1589 $address = $_SERVER['REMOTE_ADDR'];
1592 // This strips out the real address from proxy output
1593 if (strstr($address, ',')) {
1594 $addressArray = explode(',', $address);
1595 $address = $addressArray[0];
1598 // Return the result
1602 // Adds a bonus mail to the queue
1603 // This is a high-level function!
1604 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1605 // Use mode from data if not set and availble ;-)
1606 if ((empty($mode)) && (isset($data['mail_mode']))) {
1607 $mode = $data['mail_mode'];
1610 // Generate receiver list
1611 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1614 if (!empty($receiver)) {
1615 // Add bonus mail to queue
1616 addBonusMailToQueue(
1628 // Mail inserted into bonus pool
1629 if ($output === TRUE) {
1630 displayMessage('{--ADMIN_BONUS_SEND--}');
1632 } elseif ($output === TRUE) {
1633 // More entered than can be reached!
1634 displayMessage('{--ADMIN_MORE_SELECTED--}');
1637 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1641 // Enables the hourly reset mode and runs it
1642 function doHourly () {
1643 // Enable the hourly reset mode
1644 $GLOBALS['hourly_enabled'] = TRUE;
1646 // Run filters (one always!)
1647 runFilterChain('hourly');
1649 // Do not update in hourly debug mode
1650 if ((!isConfigEntrySet('DEBUG_HOURLY')) || (!isDebugHourlyEnabled())) {
1652 updateConfiguration('last_hourly', getHour());
1656 // Enables the daily reset mode and runs it
1657 function doDaily () {
1658 // Enable the reset mode
1659 $GLOBALS['daily_enabled'] = TRUE;
1662 runFilterChain('daily');
1664 // Do not update in daily debug mode
1665 if ((!isConfigEntrySet('DEBUG_DAILY')) || (!isDebugDailyEnabled())) {
1667 updateConfiguration('last_daily', getDay());
1671 // Enables the weekly reset mode and runs it
1672 function doWeekly () {
1673 // Enable the reset mode
1674 $GLOBALS['weekly_enabled'] = TRUE;
1677 runFilterChain('weekly');
1679 // Do not update in weekly debug mode
1680 if ((!isConfigEntrySet('DEBUG_WEEKLY')) || (!isDebugWeeklyEnabled())) {
1682 updateConfiguration('last_weekly', getWeek());
1686 // Enables the monthly reset mode and runs it
1687 function doMonthly () {
1688 // Enable the reset mode
1689 $GLOBALS['monthly_enabled'] = TRUE;
1692 runFilterChain('monthly');
1694 // Do not update in monthly debug mode
1695 if ((!isConfigEntrySet('DEBUG_MONTHLY')) || (!isDebugMonthlyEnabled())) {
1697 updateConfiguration('last_monthly', getMonth());
1701 // Enables the yearly reset mode and runs it
1702 function doYearly () {
1703 // Enable the reset mode
1704 $GLOBALS['yearly_enabled'] = TRUE;
1707 runFilterChain('yearly');
1709 // Do not update in yearly debug mode
1710 if ((!isConfigEntrySet('DEBUG_YEARLY')) || (!isDebugYearlyEnabled())) {
1712 updateConfiguration('last_yearly', getYear());
1716 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1717 function doShutdown () {
1718 // Call the filter chain 'shutdown'
1719 runFilterChain('shutdown', NULL);
1721 // Check if link is up
1722 if (isSqlLinkUp()) {
1724 sqlCloseLink(__FUNCTION__, __LINE__);
1725 } elseif (!isInstaller()) {
1727 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1730 // Stop executing here
1735 function initMemberId () {
1736 $GLOBALS['member_id'] = '0';
1739 // Setter for member id
1740 function setMemberId ($memberId) {
1741 // We should not set member id to zero
1742 if (!isValidId($memberId)) {
1743 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1747 $GLOBALS['member_id'] = bigintval($memberId);
1750 // Getter for member id or returns zero
1751 function getMemberId () {
1752 // Default member id
1755 // Is the member id set?
1756 if (isMemberIdSet()) {
1758 $memberId = $GLOBALS['member_id'];
1765 // Checks ether the member id is set
1766 function isMemberIdSet () {
1767 return (isset($GLOBALS['member_id']));
1770 // Setter for extra title
1771 function setExtraTitle ($extraTitle) {
1772 $GLOBALS['extra_title'] = $extraTitle;
1775 // Getter for extra title
1776 function getExtraTitle () {
1777 // Is the extra title set?
1778 if (!isExtraTitleSet()) {
1779 // No, then abort here
1780 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1784 return $GLOBALS['extra_title'];
1787 // Checks if the extra title is set
1788 function isExtraTitleSet () {
1789 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1793 * Reads a directory recursively by default and searches for files not matching
1794 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1795 * a whole directory.
1797 * @param $baseDir Relative base directory to PATH to scan from
1798 * @param $prefix Prefix for all positive matches (which files should be found)
1799 * @param $fileIncludeDirs Whether to include directories in the final output array
1800 * @param $addBaseDir Whether to add $baseDir to all array entries
1801 * @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'
1802 * @param $extension File extension for all positive matches
1803 * @param $excludePattern Regular expression to exclude more files (preg_match())
1804 * @param $recursive Whether to scan recursively
1805 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1806 * @param $withPrefixSuffix Whether to include prefix/suffix in found entries
1807 * @return $foundMatches All found positive matches for above criteria
1809 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '', $withPrefixSuffix = TRUE) {
1810 // Add default entries we should always exclude
1811 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1813 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1814 // Init found includes
1815 $foundMatches = array();
1818 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1821 while ($baseFile = readdir($dirPointer)) {
1822 // Exclude '.', '..' and entries in $excludeArray automatically
1823 if (in_array($baseFile, $excludeArray, TRUE)) {
1825 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1829 // Construct include filename and FQFN
1830 $fileName = $baseDir . $baseFile;
1831 $FQFN = getPath() . $fileName;
1833 // Remove double slashes
1834 $FQFN = str_replace('//', '/', $FQFN);
1836 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1837 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1839 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1845 // Skip also files with non-matching prefix genericly
1846 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1847 // Is a redirectory so read it as well
1848 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1850 // And skip further processing
1852 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1854 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1856 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1857 // Skip wrong suffix as well
1858 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1860 } elseif (!isFileReadable($FQFN)) {
1861 // Not readable so skip it
1862 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1863 } elseif (filesize($FQFN) < 50) {
1864 // Might be deprecated
1865 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1867 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1868 // This PHP script is deprecated
1869 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1873 // Get file' extension (last 4 chars)
1874 $fileExtension = substr($baseFile, -4, 4);
1876 // Is the file a PHP script or other?
1877 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1878 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1879 // Is this a valid include file?
1880 if ($extension == '.php') {
1881 // Remove both for extension name
1882 $extName = substr($baseFile, strlen($prefix), -4);
1884 // Add file with or without base path
1885 if ($addBaseDir === TRUE) {
1887 array_push($foundMatches, $fileName);
1888 } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1890 array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1893 array_push($foundMatches, $baseFile);
1896 // We found .php file but should not search for them, why?
1897 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1899 } elseif ((($fileExtension == $extension) || (empty($extension))) && (isFileReadable($FQFN))) {
1900 // Other, generic file found
1901 if ($addBaseDir === TRUE) {
1903 array_push($foundMatches, $fileName);
1904 } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1906 array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1909 array_push($foundMatches, $baseFile);
1915 closedir($dirPointer);
1918 sort($foundMatches);
1920 // Return array with include files
1921 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1922 return $foundMatches;
1925 // Checks whether $prefix is found in $fileName
1926 function isFilePrefixFound ($fileName, $prefix) {
1927 // @TODO Find a way to cache this
1928 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1931 // Maps a module name into a database table name
1932 function mapModuleToTable ($moduleName) {
1933 // Map only these, still lame code...
1934 switch ($moduleName) {
1935 case 'index': // 'index' is the guest's menu
1936 $moduleName = 'guest';
1939 case 'login': // ... and 'login' the member's menu
1940 $moduleName = 'member';
1942 // Anything else will not be mapped, silently.
1949 // Add SQL debug data to array for later output
1950 function addSqlToDebug ($result, $sqlString, $timing, $file, $line) {
1952 if (!isset($GLOBALS['debug_sql_available'])) {
1953 // Check it and cache it in $GLOBALS
1954 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1957 // Don't execute anything here if we don't need or ext-other is missing
1958 if ($GLOBALS['debug_sql_available'] === FALSE) {
1962 // Already executed?
1963 if (isset($GLOBALS['debug_sqls'][$file][$line][$sqlString])) {
1964 // Then abort here, we don't need to profile a query twice
1968 // Remeber this as profiled (or not, but we don't care here)
1969 $GLOBALS['debug_sqls'][$file][$line][$sqlString] = TRUE;
1973 'num_rows' => sqlNumRows($result),
1974 'affected' => sqlAffectedRows(),
1975 'sql_str' => $sqlString,
1976 'timing' => $timing,
1977 'file' => basename($file),
1982 array_push($GLOBALS['debug_sqls'], $record);
1985 // Initializes the cache instance
1986 function initCacheInstance () {
1987 // Check for double-initialization
1988 if (isset($GLOBALS['cache_instance'])) {
1989 // This should not happen and must be fixed
1990 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1993 // Load include for CacheSystem class
1994 loadIncludeOnce('inc/classes/cachesystem.class.php');
1996 // Initialize cache system only when it's needed
1997 $GLOBALS['cache_instance'] = new CacheSystem();
2000 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
2001 // Failed to initialize cache sustem
2002 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
2006 // Getter for message from array or raw message
2007 function getMessageFromIndexedArray ($message, $pos, $array) {
2008 // Check if the requested message was found in array
2009 if (isset($array[$pos])) {
2010 // ... if yes then use it!
2011 $ret = $array[$pos];
2013 // ... else use default message
2021 // Convert ';' to ', ' for e.g. receiver list
2022 function convertReceivers ($old) {
2023 return str_replace(';', ', ', $old);
2026 // Get a module from filename and access level
2027 function getModuleFromFileName ($file, $accessLevel) {
2028 // Default is 'invalid';
2029 $modCheck = 'invalid';
2031 // @TODO This is still very static, rewrite it somehow
2032 switch ($accessLevel) {
2034 $modCheck = 'admin';
2040 $modCheck = getModule();
2043 default: // Unsupported file name / access level
2044 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2052 // Encodes an URL for adding session id, etc.
2053 function encodeUrl ($url, $outputMode = '0') {
2054 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
2055 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
2056 // Raw output mode detected or session_name() found in URL
2060 // Is there a valid session?
2061 if ((!isValidSession()) && (!isSpider())) {
2062 // Determine right separator
2063 $separator = '&';
2064 if (!isInString('?', $url)) {
2069 // Then add it to URL
2070 $url .= $separator . session_name() . '=' . session_id();
2074 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2076 $url = '{?URL?}/' . $url;
2080 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
2082 // Is there to decode entities?
2083 if (!isHtmlOutputMode()) {
2084 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
2085 // Decode them for e.g. JavaScript parts
2086 $url = decodeEntities($url);
2087 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
2091 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
2093 // Return the encoded URL
2097 // Simple check for spider
2098 function isSpider () {
2099 // Get the UA and trim it down
2100 $userAgent = trim(detectUserAgent(TRUE));
2102 // It should not be empty, if so it is better a browser
2103 if (empty($userAgent)) {
2104 // It is a browser that blocks its UA string
2109 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2112 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2113 function handleFieldWithBraces ($field) {
2114 // Are there braces [] at the end?
2115 if (substr($field, -2, 2) == '[]') {
2117 * Try to find one and replace it. I do it this way to allow easy
2118 * extending of this code.
2120 foreach (array('admin_list_builder_id_value') as $key) {
2121 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2122 // Is the cache entry set?
2123 if (isset($GLOBALS[$key])) {
2125 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2128 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2138 // Converts a zero or NULL to word 'NULL'
2139 function convertZeroToNull ($number) {
2140 // Is it a valid username?
2141 if (isValidNumber($number)) {
2143 $number = bigintval($number);
2145 // Is not valid or zero
2153 // Converts an empty string to NULL, else leaves it untouched
2154 function convertEmptyToNull ($str) {
2155 // Is the string empty?
2156 if (strlen($str) == 0) {
2165 // Converts a NULL|empty string|< 1 to zero
2166 function convertNullToZero ($number) {
2167 // Is it a valid username?
2168 if (!isValidNumber($number)) {
2169 // Is not valid or zero
2177 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2178 // Note: This function is cached
2179 function capitalizeUnderscoreString ($str) {
2181 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2182 // Init target string
2185 // Explode it with the underscore, but rewrite dashes to underscore before
2186 $strArray = explode('_', str_replace('-', '_', $str));
2188 // "Walk" through all elements and make them lower-case but first upper-case
2189 foreach ($strArray as $part) {
2190 // Capitalize the string part
2191 $capitalized .= firstCharUpperCase($part);
2194 // Store the converted string in cache array
2195 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2199 return $GLOBALS[__FUNCTION__][$str];
2202 // Generate admin links for mail order
2203 // mailType can be: 'normal' or 'bonus'
2204 function generateAdminMailLinks ($mailType, $mailId) {
2209 // Default column for mail status is 'data_type'
2210 // @TODO Rename column data_type to e.g. mail_status
2211 $statusColumn = 'data_type';
2213 // Which mail do we have?
2214 switch ($mailType) {
2215 case 'bonus': // Bonus mail
2219 case 'normal': // Member mail
2223 default: // Handle unsupported types
2224 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2225 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2229 // Is the mail type supported?
2230 if (!empty($table)) {
2231 // Query for the mail
2232 $result = sqlQueryEscaped("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2237 ), __FILE__, __LINE__);
2239 // Is there one entry there?
2240 if (sqlNumRows($result) == 1) {
2242 $content = sqlFetchArray($result);
2244 // Add output and type
2245 $content['type'] = $mailType;
2246 $content['__output'] = '';
2249 $content = runFilterChain('generate_admin_mail_links', $content);
2252 $OUT = $content['__output'];
2256 sqlFreeResult($result);
2259 // Return generated HTML code
2265 * Determine if a string can represent a number in hexadecimal
2267 * @param $hex A string to check if it is hex-encoded
2268 * @return $foo True if the string is a hex, otherwise false
2269 * @author Marques Johansson
2270 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2272 function isHexadecimal ($hex) {
2273 // Make it lowercase
2274 $hex = strtolower(trim(ltrim($hex, '0')));
2276 // Fix empty strings to zero
2281 // Simply compare decode->encode result with original
2282 return ($hex == dechex(hexdec($hex)));
2286 * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2287 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2288 * response handler functions.
2290 * @param $str String to overwork
2291 * @return $str Overworked string
2293 function replaceReturnNewLine ($str) {
2294 return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2297 // Converts a given string by splitting it up with given delimiter similar to
2298 // explode(), but appending the delimiter again
2299 function stringToArray ($delimiter, $string) {
2301 $strArray = array();
2303 // "Walk" through all entries
2304 foreach (explode($delimiter, $string) as $split) {
2305 // Append the delimiter and add it to the array
2306 array_push($strArray, $split . $delimiter);
2313 // Detects the prefix 'mb_' if a multi-byte string is given
2314 function detectMultiBytePrefix ($str) {
2315 // Default is without multi-byte
2318 // Detect multi-byte (strictly)
2319 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2320 // With multi-byte encoded string
2324 // Return the prefix
2328 // Searches given array for a sub-string match and returns all found keys in an array
2329 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2330 // Init array for all found keys
2333 // Now check all entries
2334 foreach ($needles as $key => $needle) {
2335 // Is there found a partial string?
2336 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2337 if (strpos($heystack, $needle, $offset) !== FALSE) {
2338 // Add the found key
2339 array_push($keys, $key);
2347 // Determines database column name from given subject and locked
2348 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2349 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2350 // Default is 'normal' points
2351 $pointsColumn = 'points';
2353 // Which points, locked or normal?
2354 if ($locked === TRUE) {
2355 $pointsColumn = 'locked_points';
2358 // Prepare array for filter
2359 $filterData = array(
2360 'subject' => $subject,
2361 'locked' => $locked,
2362 'column' => $pointsColumn
2366 $filterData = runFilterChain('determine_points_column_name', $filterData);
2368 // Extract column name from array
2369 $pointsColumn = $filterData['column'];
2372 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2373 return $pointsColumn;
2376 // Converts a boolean variable into 'Y' for true and 'N' for false
2377 function convertBooleanToYesNo ($boolean) {
2380 if ($boolean === TRUE) {
2389 // "Translates" 'true' to true and 'false' to false
2390 function convertStringToBoolean ($str) {
2391 // Debug message (to measure how often this function is called)
2392 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2395 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2396 // Trim it lower-case for validation
2397 $strTrimmed = trim(strtolower($str));
2400 if (!in_array($strTrimmed, array('true', 'false'))) {
2402 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2406 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2410 return $GLOBALS[__FUNCTION__][$str];
2414 * "Makes" a variable in given string parseable, this function will throw an
2415 * error if the first character is not a dollar sign.
2417 * @param $varString String which contains a variable
2418 * @return $return String with added single quotes for better parsing
2420 function makeParseableVariable ($varString) {
2421 // The first character must be a dollar sign
2422 if (substr($varString, 0, 1) != '$') {
2423 // Please report this
2424 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2428 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2429 // Snap them in, if [,] are there
2430 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2434 return $GLOBALS[__FUNCTION__][$varString];
2437 // "Getter" for random TAN
2438 function getRandomTan () {
2440 return mt_rand(0, 99999);
2443 // Removes any : from subject
2444 function removeDoubleDotFromSubject ($subject) {
2446 $subjectArray = explode(':', $subject);
2447 $subject = $subjectArray[0];
2448 unset($subjectArray);
2454 // Adds a given entry to the database
2455 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2462 // Set POST data generic userid
2463 setPostRequestElement('userid', getMemberId());
2465 // Call inner function
2466 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2468 // Entry has been added?
2469 if ((!ifSqlHasZeroAffectedRows()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2470 // Display success message
2471 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2473 // Display failed message
2474 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2478 // Edit rows by given id numbers
2479 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()) {
2480 // $tableName must be an array
2481 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2482 // No tableName specified
2483 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2484 } elseif (!is_array($idColumn)) {
2485 // $idColumn is no array
2486 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2487 } elseif (!is_array($userIdColumn)) {
2488 // $userIdColumn is no array
2489 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2490 } elseif (!is_array($editNow)) {
2491 // $editNow is no array
2492 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2495 // Shall we change here or list for editing?
2496 if ($editNow[0] === TRUE) {
2497 // Add generic userid field
2498 setPostRequestElement('userid', getMemberId());
2500 // Call generic change method
2501 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2504 if ($affected == countPostSelection($idColumn[0])) {
2506 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2508 // Some are still there :(
2509 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2513 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2517 // Delete rows by given id numbers
2518 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()) {
2519 // Do this only for members
2522 // $tableName must be an array
2523 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2524 // No tableName specified
2525 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2526 } elseif (!is_array($idColumn)) {
2527 // $idColumn is no array
2528 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2529 } elseif (!is_array($userIdColumn)) {
2530 // $userIdColumn is no array
2531 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2532 } elseif (!is_array($deleteNow)) {
2533 // $deleteNow is no array
2534 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2537 // Shall we delete here or list for deletion?
2538 if ($deleteNow[0] === TRUE) {
2539 // Add generic userid field
2540 setPostRequestElement('userid', getMemberId());
2542 // Call generic function
2543 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2546 if ($affected == countPostSelection($idColumn[0])) {
2548 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2550 // Some are still there :(
2551 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), sqlAffectedRows(), countPostSelection($idColumn[0])));
2554 // List for deletion confirmation
2555 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2559 // Build a special template list
2560 // @TODO cacheFiles is not yet supported
2561 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2562 // Do this only for logged in member
2565 // Call inner (general) function
2566 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2569 // Checks whether given address is IPv4
2570 function isIp4AddressValid ($address) {
2572 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2574 $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);
2578 return $GLOBALS[__FUNCTION__][$address];
2581 // Returns the string if not empty or FALSE if empty
2582 function validateIsEmpty ($str) {
2584 $trimmed = trim($str);
2586 // Is the string empty?
2587 if (empty($trimmed)) {
2596 // "Getter" for seconds from given time unit
2597 function getSecondsFromTimeUnit ($timeUnit) {
2598 // Default is not found
2602 switch ($timeUnit) {
2603 case 's': // Seconds = 1
2607 case 'm': // Minutes
2616 $seconds = 60*60*24;
2620 $seconds = 60*60*24*7;
2623 default: // Unsupported
2624 reportBug(__FUNCTION__, __LINE__, 'Unsupported time unit ' . $timeUnit . ' detected.');
2632 // Calulates value for given seconds and time unit
2633 function caluculateTimeUnitValue ($seconds, $timeUnit) {
2635 return ($seconds / getSecondsFromTimeUnit($timeUnit));
2638 // "Getter" for an array from given one but only one index of it
2639 function getArrayFromArrayIndex ($array, $key) {
2640 // Some simple validation
2641 assert(isset($array[0][$key]));
2644 $newArray = array();
2646 // "Walk" through all elements
2647 foreach ($array as $element) {
2648 $newArray[] = $element[$key];
2656 * Compress given data and encodes it into BASE64 to be stored in database with
2659 * @param $data Data to be compressed and encoded
2660 * @return $data Compressed+encoded data
2662 function compress ($data) {
2664 return base64_encode(gzcompress($data));
2668 * Decompress given data previously compressed with compress().
2670 * @param $data Data compressed with compress()
2671 * @reurn $data Uncompressed data
2673 function decompress ($data) {
2675 return gzuncompress(base64_decode($data));
2679 * Converts given charset in given string to UTF-8 if not UTF-8. This function
2680 * is currently limited to iconv().
2682 * @param $str String to convert charset in
2683 * @param $charset Charset to convert from
2684 * @return $str Converted string
2686 function convertCharsetToUtf8 ($str, $charset) {
2687 // Is iconv() available?
2688 if (!function_exists('iconv')) {
2689 // Please make it sure
2690 reportBug(__FUNCTION__, __LINE__, 'PHP function iconv() is currently required to do charset convertion.');
2693 // Is the charset not UTF-8?
2694 if (strtoupper($charset) != 'UTF-8') {
2695 // Convert it to UTF-8
2696 $str = iconv(strtoupper($charset), 'UTF-8//TRANSLIT', $str);
2699 // Return converted string
2703 // Hash string with SHA256 and encode it to hex
2704 function hashSha256 ($str) {
2706 $hash = mhash(MHASH_SHA256, $str);
2708 // Encode it to hexadecimal
2710 for ($i = 0; $i < strlen($hash); $i++) {
2711 // Encode char to decimal, pad it with zero, add it
2712 $hex .= padLeftZero(dechex(ord(substr($hash, $i, 1))), 2);
2715 // Make sure 'length modulo 2' = 0
2716 assert((strlen($hex) % 2) == 0);
2722 // ----------------------------------------------------------------------------
2723 // "Translatation" functions for points_data table
2724 // ----------------------------------------------------------------------------
2726 // Translates generically some data into a target string
2727 function translateGeneric ($messagePrefix, $data, $messageSuffix = '') {
2728 // Is the method null or empty?
2729 if (is_null($data)) {
2732 } elseif (empty($data)) {
2733 // Is empty (string)
2737 // Default column name is unknown
2738 $return = '{%message,' . $messagePrefix . '_UNKNOWN' . $messageSuffix . '=' . strtoupper($data) . '%}';
2740 // Construct message id
2741 $messageId = $messagePrefix . '_' . strtoupper($data) . $messageSuffix;
2744 if (isMessageIdValid($messageId)) {
2745 // Then use it as message string
2746 $return = '{--' . $messageId . '--}';
2749 // Return the column name
2753 // Translates points subject to human-readable
2754 function translatePointsSubject ($subject) {
2756 $subject = removeDoubleDotFromSubject($subject);
2759 return translateGeneric('POINTS_SUBJECT', $subject);
2762 // "Translates" given points account type
2763 function translatePointsAccountType ($accountType) {
2765 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2768 // "Translates" given points "locked mode"
2769 function translatePointsLockedMode ($lockedMode) {
2771 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2774 // "Translates" given points payment method
2775 function translatePointsPaymentMethod ($paymentMethod) {
2777 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2780 // "Translates" given points account provider
2781 function translatePointsAccountProvider ($accountProvider) {
2783 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2786 // "Translates" given points notify recipient
2787 function translatePointsNotifyRecipient ($notifyRecipient) {
2789 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2792 // "Translates" given mode to a human-readable version
2793 function translatePointsMode ($pointsMode) {
2795 return translateGeneric('POINTS_MODE', $pointsMode);
2798 // "Translates" task type to a human-readable version
2799 function translateTaskType ($taskType) {
2801 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2804 // "Translates" task status to a human-readable version
2805 function translateTaskStatus ($taskStatus) {
2807 return translateGeneric('ADMIN_TASK_STATUS', $taskStatus);
2811 *-----------------------------------------------------------------------------
2812 * Automatically re-created functions, all taken from user comments on
2814 *-----------------------------------------------------------------------------
2816 if (!function_exists('html_entity_decode')) {
2817 // Taken from documentation on www.php.net
2818 function html_entity_decode ($string) {
2819 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2820 $trans_tbl = array_flip($trans_tbl);
2821 return strtr($string, $trans_tbl);
2825 // "Calculates" password strength
2826 function calculatePasswordStrength ($password, $configEntry = 'min_password_length') {
2830 if ((strlen($password) < 1) || (strlen($password) < getConfig($configEntry))) {
2835 // At least 8 chars long?
2836 if (strlen($password) >= 8) {
2841 // At least 10 chars long?
2842 if (strlen($password) >= 10) {
2847 // Lower and upper cases?
2848 if ((preg_match('/[a-z]/', $password)) && (preg_match('/[A-Z]/', $password))) {
2854 if (preg_match('/[0-9]/', $password)) {
2859 // Special characters?
2860 if (preg_match('/.[!,@,#,$,%,^,&,*,?,\/,_,~,+,-,(,)]/', $password)) {
2865 // Return password score
2869 // "Translates" password strength/score
2870 function translatePasswordStrength ($strength) {
2871 // Return it translated
2872 return '{--PASSWORD_SCORE_' . bigintval($strength) . '--}';
2875 // Checks whether given password is strong enough
2876 function isStrongPassword ($password) {
2878 return (calculatePasswordStrength($password) >= getConfig('min_password_score'));
2881 // "Getter" for base path from theme
2882 function getBasePathFromTheme ($theme) {
2883 return sprintf('%stheme/%s/css/', getPath(), $theme);
2886 // Wrapper to check whether given theme is readable
2887 function isThemeReadable ($theme) {
2889 if (!isset($GLOBALS[__FUNCTION__][$theme])) {
2891 $GLOBALS[__FUNCTION__][$theme] = (isIncludeReadable(sprintf('theme/%s/theme.php', $theme)));
2895 return $GLOBALS[__FUNCTION__][$theme];
2898 // Checks whether a given PHP extension is loaded or can be loaded at runtime
2900 // Supported OS: Windows, Linux, (Mac?)
2901 function isPhpExtensionLoaded ($extension) {
2902 // Is the extension loaded?
2903 if (extension_loaded($extension)) {
2908 // Try to load the extension
2909 return loadLibrary($extension);
2912 // Loads given library (aka. PHP extension)
2913 // Credits: shaunspiller at spammenot-gmail dot com ( http://de.php.net/dl#88566 )
2914 function loadLibrary ($n, $f = NULL) {
2915 return extension_loaded($n) or dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
2918 // "Translates" given PHP extension name into a readable version
2919 function translatePhpExtension ($extension) {
2920 // Return the language element
2921 return '{--PHP_EXTENSION_' . strtoupper($extension) . '--}';