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 = getMinPasswordLength();
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 length of the password is below 40 characters additional
108 * security can be added by scrambling it. Otherwise the hash may
111 if (strlen($password) <= 40) {
112 // Also scramble the password
113 $password = scrambleString($password);
116 // Return the password
120 // Generates a human-readable timestamp from the Uni* stamp
121 function generateDateTime ($time, $mode = '0') {
123 if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
125 return $GLOBALS[__FUNCTION__][$time][$mode];
128 // If the stamp is zero it mostly didn't "happen"
129 if (($time == '0') || (is_null($time))) {
131 return '{--NEVER_HAPPENED--}';
134 // Filter out numbers
135 $timeSecured = bigintval($time);
138 switch (getLanguage()) {
139 case 'de': // German date / time format
141 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break;
142 case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break;
143 case '2': $ret = date('d.m.Y|H:i', $timeSecured); break;
144 case '3': $ret = date('d.m.Y', $timeSecured); break;
145 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
146 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
147 case '6': $ret = date('Ymd', $timeSecured); break;
148 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
150 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
155 default: // Default is the US date / time format!
157 case '0': $ret = date('r', $timeSecured); break;
158 case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break;
159 case '2': $ret = date('y-m-d|H:i', $timeSecured); break;
160 case '3': $ret = date('y-m-d', $timeSecured); break;
161 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
162 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
163 case '6': $ret = date('Ymd', $timeSecured); break;
164 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
166 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
172 $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
178 // Translates Y/N to yes/no
179 function translateYesNo ($yn) {
181 if (!isset($GLOBALS[__FUNCTION__][$yn])) {
183 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
186 $GLOBALS[__FUNCTION__][$yn] = '{--YES--}';
190 $GLOBALS[__FUNCTION__][$yn] = '{--NO--}';
193 default: // Log unknown value
194 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $yn));
200 return $GLOBALS[__FUNCTION__][$yn];
203 // "Translates" Y/N into "de-/active"
204 function translateActivationStatus ($status) {
206 if (!isset($GLOBALS[__FUNCTION__][$status])) {
208 $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')';
210 case 'Y': // Activated
211 $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}';
214 case 'N': // Deactivated
215 $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}';
218 default: // Log unknown value
219 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $status));
225 return $GLOBALS[__FUNCTION__][$status];
228 // Translates the american decimal dot into a german comma
229 // OPPOMENT: convertCommaToDot()
230 function translateComma ($dotted, $cut = TRUE, $max = '0') {
231 // First, cast all to double, due to PHP changes
232 $dotted = (double) $dotted;
234 // Default is 3 you can change this in admin area "Settings -> Misc Options"
235 if (!isConfigEntrySet('max_comma')) {
236 setConfigEntry('max_comma', 3);
239 // Use from config is default
240 $maxComma = getConfig('max_comma');
242 // Use from parameter?
248 if (($cut === TRUE) && ($max == '0')) {
249 // Test for commata if in cut-mode
250 $com = explode('.', $dotted);
251 if (count($com) < 2) {
252 // Don't display commatas even if there are none... ;-)
260 $translated = $dotted;
261 switch (getLanguage()) {
262 case 'de': // German language
263 $translated = number_format($dotted, $maxComma, ',', '.');
266 default: // All others
267 $translated = number_format($dotted, $maxComma, '.', ',');
271 // Return translated value
272 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
276 // Translate Uni*-like gender to human-readable
277 function translateGender ($gender) {
279 $ret = '!' . $gender . '!';
281 // Male/female or company?
286 // Use generic function
287 $ret = translateGeneric('GENDER', $gender);
291 // Please report bugs on unknown genders
292 reportBug(__FUNCTION__, __LINE__, sprintf('Unknown gender %s detected.', $gender));
296 // Return translated gender
300 // "Translates" the user status
301 function translateUserStatus ($status) {
302 // Default status is unknown if something goes through
303 $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
305 // Generate message depending on status
310 // Use generic function for all "normal" cases
311 $ret = translateGeneric('ACCOUNT_STATUS', $status);
314 case '': // Account deleted
315 case NULL: // Account deleted
316 $ret = '{--ACCOUNT_STATUS_DELETED--}';
319 default: // Please report all unknown status
320 reportBug(__FUNCTION__, __LINE__, sprintf('Unknown status %s(%s) detected.', $status, gettype($status)));
328 // "Translates" 'visible' and 'locked' to a CSS class
329 function translateMenuVisibleLocked ($content, $prefix = '') {
330 // Default is 'menu_unknown'
331 $content['visible_css'] = $prefix . 'menu_unknown';
333 // Translate 'visible' and keep an eye on the prefix
334 switch ($content['visible']) {
335 case 'Y': // Should be visible
336 $content['visible_css'] = $prefix . 'menu_visible';
339 case 'N': // Is invisible
340 $content['visible_css'] = $prefix . 'menu_invisible';
343 default: // Please report this
344 reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
348 // Translate 'locked' and keep an eye on the prefix
349 switch ($content['locked']) {
350 case 'Y': // Should be locked, only admins can call this
351 $content['locked_css'] = $prefix . 'menu_locked';
354 case 'N': // Is unlocked and visible to members/guests/sponsors
355 $content['locked_css'] = $prefix . 'menu_unlocked';
358 default: // Please report this
359 reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
363 // Return the resulting array
367 // Generates an URL for the dereferer
368 function generateDereferrerUrl ($url) {
369 // Don't de-refer our own links!
370 if ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
372 $encodedUrl = encodeString(compileUriCode($url));
375 $hash = generateHash($url . getSiteKey() . getDateKey());
377 // Log plain URL and hash
378 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
381 $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie($hash) . '&salt=' . substr($hash, 0, getSaltLength()) . '%}';
388 // Generates an URL for the frametester
389 function generateFrametesterUrl ($url) {
390 // Prepare frametester URL
391 $frametesterUrl = sprintf('{%%url=modules.php?module=frametester&url=%s%%}',
392 encodeString(compileUriCode($url))
395 // Return the new URL
396 return $frametesterUrl;
399 // Count entries from e.g. a selection box
400 function countSelection ($array) {
402 if (!is_array($array)) {
404 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
411 foreach ($array as $key => $selected) {
413 if (!empty($selected)) {
414 // Yes, then count it
419 // Return counted selections
423 // Generates a timestamp (some wrapper for mktime())
424 function makeTime ($hours, $minutes, $seconds, $stamp) {
425 // Extract day, month and year from given timestamp
426 $days = getDay($stamp);
427 $months = getMonth($stamp);
428 $years = getYear($stamp);
430 // Create timestamp for wished time which depends on extracted date
441 // Redirects to an URL and if neccessarry extends it with own base URL
442 function redirectToUrl ($url, $allowSpider = TRUE) {
443 // Is the output mode -2?
444 if (isAjaxOutputMode()) {
445 // This is always (!) an AJAX request and shall not be redirected
450 if (substr($url, 0, 6) == '{%url=') {
451 $url = substr($url, 6, -2);
455 eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
457 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
458 $rel = ' rel="external"';
460 // Is there internal or external URL?
461 if (substr($url, 0, strlen(getUrl())) == getUrl()) {
462 // Own (=internal) URL
466 // Three different ways to debug...
467 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
468 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
469 //* DEBUG: */ die($url);
471 // We should not sent a redirect if headers are already sent
472 if (!headers_sent()) {
473 // Load URL when headers are not sent
474 sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), FALSE));
476 // Output error message
477 loadInclude('inc/header.php');
478 loadTemplate('redirect_url', FALSE, str_replace('&', '&', $url));
479 loadInclude('inc/footer.php');
482 // Shut the mailer down here
486 /************************************************************************
488 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
489 * $a_sort sortiert: *
491 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
492 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
493 * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird *
494 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
495 * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren *
497 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
498 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
499 * Sie, dass es doch nicht so schwer ist! :-) *
501 ************************************************************************/
502 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
503 $temporaryArray = $array;
504 while ($primary_key < count($a_sort)) {
505 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
506 foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
508 if ($nums === FALSE) {
509 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
510 if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
511 } elseif ($key != $key2) {
512 // Sort numbers (E.g.: 9 < 10)
513 if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
514 if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = TRUE;
518 // We have found two different values, so let's sort whole array
519 foreach ($temporaryArray as $sort_key => $sort_val) {
520 $t = $temporaryArray[$sort_key][$key];
521 $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2];
522 $temporaryArray[$sort_key][$key2] = $t;
533 // Write back sorted array
534 $array = $temporaryArray;
539 // Deprecated : $length (still has one reference in this function)
540 // Optional : $extraData
542 function generateRandomCode ($length, $code, $userid, $extraData = '') {
543 // Build server string
544 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
547 $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
548 if (isConfigEntrySet('secret_key')) {
549 $keys .= getEncryptSeparator() . getSecretKey();
551 if (isConfigEntrySet('file_hash')) {
552 $keys .= getEncryptSeparator() . getFileHash();
554 $keys .= getEncryptSeparator() . getDateFromRepository();
555 if (isConfigEntrySet('master_salt')) {
556 $keys .= getEncryptSeparator() . getMasterSalt();
559 // Build string from misc data
560 $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
562 // Add more additional data
563 if (isSessionVariableSet('u_hash')) {
564 $data .= getEncryptSeparator() . getSession('u_hash');
567 // Add referral id, language, theme and userid
568 $data .= getEncryptSeparator() . determineReferralId();
569 $data .= getEncryptSeparator() . getLanguage();
570 $data .= getEncryptSeparator() . getCurrentTheme();
571 $data .= getEncryptSeparator() . getMemberId();
573 // Calculate number for generating the code
574 $a = $code + getConfig('_ADD') - 1;
576 if (isConfigEntrySet('master_salt')) {
577 // Generate hash with master salt from modula of number with the prime number and other data
578 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
580 // Generate hash with "hash of site key" from modula of number with the prime number and other data
581 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
584 // Create number from hash
585 $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
587 // At least 10 numbers shall be secure enought!
588 if (isExtensionActive('other')) {
589 $len = getCodeLength();
594 // Smaller 1 is not okay
600 // Cut off requested counts of number, but skip first digit (which is mostly a zero)
601 $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
603 // Done building code
607 // Does only allow numbers
608 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
609 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
610 // Filter all non-number chars out, so only number chars will remain
611 $ret = preg_replace('/[^0123456789]/', '', $num);
614 if ($castValue === TRUE) {
615 // Cast to biggest numeric type
616 $ret = (double) $ret;
619 // Has the whole value changed?
620 if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
622 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
626 //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
630 // Creates a Uni* timestamp from given selection data and prefix
631 function createEpocheTimeFromSelections ($prefix, $postData) {
632 // Assert on typical array element (maybe all?)
633 assert(isset($postData[$prefix . '_ye']));
635 // Initial return value
638 // Is there a leap year?
640 $TEST = getYear() / 4;
643 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
644 // 01 2 2 1 1 1 123 4 43 3 32 233 4 43 3 3210
645 if ((floor($TEST) == $TEST) && ($M1 == '02') && (((isset($postData[$prefix . '_mo'])) && ($postData[$prefix . '_mo'] > '02')) || ((isset($postData[$prefix . '_mn'])) && ($postData[$prefix . '_mn'] > '02')))) {
646 $SWITCH = getOneDay();
649 // First add years...
650 $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
653 if (isset($postData[$prefix . '_mo'])) {
654 $ret += $postData[$prefix . '_mo'] * 2628000;
655 } elseif (isset($postData[$prefix . '_mn'])) {
656 $ret += $postData[$prefix . '_mn'] * 2628000;
660 $ret += $postData[$prefix . '_we'] * 604800;
663 $ret += $postData[$prefix . '_da'] * 86400;
666 $ret += $postData[$prefix . '_ho'] * 3600;
669 $ret += $postData[$prefix . '_mi'] * 60;
671 // And at last seconds...
672 $ret += $postData[$prefix . '_se'];
674 // Return calculated value
678 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
679 function createFancyTime ($stamp) {
680 // Get data array with years/months/weeks/days/...
681 $data = createTimeSelections($stamp, '', '', '', TRUE);
683 foreach ($data as $k => $v) {
685 // Value is greater than 0 "eval" data to return string
686 $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
691 // Is something there?
693 // Remove leading commata and space
694 $ret = substr($ret, 2);
697 $ret = '0 {--TIME_UNIT_SECOND--}';
700 // Return fancy time string
704 // Taken from www.php.net isInStringIgnoreCase() user comments
705 function isEmailValid ($email) {
706 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
709 if (!isset($GLOBALS[__FUNCTION__][$email])) {
710 // Check first part of email address
711 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
714 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
717 $regex = '@^' . $first . '\@' . $domain . '$@iU';
720 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
723 // Return check result
724 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
725 return $GLOBALS[__FUNCTION__][$email];
728 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
729 function isUrlValid ($url, $compile = TRUE) {
731 $url = trim(urldecode($url));
732 //* DEBUG: */ debugOutput($url);
734 // Compile some chars out...
735 if ($compile === TRUE) {
736 $url = compileUriCode($url, FALSE, FALSE, FALSE);
738 //* DEBUG: */ debugOutput($url);
740 // Check for the extension filter
741 if (isExtensionActive('filter')) {
742 // Use the extension's filter set
743 return FILTER_VALIDATE_URL($url, FALSE);
747 * If not installed, perform a simple test. Just make it sure there is always a
748 * http:// or https:// in front of the URLs.
750 return isUrlValidSimple($url);
753 // Generate a hash for extra-security for all passwords
754 function generateHash ($plainText, $salt = '', $hash = TRUE) {
756 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
758 // Is the required extension 'sql_patches' there and a salt is not given?
759 // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21
760 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
761 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
762 if ($hash === TRUE) {
764 return md5($plainText);
771 // Is an arry element missing here?
772 if (!isConfigEntrySet('file_hash')) {
774 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
777 // When the salt is empty build a new one, else use the first x configured characters as the salt
779 // Build server string for more entropy
780 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
783 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
785 // Is the secret_key config entry set?
786 if (isConfigEntrySet('secret_key')) {
788 $keys .= getEncryptSeparator() . getSecretKey();
792 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
794 // Calculate number for generating the code
795 $a = time() + getConfig('_ADD') - 1;
797 // Generate SHA1 sum from modula of number and the prime number
798 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
799 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
800 $sha1 = scrambleString($sha1);
801 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
802 //* DEBUG: */ $sha1b = descrambleString($sha1);
803 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
805 // Generate the password salt string
806 $salt = substr($sha1, 0, getSaltLength());
807 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
810 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
811 $salt = substr($salt, 0, getSaltLength());
812 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
814 // Sanity check on salt
815 if (strlen($salt) != getSaltLength()) {
817 reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
821 // Generate final hash (for debug output)
822 $finalHash = $salt . sha1($salt . $plainText);
825 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
832 function scrambleString ($str) {
836 // Final check, in case of failure it will return unscrambled string
837 if (strlen($str) > 40) {
838 // The string is to long
840 } elseif (strlen($str) == 40) {
842 $scrambleNums = explode(':', getPassScramble());
844 // Generate new numbers
845 $scrambleNums = explode(':', genScrambleString(strlen($str)));
848 // Assert on both lengths
849 assert(strlen($str) == count($scrambleNums));
851 // Scramble string here
852 //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
853 for ($idx = 0; $idx < strlen($str); $idx++) {
854 // Get char on scrambled position
855 $char = substr($str, $scrambleNums[$idx], 1);
857 // Add it to final output string
861 // Return scrambled string
862 //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
866 // De-scramble a string scrambled by scrambleString()
867 function descrambleString ($str) {
868 // Scramble only 40 chars long strings
869 if (strlen($str) != 40) {
873 // Load numbers from config
874 $scrambleNums = explode(':', getPassScramble());
877 if (count($scrambleNums) != 40) {
881 // Begin descrambling
882 $orig = str_repeat(' ', 40);
883 //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
884 for ($idx = 0; $idx < 40; $idx++) {
885 $char = substr($str, $idx, 1);
886 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
889 // Return scrambled string
890 //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
894 // Generated a "string" for scrambling
895 function genScrambleString ($len) {
896 // Prepare array for the numbers
897 $scrambleNumbers = array();
899 // First we need to setup randomized numbers from 0 to 31
900 for ($idx = 0; $idx < $len; $idx++) {
902 $rand = mt_rand(0, ($len - 1));
904 // Check for it by creating more numbers
905 while (array_key_exists($rand, $scrambleNumbers)) {
906 $rand = mt_rand(0, ($len - 1));
910 $scrambleNumbers[$rand] = $rand;
913 // So let's create the string for storing it in database
914 $scrambleString = implode(':', $scrambleNumbers);
917 return $scrambleString;
920 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
921 function encodeHashForCookie ($passHash) {
922 // Return vanilla password hash
925 // Is a secret key and master salt already initialized?
926 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
927 if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
928 // Only calculate when the secret key is generated
929 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
930 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
931 // Both keys must have same length so return unencrypted
932 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 - EXIT!');
936 $newHash = ''; $start = 9;
937 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
938 for ($idx = 0; $idx < 20; $idx++) {
939 // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
940 $part1 = hexdec(substr($passHash , $start, 2));
941 $part2 = hexdec(substr(getSecretKey(), $start, 2));
943 // Default is hexadecimal of index if both are same
946 // Is part1 larger or part2 than its counter part?
947 if ($part1 > $part2) {
949 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
950 } elseif ($part2 > $part1) {
952 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
955 $mod = substr($mod, 0, 2);
956 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
957 $mod = padLeftZero($mod, 2);
958 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
963 // Just copy it over, as the master salt is not really helpful here
964 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
969 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
973 // Fix "deleted" cookies
974 function fixDeletedCookies ($cookies) {
975 // Is this an array with entries?
976 if (isFilledArray($cookies)) {
977 // Then check all cookies if they are marked as deleted!
978 foreach ($cookies as $cookieName) {
979 // Is the cookie set to "deleted"?
980 if (getSession($cookieName) == 'deleted') {
981 setSession($cookieName, '');
987 // Checks if a given apache module is loaded
988 function isApacheModuleLoaded ($apacheModule) {
989 // Check it and return result
990 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
993 // Get current theme name
994 function getCurrentTheme () {
995 // The default theme is 'default'... ;-)
998 // Is there ext-theme installed and active or is 'theme' in URL or POST data?
999 if (isExtensionActive('theme')) {
1000 // Call inner method
1001 $ret = getActualTheme();
1002 } elseif ((isPostRequestElementSet('theme')) && (isThemeReadable(postRequestElement('theme')))) {
1003 // Use value from POST data
1004 $ret = postRequestElement('theme');
1005 } elseif ((isGetRequestElementSet('theme')) && (isThemeReadable(getRequestElement('theme')))) {
1006 // Use value from GET data
1007 $ret = getRequestElement('theme');
1008 } elseif ((isMailerThemeSet()) && (isThemeReadable(getMailerTheme()))) {
1009 // Use value from GET data
1010 $ret = getMailerTheme();
1013 // Return theme value
1017 // Generates an error code from given account status
1018 function generateErrorCodeFromUserStatus ($status = '') {
1019 // If no status is provided, use the default, cached
1020 if ((empty($status)) && (isMember())) {
1022 $status = getUserData('status');
1025 // Default error code if unknown account status
1026 $errorCode = getCode('ACCOUNT_UNKNOWN');
1028 // Generate constant name
1029 $codeName = sprintf('ACCOUNT_%s', strtoupper($status));
1031 // Is the constant there?
1032 if (isCodeSet($codeName)) {
1034 $errorCode = getCode($codeName);
1037 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown error status %s detected.', $status));
1040 // Return error code
1044 // Back-ported from the new ship-simu engine. :-)
1045 function debug_get_printable_backtrace () {
1047 $backtrace = '<ol>';
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 .= '<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>';
1059 $backtrace .= '</ol>';
1061 // Return the backtrace
1065 // A mail-able backtrace
1066 function debug_get_mailable_backtrace () {
1070 // Get and prepare backtrace for output
1071 $backtraceArray = debug_backtrace();
1072 foreach ($backtraceArray as $key => $trace) {
1073 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1074 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1075 if (!isset($trace['args'])) $trace['args'] = array();
1076 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1079 // Return the backtrace
1083 // Generates a ***weak*** seed
1084 function generateSeed () {
1085 return microtime(TRUE) * 100000;
1088 // Converts a message code to a human-readable message
1089 function getMessageFromErrorCode ($code) {
1090 // Default is an unknown error code
1091 $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1093 // Which code is provided?
1096 // No error code is bad coding practice
1097 reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1100 // All error messages
1101 case getCode('LOGOUT_DONE') : $message = '{--LOGOUT_DONE--}'; break;
1102 case getCode('LOGOUT_FAILED') : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1103 case getCode('DATA_INVALID') : $message = '{--MAIL_DATA_INVALID--}'; break;
1104 case getCode('POSSIBLE_INVALID') : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1105 case getCode('USER_404') : $message = '{--USER_404--}'; break;
1106 case getCode('STATS_404') : $message = '{--MAIL_STATS_404--}'; break;
1107 case getCode('ALREADY_CONFIRMED') : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1108 case getCode('BEG_SAME_AS_OWN') : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1109 case getCode('LOGIN_FAILED') : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1110 case getCode('MODULE_MEMBER_ONLY') : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1111 case getCode('OVERLENGTH') : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1112 case getCode('URL_FOUND') : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1113 case getCode('SUBJECT_URL') : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1114 case getCode('BLIST_URL') : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1115 case getCode('NO_RECS_LEFT') : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1116 case getCode('INVALID_TAGS') : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1117 case getCode('MORE_POINTS') : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1118 case getCode('MORE_RECEIVERS1') : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1119 case getCode('MORE_RECEIVERS2') : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1120 case getCode('MORE_RECEIVERS3') : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1121 case getCode('INVALID_URL') : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1122 case getCode('NO_MAIL_TYPE') : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1123 case getCode('PROFILE_UPDATED') : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1124 case getCode('UNKNOWN_REDIRECT') : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1125 case getCode('WRONG_PASS') : $message = '{--LOGIN_WRONG_PASS--}'; break;
1126 case getCode('WRONG_ID') : $message = '{--LOGIN_WRONG_ID--}'; break;
1127 case getCode('ACCOUNT_LOCKED') : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1128 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1129 case getCode('COOKIES_DISABLED') : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1130 case getCode('UNKNOWN_ERROR') : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1131 case getCode('UNKNOWN_STATUS') : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1132 case getCode('LOGIN_EMPTY_ID') : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1133 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1135 case getCode('ERROR_MAILID'):
1136 if (isExtensionActive('mailid', TRUE)) {
1137 $message = '{--ERROR_CONFIRMING_MAIL--}';
1139 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1143 case getCode('EXTENSION_PROBLEM'):
1144 if (isGetRequestElementSet('ext')) {
1145 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1147 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1151 case getCode('URL_TIME_LOCK'):
1152 // Load timestamp from last order
1153 $content = getPoolDataFromId(getRequestElement('id'));
1155 // Translate it for templates
1156 $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1158 // Calculate hours...
1159 $content['hours'] = round(getUrlTlock() / 60 / 60);
1162 $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1165 $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1167 // Finally contruct the message
1168 $message = loadTemplate('tlock_message', TRUE, $content);
1172 // Log missing/invalid error codes
1173 logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1177 // Return the message
1181 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1182 function isUrlValidSimple ($url) {
1183 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1185 $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1187 // Allows http and https
1188 $http = "(http|https)+(:\/\/)";
1190 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1191 // Test double-domains (e.g. .de.vu)
1192 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1194 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1196 $dir = "((/)+([-_\.[:alnum:]])+)*";
1198 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1199 // ... and the string after and including question character
1200 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1201 // Pattern for URLs like http://url/dir/doc.html?var=value
1202 $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
1203 $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
1204 $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
1205 // Pattern for URLs like http://url/dir/?var=value
1206 $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
1207 $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
1208 $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
1209 // Pattern for URLs like http://url/dir/page.ext
1210 $pattern['d1dp'] = $http . $domain1 . $dir . $page;
1211 $pattern['d1dp'] = $http . $domain2 . $dir . $page;
1212 $pattern['ipdp'] = $http . $ip . $dir . $page;
1213 // Pattern for URLs like http://url/dir
1214 $pattern['d1d'] = $http . $domain1 . $dir;
1215 $pattern['d2d'] = $http . $domain2 . $dir;
1216 $pattern['ipd'] = $http . $ip . $dir;
1217 // Pattern for URLs like http://url/?var=value
1218 $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
1219 $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
1220 $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
1221 // Pattern for URLs like http://url?var=value
1222 $pattern['d1g12'] = $http . $domain1 . $getstring1;
1223 $pattern['d2g12'] = $http . $domain2 . $getstring1;
1224 $pattern['ipg12'] = $http . $ip . $getstring1;
1226 // Test all patterns
1228 foreach ($pattern as $key => $pat) {
1230 if (isDebugRegularExpressionEnabled()) {
1231 // @TODO Are these convertions still required?
1232 $pat = str_replace('.', '\.', $pat);
1233 $pat = str_replace('@', '\@', $pat);
1234 //* DEBUG: */ debugOutput($key . '= ' . $pat);
1237 // Check if expression matches
1238 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1241 if ($reg === TRUE) {
1246 // Return true/false
1247 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1251 // Wtites data to a config.php-style file
1252 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1253 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek = 0) {
1254 // Initialize some variables
1260 // Is the file there and read-/write-able?
1261 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1262 $search = 'CFG: ' . $comment;
1263 $tmp = $FQFN . '.tmp';
1265 // Open the source file
1266 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1268 // Is the resource valid?
1269 if (is_resource($fp)) {
1270 // Open temporary file
1271 $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1273 // Is the resource again valid?
1274 if (is_resource($fp_tmp)) {
1275 // Mark temporary file as readable
1276 $GLOBALS['file_readable'][$tmp] = TRUE;
1279 while (!feof($fp)) {
1280 // Read from source file
1281 $line = fgets($fp, 1024);
1283 if (isInString($search, $line)) {
1289 if ($next === $seek) {
1291 $line = $prefix . $inserted . $suffix . PHP_EOL;
1297 // Write to temp file
1298 fwrite($fp_tmp, $line);
1304 // Finished writing tmp file
1308 // Close source file
1311 if (($done === TRUE) && ($found === TRUE)) {
1312 // Copy back temporary->FQFN file and ...
1313 copyFileVerified($tmp, $FQFN, 0644);
1315 // ... delete temporay file :-)
1316 return removeFile($tmp);
1317 } elseif ($found === FALSE) {
1319 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!');
1321 // Temporary file not fully written
1322 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - Temporary file unfinished!');
1326 // File not found, not readable or writeable
1327 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN) . ',comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek);
1330 // An error was detected!
1334 // Debug message logger
1335 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1336 // Is debug mode enabled?
1337 if ((isDebugModeEnabled()) || ($force === TRUE)) {
1339 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1341 // Log this message away
1342 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1346 // Handle extra values
1347 function handleExtraValues ($filterFunction, $value, $extraValue) {
1348 // Default is the value itself
1351 // Is there a special filter function?
1352 if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1353 // Call-back function does not exist or is empty
1354 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1357 // Is there extra parameters here?
1358 if ((!is_null($extraValue)) && (!empty($extraValue))) {
1359 // Put both parameters in one new array by default
1360 $args = array($value, $extraValue);
1362 // If we have an array simply use it and pre-extend it with our value
1363 if (is_array($extraValue)) {
1364 // Make the new args array
1365 $args = merge_array(array($value), $extraValue);
1368 // Call the multi-parameter call-back
1369 $ret = call_user_func_array($filterFunction, $args);
1372 if ($ret === TRUE) {
1373 // Test passed, so write direct value
1377 // One parameter call
1378 $ret = call_user_func($filterFunction, $value);
1379 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1382 if ($ret === TRUE) {
1383 // Test passed, so write direct value
1392 // Tries to determine if call-back functions and/or extra values shall be parsed
1393 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1394 // Debug mode enabled?
1395 if (isDebugModeEnabled()) {
1397 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1400 // Send data through the filter function if found
1401 if ($key === $userIdColumn[0]) {
1402 // Is the userid, we have to process it with convertZeroToNull()
1403 $entries = convertZeroToNull($entries);
1404 } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1405 // Debug mode enabled?
1406 if (isDebugModeEnabled()) {
1408 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1411 // Filter function + extra value set
1412 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1414 // Debug mode enabled?
1415 if (isDebugModeEnabled()) {
1417 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1419 } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1420 // Debug mode enabled?
1421 if (isDebugModeEnabled()) {
1423 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1426 // Handle extra values
1427 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1429 // Debug mode enabled?
1430 if (isDebugModeEnabled()) {
1432 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1435 // Make sure entries is not bool, then something went wrong
1436 assert(!is_bool($entries));
1437 } elseif (!empty($filterFunctions[$search])) {
1438 // Debug mode enabled?
1439 if (isDebugModeEnabled()) {
1441 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1444 // Handle extra values
1445 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1447 // Debug mode enabled?
1448 if (isDebugModeEnabled()) {
1450 /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1453 // Make sure entries is not bool, then something went wrong
1454 assert(!is_bool($entries));
1461 // Converts timestamp selections into a timestamp
1462 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1463 // Init test variable
1467 // Get last three chars
1468 $test = substr($id, -3);
1470 // Improved way of checking! :-)
1471 if (in_array($test, array('_ye', '_mo', '_mn', '_we', '_da', '_ho', '_mi', '_se'))) {
1472 // Found a multi-selection for timings?
1473 $test = substr($id, 0, -3);
1474 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)) {
1475 // Generate timestamp
1476 $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1477 array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1478 $GLOBALS['skip_config'][$test] = TRUE;
1480 // Remove data from array
1481 foreach (array('ye', 'mo', 'mn', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1482 unset($postData[$test . '_' . $rem]);
1493 // Reverts the german decimal comma into Computer decimal dot
1494 // OPPOMENT: translateComma()
1495 function convertCommaToDot ($str) {
1496 // Default float is not a float... ;-)
1499 // Which language is selected?
1500 switch (getLanguage()) {
1501 case 'de': // German language
1502 // Remove german thousand dots first
1503 $str = str_replace('.', '', $str);
1505 // Replace german commata with decimal dot and cast it
1506 $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str));
1509 default: // US and so on
1510 // Remove thousand commatas first and cast
1511 $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str));
1519 // Handle menu-depending failed logins and return the rendered content
1520 function handleLoginFailures ($accessLevel) {
1521 // Default output is empty ;-)
1524 // Is the session data set?
1525 if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1526 // Ignore zero values
1527 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1528 // Non-guest has login failures found, get both data and prepare it for template
1529 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1531 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1532 'last_failure' => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1536 $OUT = loadTemplate('login_failures', TRUE, $content);
1539 // Reset session data
1540 setSession('mailer_' . $accessLevel . '_failures', '');
1541 setSession('mailer_' . $accessLevel . '_last_failure', '');
1544 // Return rendered content
1549 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1551 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1553 // Shall I remove the cache file?
1554 if ((isExtensionInstalled('cache')) && (isValidCacheInstance()) && (isHtmlOutputMode())) {
1555 // Rebuild cache only in HTML output-mode
1556 // @TODO This should be rewritten not to load the cache file for just checking if it is there for save removal.
1557 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1559 $GLOBALS['cache_instance']->removeCacheFile($force);
1562 // Include file given?
1565 $inc = sprintf('inc/loader/load-%s.php', $inc);
1567 // Is the include there?
1568 if (isIncludeReadable($inc)) {
1569 // And rebuild it from scratch
1570 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1573 // Include not found, which needs now tracing
1574 reportBug(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1580 // Determines the real remote address
1581 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1582 // Default is 127.0.0.1
1583 $address = '127.0.0.1';
1585 // Is a proxy in use?
1586 if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1588 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1589 } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1590 // Yet, another proxy
1591 $address = $_SERVER['HTTP_CLIENT_IP'];
1592 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1593 // The regular address when no proxy was used
1594 $address = $_SERVER['REMOTE_ADDR'];
1597 // This strips out the real address from proxy output
1598 if (strstr($address, ',')) {
1599 $addressArray = explode(',', $address);
1600 $address = $addressArray[0];
1603 // Return the result
1607 // Adds a bonus mail to the queue
1608 // This is a high-level function!
1609 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1610 // Use mode from data if not set and availble ;-)
1611 if ((empty($mode)) && (isset($data['mail_mode']))) {
1612 $mode = $data['mail_mode'];
1615 // Generate receiver list
1616 $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1619 if (!empty($receiver)) {
1620 // Add bonus mail to queue
1621 addBonusMailToQueue(
1633 // Mail inserted into bonus pool
1634 if ($output === TRUE) {
1635 displayMessage('{--ADMIN_BONUS_SEND--}');
1637 } elseif ($output === TRUE) {
1638 // More entered than can be reached!
1639 displayMessage('{--ADMIN_MORE_SELECTED--}');
1642 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1646 // Enables the hourly reset mode and runs it
1647 function doHourly () {
1648 // Enable the hourly reset mode
1649 $GLOBALS['hourly_enabled'] = TRUE;
1651 // Run filters (one always!)
1652 runFilterChain('hourly');
1654 // Do not update in hourly debug mode
1655 if ((!isConfigEntrySet('DEBUG_HOURLY')) || (!isDebugHourlyEnabled())) {
1657 updateConfiguration('last_hourly', getHour());
1661 // Enables the daily reset mode and runs it
1662 function doDaily () {
1663 // Enable the reset mode
1664 $GLOBALS['daily_enabled'] = TRUE;
1667 runFilterChain('daily');
1669 // Do not update in daily debug mode
1670 if ((!isConfigEntrySet('DEBUG_DAILY')) || (!isDebugDailyEnabled())) {
1672 updateConfiguration('last_daily', getDay());
1676 // Enables the weekly reset mode and runs it
1677 function doWeekly () {
1678 // Enable the reset mode
1679 $GLOBALS['weekly_enabled'] = TRUE;
1682 runFilterChain('weekly');
1684 // Do not update in weekly debug mode
1685 if ((!isConfigEntrySet('DEBUG_WEEKLY')) || (!isDebugWeeklyEnabled())) {
1687 updateConfiguration('last_weekly', getWeek());
1691 // Enables the monthly reset mode and runs it
1692 function doMonthly () {
1693 // Enable the reset mode
1694 $GLOBALS['monthly_enabled'] = TRUE;
1697 runFilterChain('monthly');
1699 // Do not update in monthly debug mode
1700 if ((!isConfigEntrySet('DEBUG_MONTHLY')) || (!isDebugMonthlyEnabled())) {
1702 updateConfiguration('last_monthly', getMonth());
1706 // Enables the yearly reset mode and runs it
1707 function doYearly () {
1708 // Enable the reset mode
1709 $GLOBALS['yearly_enabled'] = TRUE;
1712 runFilterChain('yearly');
1714 // Do not update in yearly debug mode
1715 if ((!isConfigEntrySet('DEBUG_YEARLY')) || (!isDebugYearlyEnabled())) {
1717 updateConfiguration('last_yearly', getYear());
1721 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1722 function doShutdown () {
1723 // Call the filter chain 'shutdown'
1724 runFilterChain('shutdown', NULL);
1726 // Check if link is up
1727 if (isSqlLinkUp()) {
1729 sqlCloseLink(__FUNCTION__, __LINE__);
1730 } elseif (!isInstaller()) {
1732 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1735 // Stop executing here
1740 function initMemberId () {
1741 $GLOBALS['member_id'] = '0';
1744 // Setter for member id
1745 function setMemberId ($memberId) {
1746 // We should not set member id to zero
1747 if (!isValidId($memberId)) {
1748 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1752 $GLOBALS['member_id'] = bigintval($memberId);
1755 // Getter for member id or returns zero
1756 function getMemberId () {
1757 // Default member id
1760 // Is the member id set?
1761 if (isMemberIdSet()) {
1763 $memberId = $GLOBALS['member_id'];
1770 // Checks ether the member id is set
1771 function isMemberIdSet () {
1772 return (isset($GLOBALS['member_id']));
1775 // Setter for extra title
1776 function setExtraTitle ($extraTitle) {
1777 $GLOBALS['extra_title'] = $extraTitle;
1780 // Getter for extra title
1781 function getExtraTitle () {
1782 // Is the extra title set?
1783 if (!isExtraTitleSet()) {
1784 // No, then abort here
1785 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1789 return $GLOBALS['extra_title'];
1792 // Checks if the extra title is set
1793 function isExtraTitleSet () {
1794 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1798 * Reads a directory recursively by default and searches for files not matching
1799 * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1800 * a whole directory.
1802 * @param $baseDir Relative base directory to PATH to scan from
1803 * @param $prefix Prefix for all positive matches (which files should be found)
1804 * @param $fileIncludeDirs whether to include directories in the final output array
1805 * @param $addBaseDir whether to add $baseDir to all array entries
1806 * @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'
1807 * @param $extension File extension for all positive matches
1808 * @param $excludePattern Regular expression to exclude more files (preg_match())
1809 * @param $recursive whether to scan recursively
1810 * @param $suffix Suffix for positive matches ($extension will be appended, too)
1811 * @param $withPrefixSuffix Whether to include prefix/suffix in found entries
1812 * @return $foundMatches All found positive matches for above criteria
1814 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '', $withPrefixSuffix = TRUE) {
1815 // Add default entries we should always exclude
1816 array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1818 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1819 // Init found includes
1820 $foundMatches = array();
1823 $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1826 while ($baseFile = readdir($dirPointer)) {
1827 // Exclude '.', '..' and entries in $excludeArray automatically
1828 if (in_array($baseFile, $excludeArray, TRUE)) {
1830 //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1834 // Construct include filename and FQFN
1835 $fileName = $baseDir . $baseFile;
1836 $FQFN = getPath() . $fileName;
1838 // Remove double slashes
1839 $FQFN = str_replace('//', '/', $FQFN);
1841 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1842 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1844 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1850 // Skip also files with non-matching prefix genericly
1851 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1852 // Is a redirectory so read it as well
1853 $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1855 // And skip further processing
1857 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1859 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1861 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1862 // Skip wrong suffix as well
1863 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1865 } elseif (!isFileReadable($FQFN)) {
1866 // Not readable so skip it
1867 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1868 } elseif (filesize($FQFN) < 50) {
1869 // Might be deprecated
1870 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1872 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1873 // This PHP script is deprecated
1874 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1878 // Get file' extension (last 4 chars)
1879 $fileExtension = substr($baseFile, -4, 4);
1881 // Is the file a PHP script or other?
1882 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1883 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1884 // Is this a valid include file?
1885 if ($extension == '.php') {
1886 // Remove both for extension name
1887 $extName = substr($baseFile, strlen($prefix), -4);
1889 // Add file with or without base path
1890 if ($addBaseDir === TRUE) {
1892 array_push($foundMatches, $fileName);
1893 } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1895 array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1898 array_push($foundMatches, $baseFile);
1901 // We found .php file but should not search for them, why?
1902 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1904 } elseif ((($fileExtension == $extension) || (empty($extension))) && (isFileReadable($FQFN))) {
1905 // Other, generic file found
1906 if ($addBaseDir === TRUE) {
1908 array_push($foundMatches, $fileName);
1909 } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1911 array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1914 array_push($foundMatches, $baseFile);
1920 closedir($dirPointer);
1923 sort($foundMatches);
1925 // Return array with include files
1926 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1927 return $foundMatches;
1930 // Checks whether $prefix is found in $fileName
1931 function isFilePrefixFound ($fileName, $prefix) {
1932 // @TODO Find a way to cache this
1933 return (substr($fileName, 0, strlen($prefix)) == $prefix);
1936 // Maps a module name into a database table name
1937 function mapModuleToTable ($moduleName) {
1938 // Map only these, still lame code...
1939 switch ($moduleName) {
1940 case 'index': // 'index' is the guest's menu
1941 $moduleName = 'guest';
1944 case 'login': // ... and 'login' the member's menu
1945 $moduleName = 'member';
1947 // Anything else will not be mapped, silently.
1954 // Add SQL debug data to array for later output
1955 function addSqlToDebug ($result, $sqlString, $timing, $file, $line) {
1957 if (!isset($GLOBALS['debug_sql_available'])) {
1958 // Check it and cache it in $GLOBALS
1959 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1962 // Don't execute anything here if we don't need or ext-other is missing
1963 if ($GLOBALS['debug_sql_available'] === FALSE) {
1967 // Already executed?
1968 if (isset($GLOBALS['debug_sqls'][$file][$line][$sqlString])) {
1969 // Then abort here, we don't need to profile a query twice
1973 // Remeber this as profiled (or not, but we don't care here)
1974 $GLOBALS['debug_sqls'][$file][$line][$sqlString] = TRUE;
1978 'num_rows' => sqlNumRows($result),
1979 'affected' => sqlAffectedRows(),
1980 'sql_str' => $sqlString,
1981 'timing' => $timing,
1982 'file' => basename($file),
1987 array_push($GLOBALS['debug_sqls'], $record);
1990 // Initializes the cache instance
1991 function initCacheInstance () {
1992 // Check for double-initialization
1993 if (isset($GLOBALS['cache_instance'])) {
1994 // This should not happen and must be fixed
1995 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1998 // Load include for CacheSystem class
1999 loadIncludeOnce('inc/classes/cachesystem.class.php');
2001 // Initialize cache system only when it's needed
2002 $GLOBALS['cache_instance'] = new CacheSystem();
2005 if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
2006 // Failed to initialize cache sustem
2007 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
2011 // Getter for message from array or raw message
2012 function getMessageFromIndexedArray ($message, $pos, $array) {
2013 // Check if the requested message was found in array
2014 if (isset($array[$pos])) {
2015 // ... if yes then use it!
2016 $ret = $array[$pos];
2018 // ... else use default message
2026 // Convert ';' to ', ' for e.g. receiver list
2027 function convertReceivers ($old) {
2028 return str_replace(';', ', ', $old);
2031 // Get a module from filename and access level
2032 function getModuleFromFileName ($file, $accessLevel) {
2033 // Default is 'invalid';
2034 $modCheck = 'invalid';
2036 // @TODO This is still very static, rewrite it somehow
2037 switch ($accessLevel) {
2039 $modCheck = 'admin';
2045 $modCheck = getModule();
2048 default: // Unsupported file name / access level
2049 reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2057 // Encodes an URL for adding session id, etc.
2058 function encodeUrl ($url, $outputMode = '0') {
2059 // Is there already have a PHPSESSID inside or view.php is called? Then abort here
2060 if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
2061 // Raw output mode detected or session_name() found in URL
2065 // Is there a valid session?
2066 if ((!isValidSession()) && (!isSpider())) {
2067 // Determine right separator
2068 $separator = '&';
2069 if (!isInString('?', $url)) {
2074 // Then add it to URL
2075 $url .= $separator . session_name() . '=' . session_id();
2079 if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2081 $url = '{?URL?}/' . $url;
2085 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
2087 // Is there to decode entities?
2088 if (!isHtmlOutputMode()) {
2089 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
2090 // Decode them for e.g. JavaScript parts
2091 $url = decodeEntities($url);
2092 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
2096 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
2098 // Return the encoded URL
2102 // Simple check for spider
2103 function isSpider () {
2104 // Get the UA and trim it down
2105 $userAgent = trim(detectUserAgent(TRUE));
2107 // It should not be empty, if so it is better a browser
2108 if (empty($userAgent)) {
2109 // It is a browser that blocks its UA string
2114 return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2117 // Function to search for the last modified file
2118 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2120 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2121 // Does it match what we are looking for? (We skip a lot files already!)
2122 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2123 $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2125 $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2126 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2128 // Walk through all entries
2129 foreach ($ds as $d) {
2130 // Generate proper FQFN
2131 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2133 // Is it a file and readable?
2134 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2135 if (isFileReadable($FQFN)) {
2136 // $FQFN is a readable file so extract the requested data from it
2137 $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2138 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2140 // Is the file more recent?
2141 if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2142 // This file is newer as the file before
2143 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2144 $last_changed['path_name'] = $FQFN;
2145 $last_changed[$lookFor] = $check;
2149 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2154 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2155 function handleFieldWithBraces ($field) {
2156 // Are there braces [] at the end?
2157 if (substr($field, -2, 2) == '[]') {
2159 * Try to find one and replace it. I do it this way to allow easy
2160 * extending of this code.
2162 foreach (array('admin_list_builder_id_value') as $key) {
2163 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2164 // Is the cache entry set?
2165 if (isset($GLOBALS[$key])) {
2167 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2170 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2180 // Converts a zero or NULL to word 'NULL'
2181 function convertZeroToNull ($number) {
2182 // Is it a valid username?
2183 if (isValidNumber($number)) {
2185 $number = bigintval($number);
2187 // Is not valid or zero
2195 // Converts a NULL|empty string|< 1 to zero
2196 function convertNullToZero ($number) {
2197 // Is it a valid username?
2198 if (!isValidNumber($number)) {
2199 // Is not valid or zero
2207 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2208 // Note: This function is cached
2209 function capitalizeUnderscoreString ($str) {
2211 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2212 // Init target string
2215 // Explode it with the underscore, but rewrite dashes to underscore before
2216 $strArray = explode('_', str_replace('-', '_', $str));
2218 // "Walk" through all elements and make them lower-case but first upper-case
2219 foreach ($strArray as $part) {
2220 // Capitalize the string part
2221 $capitalized .= firstCharUpperCase($part);
2224 // Store the converted string in cache array
2225 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2229 return $GLOBALS[__FUNCTION__][$str];
2232 // Generate admin links for mail order
2233 // mailType can be: 'normal' or 'bonus'
2234 function generateAdminMailLinks ($mailType, $mailId) {
2239 // Default column for mail status is 'data_type'
2240 // @TODO Rename column data_type to e.g. mail_status
2241 $statusColumn = 'data_type';
2243 // Which mail do we have?
2244 switch ($mailType) {
2245 case 'bonus': // Bonus mail
2249 case 'normal': // Member mail
2253 default: // Handle unsupported types
2254 logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2255 $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2259 // Is the mail type supported?
2260 if (!empty($table)) {
2261 // Query for the mail
2262 $result = sqlQueryEscaped("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2267 ), __FILE__, __LINE__);
2269 // Is there one entry there?
2270 if (sqlNumRows($result) == 1) {
2272 $content = sqlFetchArray($result);
2274 // Add output and type
2275 $content['type'] = $mailType;
2276 $content['__output'] = '';
2279 $content = runFilterChain('generate_admin_mail_links', $content);
2282 $OUT = $content['__output'];
2286 sqlFreeResult($result);
2289 // Return generated HTML code
2295 * Determine if a string can represent a number in hexadecimal
2297 * @param $hex A string to check if it is hex-encoded
2298 * @return $foo True if the string is a hex, otherwise false
2299 * @author Marques Johansson
2300 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
2302 function isHexadecimal ($hex) {
2303 // Make it lowercase
2304 $hex = strtolower(trim(ltrim($hex, '0')));
2306 // Fix empty strings to zero
2311 // Simply compare decode->encode result with original
2312 return ($hex == dechex(hexdec($hex)));
2316 * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2317 * them visible to the developer. Use this function to debug e.g. buggy HTTP
2318 * response handler functions.
2320 * @param $str String to overwork
2321 * @return $str Overworked string
2323 function replaceReturnNewLine ($str) {
2324 return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2327 // Converts a given string by splitting it up with given delimiter similar to
2328 // explode(), but appending the delimiter again
2329 function stringToArray ($delimiter, $string) {
2331 $strArray = array();
2333 // "Walk" through all entries
2334 foreach (explode($delimiter, $string) as $split) {
2335 // Append the delimiter and add it to the array
2336 array_push($strArray, $split . $delimiter);
2343 // Detects the prefix 'mb_' if a multi-byte string is given
2344 function detectMultiBytePrefix ($str) {
2345 // Default is without multi-byte
2348 // Detect multi-byte (strictly)
2349 if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2350 // With multi-byte encoded string
2354 // Return the prefix
2358 // Searches given array for a sub-string match and returns all found keys in an array
2359 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2360 // Init array for all found keys
2363 // Now check all entries
2364 foreach ($needles as $key => $needle) {
2365 // Is there found a partial string?
2366 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2367 if (strpos($heystack, $needle, $offset) !== FALSE) {
2368 // Add the found key
2369 array_push($keys, $key);
2377 // Determines database column name from given subject and locked
2378 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2379 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2380 // Default is 'normal' points
2381 $pointsColumn = 'points';
2383 // Which points, locked or normal?
2384 if ($locked === TRUE) {
2385 $pointsColumn = 'locked_points';
2388 // Prepare array for filter
2389 $filterData = array(
2390 'subject' => $subject,
2391 'locked' => $locked,
2392 'column' => $pointsColumn
2396 $filterData = runFilterChain('determine_points_column_name', $filterData);
2398 // Extract column name from array
2399 $pointsColumn = $filterData['column'];
2402 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2403 return $pointsColumn;
2406 // Converts a boolean variable into 'Y' for true and 'N' for false
2407 function convertBooleanToYesNo ($boolean) {
2410 if ($boolean === TRUE) {
2419 // "Translates" 'true' to true and 'false' to false
2420 function convertStringToBoolean ($str) {
2421 // Debug message (to measure how often this function is called)
2422 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2425 if (!isset($GLOBALS[__FUNCTION__][$str])) {
2426 // Trim it lower-case for validation
2427 $strTrimmed = trim(strtolower($str));
2430 if (!in_array($strTrimmed, array('true', 'false'))) {
2432 reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2436 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2440 return $GLOBALS[__FUNCTION__][$str];
2444 * "Makes" a variable in given string parseable, this function will throw an
2445 * error if the first character is not a dollar sign.
2447 * @param $varString String which contains a variable
2448 * @return $return String with added single quotes for better parsing
2450 function makeParseableVariable ($varString) {
2451 // The first character must be a dollar sign
2452 if (substr($varString, 0, 1) != '$') {
2453 // Please report this
2454 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2458 if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2459 // Snap them in, if [,] are there
2460 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2464 return $GLOBALS[__FUNCTION__][$varString];
2467 // "Getter" for random TAN
2468 function getRandomTan () {
2470 return mt_rand(0, 99999);
2473 // Removes any : from subject
2474 function removeDoubleDotFromSubject ($subject) {
2476 $subjectArray = explode(':', $subject);
2477 $subject = $subjectArray[0];
2478 unset($subjectArray);
2484 // Adds a given entry to the database
2485 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2492 // Set POST data generic userid
2493 setPostRequestElement('userid', getMemberId());
2495 // Call inner function
2496 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2498 // Entry has been added?
2499 if ((!ifSqlHasZeroAffectedRows()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2500 // Display success message
2501 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2503 // Display failed message
2504 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2508 // Edit rows by given id numbers
2509 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()) {
2510 // $tableName must be an array
2511 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2512 // No tableName specified
2513 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2514 } elseif (!is_array($idColumn)) {
2515 // $idColumn is no array
2516 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2517 } elseif (!is_array($userIdColumn)) {
2518 // $userIdColumn is no array
2519 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2520 } elseif (!is_array($editNow)) {
2521 // $editNow is no array
2522 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2525 // Shall we change here or list for editing?
2526 if ($editNow[0] === TRUE) {
2527 // Add generic userid field
2528 setPostRequestElement('userid', getMemberId());
2530 // Call generic change method
2531 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2534 if ($affected == countPostSelection($idColumn[0])) {
2536 displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2538 // Some are still there :(
2539 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2543 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2547 // Delete rows by given id numbers
2548 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()) {
2549 // Do this only for members
2552 // $tableName must be an array
2553 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2554 // No tableName specified
2555 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2556 } elseif (!is_array($idColumn)) {
2557 // $idColumn is no array
2558 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2559 } elseif (!is_array($userIdColumn)) {
2560 // $userIdColumn is no array
2561 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2562 } elseif (!is_array($deleteNow)) {
2563 // $deleteNow is no array
2564 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2567 // Shall we delete here or list for deletion?
2568 if ($deleteNow[0] === TRUE) {
2569 // Add generic userid field
2570 setPostRequestElement('userid', getMemberId());
2572 // Call generic function
2573 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2576 if ($affected == countPostSelection($idColumn[0])) {
2578 displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2580 // Some are still there :(
2581 displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), sqlAffectedRows(), countPostSelection($idColumn[0])));
2584 // List for deletion confirmation
2585 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2589 // Build a special template list
2590 // @TODO cacheFiles is not yet supported
2591 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2592 // Do this only for logged in member
2595 // Call inner (general) function
2596 doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2599 // Checks whether given address is IPv4
2600 function isIp4AddressValid ($address) {
2602 if (!isset($GLOBALS[__FUNCTION__][$address])) {
2604 $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);
2608 return $GLOBALS[__FUNCTION__][$address];
2611 // Returns the string if not empty or FALSE if empty
2612 function validateIsEmpty ($str) {
2614 $trimmed = trim($str);
2616 // Is the string empty?
2617 if (empty($trimmed)) {
2626 // "Getter" for seconds from given time unit
2627 function getSecondsFromTimeUnit ($timeUnit) {
2628 // Default is not found
2632 switch ($timeUnit) {
2633 case 's': // Seconds = 1
2637 case 'm': // Minutes
2646 $seconds = 60*60*24;
2650 $seconds = 60*60*24*7;
2653 default: // Unsupported
2654 reportBug(__FUNCTION__, __LINE__, 'Unsupported time unit ' . $timeUnit . ' detected.');
2662 // Calulates value for given seconds and time unit
2663 function caluculateTimeUnitValue ($seconds, $timeUnit) {
2665 return ($seconds / getSecondsFromTimeUnit($timeUnit));
2668 // "Getter" for an array from given one but only one index of it
2669 function getArrayFromArrayIndex ($array, $key) {
2670 // Some simple validation
2671 assert(isset($array[0][$key]));
2674 $newArray = array();
2676 // "Walk" through all elements
2677 foreach ($array as $element) {
2678 $newArray[] = $element[$key];
2686 * Compress given data and encodes it into BASE64 to be stored in database with
2689 * @param $data Data to be compressed and encoded
2690 * @return $data Compressed+encoded data
2692 function compress ($data) {
2694 return base64_encode(gzcompress($data));
2698 * Decompress given data previously compressed with compress().
2700 * @param $data Data compressed with compress()
2701 * @reurn $data Uncompressed data
2703 function decompress ($data) {
2705 return gzuncompress(base64_decode($data));
2709 * Converts given charset in given string to UTF-8 if not UTF-8. This function
2710 * is currently limited to iconv().
2712 * @param $str String to convert charset in
2713 * @param $charset Charset to convert from
2714 * @return $str Converted string
2716 function convertCharsetToUtf8 ($str, $charset) {
2717 // Is iconv() available?
2718 if (!function_exists('iconv')) {
2719 // Please make it sure
2720 reportBug(__FUNCTION__, __LINE__, 'PHP function iconv() is currently required to do charset convertion.');
2723 // Is the charset not UTF-8?
2724 if (strtoupper($charset) != 'UTF-8') {
2725 // Convert it to UTF-8
2726 $str = iconv(strtoupper($charset), 'UTF-8//TRANSLIT', $str);
2729 // Return converted string
2733 // Hash string with SHA256 and encode it to hex
2734 function hashSha256 ($str) {
2736 $hash = mhash(MHASH_SHA256, $str);
2738 // Encode it to hexadecimal
2740 for ($i = 0; $i < strlen($hash); $i++) {
2741 // Encode char to decimal, pad it with zero, add it
2742 $hex .= padLeftZero(dechex(ord(substr($hash, $i, 1))), 2);
2745 // Make sure 'length modulo 2' = 0
2746 assert((strlen($hex) % 2) == 0);
2752 // ----------------------------------------------------------------------------
2753 // "Translatation" functions for points_data table
2754 // ----------------------------------------------------------------------------
2756 // Translates generically some data into a target string
2757 function translateGeneric ($messagePrefix, $data, $messageSuffix = '') {
2758 // Is the method null or empty?
2759 if (is_null($data)) {
2762 } elseif (empty($data)) {
2763 // Is empty (string)
2767 // Default column name is unknown
2768 $return = '{%message,' . $messagePrefix . '_UNKNOWN' . $messageSuffix . '=' . strtoupper($data) . '%}';
2770 // Construct message id
2771 $messageId = $messagePrefix . '_' . strtoupper($data) . $messageSuffix;
2774 if (isMessageIdValid($messageId)) {
2775 // Then use it as message string
2776 $return = '{--' . $messageId . '--}';
2779 // Return the column name
2783 // Translates points subject to human-readable
2784 function translatePointsSubject ($subject) {
2786 $subject = removeDoubleDotFromSubject($subject);
2789 return translateGeneric('POINTS_SUBJECT', $subject);
2792 // "Translates" given points account type
2793 function translatePointsAccountType ($accountType) {
2795 return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2798 // "Translates" given points "locked mode"
2799 function translatePointsLockedMode ($lockedMode) {
2801 return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2804 // "Translates" given points payment method
2805 function translatePointsPaymentMethod ($paymentMethod) {
2807 return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2810 // "Translates" given points account provider
2811 function translatePointsAccountProvider ($accountProvider) {
2813 return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2816 // "Translates" given points notify recipient
2817 function translatePointsNotifyRecipient ($notifyRecipient) {
2819 return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2822 // "Translates" given mode to a human-readable version
2823 function translatePointsMode ($pointsMode) {
2825 return translateGeneric('POINTS_MODE', $pointsMode);
2828 // "Translates" task type to a human-readable version
2829 function translateTaskType ($taskType) {
2831 return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2834 // "Translates" task status to a human-readable version
2835 function translateTaskStatus ($taskStatus) {
2837 return translateGeneric('ADMIN_TASK_STATUS', $taskStatus);
2841 *-----------------------------------------------------------------------------
2842 * Automatically re-created functions, all taken from user comments on
2844 *-----------------------------------------------------------------------------
2846 if (!function_exists('html_entity_decode')) {
2847 // Taken from documentation on www.php.net
2848 function html_entity_decode ($string) {
2849 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2850 $trans_tbl = array_flip($trans_tbl);
2851 return strtr($string, $trans_tbl);
2855 // "Calculates" password strength
2856 function calculatePasswordStrength ($password, $configEntry = 'min_password_length') {
2860 if ((strlen($password) < 1) || (strlen($password) < getConfig($configEntry))) {
2865 // At least 8 chars long?
2866 if (strlen($password) >= 8) {
2871 // At least 10 chars long?
2872 if (strlen($password) >= 10) {
2877 // Lower and upper cases?
2878 if ((preg_match('/[a-z]/', $password)) && (preg_match('/[A-Z]/', $password))) {
2884 if (preg_match('/[0-9]/', $password)) {
2889 // Special characters?
2890 if (preg_match('/.[!,@,#,$,%,^,&,*,?,\/,_,~,+,-,(,)]/', $password)) {
2895 // Return password score
2899 // "Translates" password strength/score
2900 function translatePasswordStrength ($strength) {
2901 // Return it translated
2902 return '{--PASSWORD_SCORE_' . bigintval($strength) . '--}';
2905 // Checks whether given password is strong enough
2906 function isStrongPassword ($password) {
2908 return (calculatePasswordStrength($password) >= getConfig('min_password_score'));
2911 // "Getter" for base path from theme
2912 function getBasePathFromTheme ($theme) {
2913 return sprintf('%stheme/%s/css/', getPath(), $theme);
2916 // Wrapper to check whether given theme is readable
2917 function isThemeReadable ($theme) {
2919 if (!isset($GLOBALS[__FUNCTION__][$theme])) {
2921 $GLOBALS[__FUNCTION__][$theme] = (isIncludeReadable(sprintf('theme/%s/theme.php', $theme)));
2925 return $GLOBALS[__FUNCTION__][$theme];