Fixed handling of SQL strings
[mailer.git] / inc / functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 08/25/2003 *
4  * ===================                          Last change: 11/29/2005 *
5  *                                                                      *
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  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
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                      *
21  *                                                                      *
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.                                  *
26  *                                                                      *
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.                         *
31  *                                                                      *
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,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Init fatal message array
44 function initFatalMessages () {
45         $GLOBALS['fatal_messages'] = array();
46 }
47
48 // Getter for whole fatal error messages
49 function getFatalArray () {
50         return $GLOBALS['fatal_messages'];
51 }
52
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);
61         }
62
63         // Add message to $GLOBALS['fatal_messages']
64         array_push($GLOBALS['fatal_messages'], $message);
65
66         // Log fatal messages away
67         logDebugMessage($file, $line, 'Fatal error message: ' . compileCode($message));
68 }
69
70 // Getter for total fatal message count
71 function getTotalFatalErrors () {
72         // Init count
73         $count = 0;
74
75         // Is there at least the first entry?
76         if (!empty($GLOBALS['fatal_messages'][0])) {
77                 // Get total count
78                 $count = count($GLOBALS['fatal_messages']);
79                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - FROM ARRAY');
80         } // END - if
81
82         // Return value
83         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - EXIT!');
84         return $count;
85 }
86
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
90         if ($length == '0') {
91                 $length = getMinPasswordLength();
92         } // END - if
93
94         // Exclude some entries
95         $localAbc = array_diff($GLOBALS['_abc'], $exclude);
96
97         // $localAbc must have at least 10 entries
98         assert(count($localAbc) >= 10);
99
100         // Start creating password
101         $password = '';
102         while (strlen($password) < $length) {
103                 $password .= $localAbc[mt_rand(0, count($localAbc) -1)];
104         } // END - while
105
106         /*
107          * When the length of the password is below 40 characters additional
108          * security can be added by scrambling it. Otherwise the hash may
109          * corrupted.
110          */
111         if (strlen($password) <= 40) {
112                 // Also scramble the password
113                 $password = scrambleString($password);
114         } // END - if
115
116         // Return the password
117         return $password;
118 }
119
120 // Generates a human-readable timestamp from the Uni* stamp
121 function generateDateTime ($time, $mode = '0') {
122         // Is there cache?
123         if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
124                 // Return it instead
125                 return $GLOBALS[__FUNCTION__][$time][$mode];
126         } // END - if
127
128         // If the stamp is zero it mostly didn't "happen"
129         if (($time == '0') || (is_null($time))) {
130                 // Never happend
131                 return '{--NEVER_HAPPENED--}';
132         } // END - if
133
134         // Filter out numbers
135         $timeSecured = bigintval($time);
136
137         // Detect language
138         switch (getLanguage()) {
139                 case 'de': // German date / time format
140                         switch ($mode) {
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
149                                 default:
150                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
151                                         break;
152                         } // END - switch
153                         break;
154
155                 default: // Default is the US date / time format!
156                         switch ($mode) {
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
165                                 default:
166                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
167                                         break;
168                         } // END - switch
169         } // END - switch
170
171         // Store it in cache
172         $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
173
174         // Return result
175         return $ret;
176 }
177
178 // Translates Y/N to yes/no
179 function translateYesNo ($yn) {
180         // Is it cached?
181         if (!isset($GLOBALS[__FUNCTION__][$yn])) {
182                 // Default
183                 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
184                 switch ($yn) {
185                         case 'Y': // Yes
186                                 $GLOBALS[__FUNCTION__][$yn] = '{--YES--}';
187                                 break;
188
189                         case 'N': // No
190                                 $GLOBALS[__FUNCTION__][$yn] = '{--NO--}';
191                                 break;
192
193                         default: // Log unknown value
194                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $yn));
195                                 break;
196                 } // END - switch
197         } // END - if
198
199         // Return it
200         return $GLOBALS[__FUNCTION__][$yn];
201 }
202
203 // "Translates" Y/N into "de-/active"
204 function translateActivationStatus ($status) {
205         // Is it cached?
206         if (!isset($GLOBALS[__FUNCTION__][$status])) {
207                 // Default
208                 $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')';
209                 switch ($status) {
210                         case 'Y': // Activated
211                                 $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}';
212                                 break;
213
214                         case 'N': // Deactivated
215                                 $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}';
216                                 break;
217
218                         default: // Log unknown value
219                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $status));
220                                 break;
221                 } // END - switch
222         } // END - if
223
224         // Return it
225         return $GLOBALS[__FUNCTION__][$status];
226 }
227
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;
233
234         // Default is 3 you can change this in admin area "Settings -> Misc Options"
235         if (!isConfigEntrySet('max_comma')) {
236                 setConfigEntry('max_comma', 3);
237         } // END - if
238
239         // Use from config is default
240         $maxComma = getConfig('max_comma');
241
242         // Use from parameter?
243         if ($max > 0) {
244                 $maxComma = $max;
245         } // END - if
246
247         // Cut zeros off?
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... ;-)
253                         $maxComma = '0';
254                 } // END - if
255         } // END - if
256
257         // Debug log
258
259         // Translate it now
260         $translated = $dotted;
261         switch (getLanguage()) {
262                 case 'de': // German language
263                         $translated = number_format($dotted, $maxComma, ',', '.');
264                         break;
265
266                 default: // All others
267                         $translated = number_format($dotted, $maxComma, '.', ',');
268                         break;
269         } // END - switch
270
271         // Return translated value
272         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
273         return $translated;
274 }
275
276 // Translate Uni*-like gender to human-readable
277 function translateGender ($gender) {
278         // Default
279         $ret = '!' . $gender . '!';
280
281         // Male/female or company?
282         switch ($gender) {
283                 case 'M': // Male
284                 case 'F': // Female
285                 case 'C': // Company
286                         // Use generic function
287                         $ret = translateGeneric('GENDER', $gender);
288                         break;
289
290                 default:
291                         // Please report bugs on unknown genders
292                         reportBug(__FUNCTION__, __LINE__, sprintf('Unknown gender %s detected.', $gender));
293                         break;
294         } // END - switch
295
296         // Return translated gender
297         return $ret;
298 }
299
300 // "Translates" the user status
301 function translateUserStatus ($status) {
302         // Default status is unknown if something goes through
303         $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
304
305         // Generate message depending on status
306         switch ($status) {
307                 case 'UNCONFIRMED':
308                 case 'CONFIRMED':
309                 case 'LOCKED':
310                         // Use generic function for all "normal" cases
311                         $ret = translateGeneric('ACCOUNT_STATUS', $status);
312                         break;
313
314                 case '': // Account deleted
315                 case NULL: // Account deleted
316                         $ret = '{--ACCOUNT_STATUS_DELETED--}';
317                         break;
318
319                 default: // Please report all unknown status
320                         reportBug(__FUNCTION__, __LINE__, sprintf('Unknown status %s(%s) detected.', $status, gettype($status)));
321                         break;
322         } // END - switch
323
324         // Return it
325         return $ret;
326 }
327
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';
332
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';
337                         break;
338
339                 case 'N': // Is invisible
340                         $content['visible_css'] = $prefix . 'menu_invisible';
341                         break;
342
343                 default: // Please report this
344                         reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
345                         break;
346         } // END - switch
347
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';
352                         break;
353
354                 case 'N': // Is unlocked and visible to members/guests/sponsors
355                         $content['locked_css'] = $prefix . 'menu_unlocked';
356                         break;
357
358                 default: // Please report this
359                         reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
360                         break;
361         } // END - switch
362
363         // Return the resulting array
364         return $content;
365 }
366
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())) {
371                 // Encode URL
372                 $encodedUrl = encodeString(compileUriCode($url));
373
374                 // Generate hash
375                 $hash = generateHash($url . getSiteKey() . getDateKey());
376
377                 // Log plain URL and hash
378                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
379
380                 // De-refer this URL
381                 $url = '{%url=modules.php?module=loader&amp;url=' . $encodedUrl . '&amp;hash=' . encodeHashForCookie($hash) . '&amp;salt=' . substr($hash, 0, getSaltLength()) . '%}';
382         } // END - if
383
384         // Return link
385         return $url;
386 }
387
388 // Generates an URL for the frametester
389 function generateFrametesterUrl ($url) {
390         // Prepare frametester URL
391         $frametesterUrl = sprintf('{%%url=modules.php?module=frametester&amp;url=%s%%}',
392                 encodeString(compileUriCode($url))
393         );
394
395         // Return the new URL
396         return $frametesterUrl;
397 }
398
399 // Count entries from e.g. a selection box
400 function countSelection ($array) {
401         // Integrity check
402         if (!is_array($array)) {
403                 // Not an array!
404                 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
405         } // END - if
406
407         // Init count
408         $ret = '0';
409
410         // Count all entries
411         foreach ($array as $key => $selected) {
412                 // Is it checked?
413                 if (!empty($selected)) {
414                         // Yes, then count it
415                         $ret++;
416                 } // END - if
417         } // END - foreach
418
419         // Return counted selections
420         return $ret;
421 }
422
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);
429
430         // Create timestamp for wished time which depends on extracted date
431         return mktime(
432                 $hours,
433                 $minutes,
434                 $seconds,
435                 $months,
436                 $days,
437                 $years
438         );
439 }
440
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
446                 return;
447         } // END - if
448
449         // Remove {%url=
450         if (substr($url, 0, 6) == '{%url=') {
451                 $url = substr($url, 6, -2);
452         } // END - if
453
454         // Compile out codes
455         eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
456
457         // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
458         $rel = ' rel="external"';
459
460         // Is there internal or external URL?
461         if (substr($url, 0, strlen(getUrl())) == getUrl()) {
462                 // Own (=internal) URL
463                 $rel = '';
464         } // END - if
465
466         // Three different ways to debug...
467         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
468         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
469         //* DEBUG: */ die($url);
470
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('&amp;', '&', $url), FALSE));
475         } else {
476                 // Output error message
477                 loadInclude('inc/header.php');
478                 loadTemplate('redirect_url', FALSE, str_replace('&amp;', '&', $url));
479                 loadInclude('inc/footer.php');
480         }
481
482         // Shut the mailer down here
483         doShutdown();
484 }
485
486 /************************************************************************
487  *                                                                      *
488  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
489  * $a_sort sortiert:                                                    *
490  *                                                                      *
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   *
496  *                                                                      *
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! :-)                           *
500  *                                                                      *
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) {
507                                 $match = FALSE;
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;
515                                 }
516
517                                 if ($match) {
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;
523                                                 unset($t);
524                                         } // END - foreach
525                                 } // END - if
526                         } // END - foreach
527                 } // END - foreach
528
529                 // Count one up
530                 $primary_key++;
531         } // END - while
532
533         // Write back sorted array
534         $array = $temporaryArray;
535 }
536
537
538 //
539 // Deprecated : $length (still has one reference in this function)
540 // Optional   : $extraData
541 //
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();
545
546         // Build key string
547         $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
548         if (isConfigEntrySet('secret_key')) {
549                 $keys .= getEncryptSeparator() . getSecretKey();
550         } // END - if
551         if (isConfigEntrySet('file_hash')) {
552                 $keys .= getEncryptSeparator() . getFileHash();
553         } // END - if
554         $keys .= getEncryptSeparator() . getDateFromRepository();
555         if (isConfigEntrySet('master_salt')) {
556                 $keys .= getEncryptSeparator() . getMasterSalt();
557         } // END - if
558
559         // Build string from misc data
560         $data  = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
561
562         // Add more additional data
563         if (isSessionVariableSet('u_hash')) {
564                 $data .= getEncryptSeparator() . getSession('u_hash');
565         } // END - if
566
567         // Add referral id, language, theme and userid
568         $data .= getEncryptSeparator() . determineReferralId();
569         $data .= getEncryptSeparator() . getLanguage();
570         $data .= getEncryptSeparator() . getCurrentTheme();
571         $data .= getEncryptSeparator() . getMemberId();
572
573         // Calculate number for generating the code
574         $a = $code + getConfig('_ADD') - 1;
575
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());
579         } else {
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()));
582         }
583
584         // Create number from hash
585         $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
586
587         // At least 10 numbers shall be secure enought!
588         if (isExtensionActive('other')) {
589                 $len = getCodeLength();
590         } else {
591                 $len = $length;
592         } // END - if
593
594         // Smaller 1 is not okay
595         if ($len < 1) {
596                 // Fix it to 10
597                 $len = 10;
598         } // END - if
599
600         // Cut off requested counts of number, but skip first digit (which is mostly a zero)
601         $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
602
603         // Done building code
604         return $return;
605 }
606
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);
612
613         // Shall we cast?
614         if ($castValue === TRUE) {
615                 // Cast to biggest numeric type
616                 $ret = (double) $ret;
617         } // END - if
618
619         // Has the whole value changed?
620         if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
621                 // Log the values
622                 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
623         } // END - if
624
625         // Return result
626         //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
627         return $ret;
628 }
629
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']));
634
635         // Initial return value
636         $ret = '0';
637
638         // Is there a leap year?
639         $SWITCH = '0';
640         $TEST   = getYear() / 4;
641         $M1     = getMonth();
642
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();
647         } // END - if
648
649         // First add years...
650         $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
651
652         // Next months...
653         if (isset($postData[$prefix . '_mo'])) {
654                 $ret += $postData[$prefix . '_mo'] * 2628000;
655         } elseif (isset($postData[$prefix . '_mn'])) {
656                 $ret += $postData[$prefix . '_mn'] * 2628000;
657         }
658
659         // Next weeks
660         $ret += $postData[$prefix . '_we'] * 604800;
661
662         // Next days...
663         $ret += $postData[$prefix . '_da'] * 86400;
664
665         // Next hours...
666         $ret += $postData[$prefix . '_ho'] * 3600;
667
668         // Next minutes..
669         $ret += $postData[$prefix . '_mi'] * 60;
670
671         // And at last seconds...
672         $ret += $postData[$prefix . '_se'];
673
674         // Return calculated value
675         return $ret;
676 }
677
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);
682         $ret = '';
683         foreach ($data as $k => $v) {
684                 if ($v > 0) {
685                         // Value is greater than 0 "eval" data to return string
686                         $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
687                         break;
688                 } // END - if
689         } // END - foreach
690
691         // Is something there?
692         if (!empty($ret)) {
693                 // Remove leading commata and space
694                 $ret = substr($ret, 2);
695         } else {
696                 // Zero seconds
697                 $ret = '0 {--TIME_UNIT_SECOND--}';
698         }
699
700         // Return fancy time string
701         return $ret;
702 }
703
704 // Taken from www.php.net isInStringIgnoreCase() user comments
705 function isEmailValid ($email) {
706         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
707
708         // Is there cache?
709         if (!isset($GLOBALS[__FUNCTION__][$email])) {
710                 // Check first part of email address
711                 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
712
713                 //  Check domain
714                 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
715
716                 // Generate pattern
717                 $regex = '@^' . $first . '\@' . $domain . '$@iU';
718
719                 // Determine it
720                 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
721         } // END - if
722
723         // Return check result
724         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
725         return $GLOBALS[__FUNCTION__][$email];
726 }
727
728 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
729 function isUrlValid ($url, $compile = TRUE) {
730         // Trim URL a little
731         $url = trim(urldecode($url));
732         //* DEBUG: */ debugOutput($url);
733
734         // Compile some chars out...
735         if ($compile === TRUE) {
736                 $url = compileUriCode($url, FALSE, FALSE, FALSE);
737         } // END - if
738         //* DEBUG: */ debugOutput($url);
739
740         // Check for the extension filter
741         if (isExtensionActive('filter')) {
742                 // Use the extension's filter set
743                 return FILTER_VALIDATE_URL($url, FALSE);
744         } // END - if
745
746         /*
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.
749          */
750         return isUrlValidSimple($url);
751 }
752
753 // Generate a hash for extra-security for all passwords
754 function generateHash ($plainText, $salt = '', $hash = TRUE) {
755         // Debug output
756         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
757
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) {
763                         // Is plain password
764                         return md5($plainText);
765                 } else {
766                         // Is already a hash
767                         return $plainText;
768                 }
769         } // END - if
770
771         // Is an arry element missing here?
772         if (!isConfigEntrySet('file_hash')) {
773                 // Stop here
774                 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
775         } // END - if
776
777         // When the salt is empty build a new one, else use the first x configured characters as the salt
778         if (empty($salt)) {
779                 // Build server string for more entropy
780                 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
781
782                 // Build key string
783                 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
784
785                 // Is the secret_key config entry set?
786                 if (isConfigEntrySet('secret_key')) {
787                         // Add it
788                         $keys .= getEncryptSeparator() . getSecretKey();
789                 } // END - if
790
791                 // Additional data
792                 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
793
794                 // Calculate number for generating the code
795                 $a = time() + getConfig('_ADD') - 1;
796
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).')');
804
805                 // Generate the password salt string
806                 $salt = substr($sha1, 0, getSaltLength());
807                 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
808         } else {
809                 // Use given salt
810                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
811                 $salt = substr($salt, 0, getSaltLength());
812                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
813
814                 // Sanity check on salt
815                 if (strlen($salt) != getSaltLength()) {
816                         // Not the same!
817                         reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
818                 } // END - if
819         }
820
821         // Generate final hash (for debug output)
822         $finalHash = $salt . sha1($salt . $plainText);
823
824         // Debug output
825         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
826
827         // Return hash
828         return $finalHash;
829 }
830
831 // Scramble a string
832 function scrambleString ($str) {
833         // Init
834         $scrambled = '';
835
836         // Final check, in case of failure it will return unscrambled string
837         if (strlen($str) > 40) {
838                 // The string is to long
839                 return $str;
840         } elseif (strlen($str) == 40) {
841                 // From database
842                 $scrambleNums = explode(':', getPassScramble());
843         } else {
844                 // Generate new numbers
845                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
846         }
847
848         // Assert on both lengths
849         assert(strlen($str) == count($scrambleNums));
850
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);
856
857                 // Add it to final output string
858                 $scrambled .= $char;
859         } // END - for
860
861         // Return scrambled string
862         //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
863         return $scrambled;
864 }
865
866 // De-scramble a string scrambled by scrambleString()
867 function descrambleString ($str) {
868         // Scramble only 40 chars long strings
869         if (strlen($str) != 40) {
870                 return $str;
871         } // END - if
872
873         // Load numbers from config
874         $scrambleNums = explode(':', getPassScramble());
875
876         // Validate numbers
877         if (count($scrambleNums) != 40) {
878                 return $str;
879         } // END - if
880
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);
887         } // END - for
888
889         // Return scrambled string
890         //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
891         return $orig;
892 }
893
894 // Generated a "string" for scrambling
895 function genScrambleString ($len) {
896         // Prepare array for the numbers
897         $scrambleNumbers = array();
898
899         // First we need to setup randomized numbers from 0 to 31
900         for ($idx = 0; $idx < $len; $idx++) {
901                 // Generate number
902                 $rand = mt_rand(0, ($len - 1));
903
904                 // Check for it by creating more numbers
905                 while (array_key_exists($rand, $scrambleNumbers)) {
906                         $rand = mt_rand(0, ($len - 1));
907                 } // END - while
908
909                 // Add number
910                 $scrambleNumbers[$rand] = $rand;
911         } // END - for
912
913         // So let's create the string for storing it in database
914         $scrambleString = implode(':', $scrambleNumbers);
915
916         // Return it
917         return $scrambleString;
918 }
919
920 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
921 function encodeHashForCookie ($passHash) {
922         // Return vanilla password hash
923         $ret = $passHash;
924
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!');
933                         return $ret;
934                 } // END - if
935
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));
942
943                         // Default is hexadecimal of index if both are same
944                         $mod = dechex($idx);
945
946                         // Is part1 larger or part2 than its counter part?
947                         if ($part1 > $part2) {
948                                 // part1 is larger
949                                 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
950                         } elseif ($part2 > $part1) {
951                                 // part2 is larger
952                                 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
953                         }
954
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 . '*');
959                         $start += 2;
960                         $newHash .= $mod;
961                 } // END - for
962
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) . ')');
965                 $ret = $newHash;
966         } // END - if
967
968         // Return result
969         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
970         return $ret;
971 }
972
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, '');
982                         } // END - if
983                 } // END - foreach
984         } // END - if
985 }
986
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')));
991 }
992
993 // Get current theme name
994 function getCurrentTheme () {
995         // The default theme is 'default'... ;-)
996         $ret = 'default';
997
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();
1011         }
1012
1013         // Return theme value
1014         return $ret;
1015 }
1016
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())) {
1021                 // Get user status
1022                 $status = getUserData('status');
1023         } // END - if
1024
1025         // Default error code if unknown account status
1026         $errorCode = getCode('ACCOUNT_UNKNOWN');
1027
1028         // Generate constant name
1029         $codeName = sprintf('ACCOUNT_%s', strtoupper($status));
1030
1031         // Is the constant there?
1032         if (isCodeSet($codeName)) {
1033                 // Then get it!
1034                 $errorCode = getCode($codeName);
1035         } else {
1036                 // Unknown status
1037                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown error status %s detected.', $status));
1038         }
1039
1040         // Return error code
1041         return $errorCode;
1042 }
1043
1044 // Back-ported from the new ship-simu engine. :-)
1045 function debug_get_printable_backtrace () {
1046         // Init variable
1047         $backtrace = '<ol>';
1048
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>';
1056         } // END - foreach
1057
1058         // Close it
1059         $backtrace .= '</ol>';
1060
1061         // Return the backtrace
1062         return $backtrace;
1063 }
1064
1065 // A mail-able backtrace
1066 function debug_get_mailable_backtrace () {
1067         // Init variable
1068         $backtrace = '';
1069
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";
1077         } // END - foreach
1078
1079         // Return the backtrace
1080         return $backtrace;
1081 }
1082
1083 // Generates a ***weak*** seed
1084 function generateSeed () {
1085         return microtime(TRUE) * 100000;
1086 }
1087
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 . '%}';
1092
1093         // Which code is provided?
1094         switch ($code) {
1095                 case '':
1096                         // No error code is bad coding practice
1097                         reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1098                         break;
1099
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;
1134
1135                 case getCode('ERROR_MAILID'):
1136                         if (isExtensionActive('mailid', TRUE)) {
1137                                 $message = '{--ERROR_CONFIRMING_MAIL--}';
1138                         } else {
1139                                 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1140                         }
1141                         break;
1142
1143                 case getCode('EXTENSION_PROBLEM'):
1144                         if (isGetRequestElementSet('ext')) {
1145                                 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1146                         } else {
1147                                 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1148                         }
1149                         break;
1150
1151                 case getCode('URL_TIME_LOCK'):
1152                         // Load timestamp from last order
1153                         $content = getPoolDataFromId(getRequestElement('id'));
1154
1155                         // Translate it for templates
1156                         $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1157
1158                         // Calculate hours...
1159                         $content['hours'] = round(getUrlTlock() / 60 / 60);
1160
1161                         // Minutes...
1162                         $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1163
1164                         // And seconds
1165                         $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1166
1167                         // Finally contruct the message
1168                         $message = loadTemplate('tlock_message', TRUE, $content);
1169                         break;
1170
1171                 default:
1172                         // Log missing/invalid error codes
1173                         logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1174                         break;
1175         } // END - switch
1176
1177         // Return the message
1178         return $message;
1179 }
1180
1181 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1182 function isUrlValidSimple ($url) {
1183         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1184         // Prepare URL
1185         $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1186
1187         // Allows http and https
1188         $http      = "(http|https)+(:\/\/)";
1189         // Test domain
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})?";
1193         // Test IP number
1194         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1195         // ... directory
1196         $dir       = "((/)+([-_\.[:alnum:]])+)*";
1197         // ... page
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;
1225
1226         // Test all patterns
1227         $reg = FALSE;
1228         foreach ($pattern as $key => $pat) {
1229                 // Debug regex?
1230                 if (isDebugRegularExpressionEnabled()) {
1231                         // @TODO Are these convertions still required?
1232                         $pat = str_replace('.', '&#92;&#46;', $pat);
1233                         $pat = str_replace('@', '&#92;&#64;', $pat);
1234                         //* DEBUG: */ debugOutput($key . '=&nbsp;' . $pat);
1235                 } // END - if
1236
1237                 // Check if expression matches
1238                 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1239
1240                 // Does it match?
1241                 if ($reg === TRUE) {
1242                         break;
1243                 } // END - if
1244         } // END - foreach
1245
1246         // Return true/false
1247         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1248         return $reg;
1249 }
1250
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
1255         $done = FALSE;
1256         $seek++;
1257         $next  = -1;
1258         $found = FALSE;
1259
1260         // Is the file there and read-/write-able?
1261         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1262                 $search = 'CFG: ' . $comment;
1263                 $tmp = $FQFN . '.tmp';
1264
1265                 // Open the source file
1266                 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1267
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);
1272
1273                         // Is the resource again valid?
1274                         if (is_resource($fp_tmp)) {
1275                                 // Mark temporary file as readable
1276                                 $GLOBALS['file_readable'][$tmp] = TRUE;
1277
1278                                 // Start reading
1279                                 while (!feof($fp)) {
1280                                         // Read from source file
1281                                         $line = fgets($fp, 1024);
1282
1283                                         if (isInString($search, $line)) {
1284                                                 $next = '0';
1285                                                 $found = TRUE;
1286                                         } // END - if
1287
1288                                         if ($next > -1) {
1289                                                 if ($next === $seek) {
1290                                                         $next = -1;
1291                                                         $line = $prefix . $inserted . $suffix . PHP_EOL;
1292                                                 } else {
1293                                                         $next++;
1294                                                 }
1295                                         } // END - if
1296
1297                                         // Write to temp file
1298                                         fwrite($fp_tmp, $line);
1299                                 } // END - while
1300
1301                                 // Close temp file
1302                                 fclose($fp_tmp);
1303
1304                                 // Finished writing tmp file
1305                                 $done = TRUE;
1306                         } // END - if
1307
1308                         // Close source file
1309                         fclose($fp);
1310
1311                         if (($done === TRUE) && ($found === TRUE)) {
1312                                 // Copy back temporary->FQFN file and ...
1313                                 copyFileVerified($tmp, $FQFN, 0644);
1314
1315                                 // ... delete temporay file :-)
1316                                 return removeFile($tmp);
1317                         } elseif ($found === FALSE) {
1318                                 // Entry not found
1319                                 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!');
1320                         } else {
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!');
1323                         }
1324                 }
1325         } else {
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);
1328         }
1329
1330         // An error was detected!
1331         return FALSE;
1332 }
1333
1334 // Debug message logger
1335 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1336         // Is debug mode enabled?
1337         if ((isDebugModeEnabled()) || ($force === TRUE)) {
1338                 // Remove CRLF
1339                 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1340
1341                 // Log this message away
1342                 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1343         } // END - if
1344 }
1345
1346 // Handle extra values
1347 function handleExtraValues ($filterFunction, $value, $extraValue) {
1348         // Default is the value itself
1349         $ret = $value;
1350
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);
1355         } // END - if
1356
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);
1361
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);
1366                 } // END - if
1367
1368                 // Call the multi-parameter call-back
1369                 $ret = call_user_func_array($filterFunction, $args);
1370
1371                 // Is $ret 'true'?
1372                 if ($ret === TRUE) {
1373                         // Test passed, so write direct value
1374                         $ret = $args;
1375                 } // END - if
1376         } else {
1377                 // One parameter call
1378                 $ret = call_user_func($filterFunction, $value);
1379                 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1380
1381                 // Is $ret 'true'?
1382                 if ($ret === TRUE) {
1383                         // Test passed, so write direct value
1384                         $ret = $value;
1385                 } // END - if
1386         }
1387
1388         // Return the value
1389         return $ret;
1390 }
1391
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()) {
1396                 // Debug message
1397                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1398         } // END - if
1399
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()) {
1407                         // Then log it
1408                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1409                 } // END - if
1410
1411                 // Filter function + extra value set
1412                 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1413
1414                 // Debug mode enabled?
1415                 if (isDebugModeEnabled()) {
1416                         // Then log it
1417                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1418                 } // END - if
1419         } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1420                 // Debug mode enabled?
1421                 if (isDebugModeEnabled()) {
1422                         // Then log it
1423                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1424                 } // END - if
1425
1426                 // Handle extra values
1427                 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1428
1429                 // Debug mode enabled?
1430                 if (isDebugModeEnabled()) {
1431                         // Then log it
1432                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1433                 } // END - if
1434
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()) {
1440                         // Then log it
1441                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1442                 } // END - if
1443
1444                 // Handle extra values
1445                 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1446
1447                 // Debug mode enabled?
1448                 if (isDebugModeEnabled()) {
1449                         // Then log it
1450                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1451                 } // END - if
1452
1453                 // Make sure entries is not bool, then something went wrong
1454                 assert(!is_bool($entries));
1455         }
1456
1457         // Return value
1458         return $entries;
1459 }
1460
1461 // Converts timestamp selections into a timestamp
1462 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1463         // Init test variable
1464         $skip  = FALSE;
1465         $test2 = '';
1466
1467         // Get last three chars
1468         $test = substr($id, -3);
1469
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;
1479
1480                         // Remove data from array
1481                         foreach (array('ye', 'mo', 'mn', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1482                                 unset($postData[$test . '_' . $rem]);
1483                         } // END - foreach
1484
1485                         // Skip adding
1486                         unset($id);
1487                         $skip = TRUE;
1488                         $test2 = $test;
1489                 } // END - if
1490         } // END - if
1491 }
1492
1493 // Reverts the german decimal comma into Computer decimal dot
1494 // OPPOMENT: translateComma()
1495 function convertCommaToDot ($str) {
1496         // Default float is not a float... ;-)
1497         $float = FALSE;
1498
1499         // Which language is selected?
1500         switch (getLanguage()) {
1501                 case 'de': // German language
1502                         // Remove german thousand dots first
1503                         $str = str_replace('.', '', $str);
1504
1505                         // Replace german commata with decimal dot and cast it
1506                         $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str));
1507                         break;
1508
1509                 default: // US and so on
1510                         // Remove thousand commatas first and cast
1511                         $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str));
1512                         break;
1513         } // END - switch
1514
1515         // Return float
1516         return $float;
1517 }
1518
1519 // Handle menu-depending failed logins and return the rendered content
1520 function handleLoginFailures ($accessLevel) {
1521         // Default output is empty ;-)
1522         $OUT = '';
1523
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 />');
1530                         $content = array(
1531                                 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1532                                 'last_failure'   => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1533                         );
1534
1535                         // Load template
1536                         $OUT = loadTemplate('login_failures', TRUE, $content);
1537                 } // END - if
1538
1539                 // Reset session data
1540                 setSession('mailer_' . $accessLevel . '_failures', '');
1541                 setSession('mailer_' . $accessLevel . '_last_failure', '');
1542         } // END - if
1543
1544         // Return rendered content
1545         return $OUT;
1546 }
1547
1548 // Rebuild cache
1549 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1550         // Debug message
1551         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1552
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)) {
1558                         // Destroy it
1559                         $GLOBALS['cache_instance']->removeCacheFile($force);
1560                 } // END - if
1561
1562                 // Include file given?
1563                 if (!empty($inc)) {
1564                         // Construct FQFN
1565                         $inc = sprintf('inc/loader/load-%s.php', $inc);
1566
1567                         // Is the include there?
1568                         if (isIncludeReadable($inc)) {
1569                                 // And rebuild it from scratch
1570                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1571                                 loadInclude($inc);
1572                         } else {
1573                                 // Include not found, which needs now tracing
1574                                 reportBug(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1575                         }
1576                 } // END - if
1577         } // END - if
1578 }
1579
1580 // Determines the real remote address
1581 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1582         // Default is 127.0.0.1
1583         $address = '127.0.0.1';
1584
1585         // Is a proxy in use?
1586         if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1587                 // Proxy was used
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'];
1595         }
1596
1597         // This strips out the real address from proxy output
1598         if (strstr($address, ',')) {
1599                 $addressArray = explode(',', $address);
1600                 $address = $addressArray[0];
1601         } // END - if
1602
1603         // Return the result
1604         return $address;
1605 }
1606
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'];
1613         } // END - if
1614
1615         // Generate receiver list
1616         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1617
1618         // Receivers added?
1619         if (!empty($receiver)) {
1620                 // Add bonus mail to queue
1621                 addBonusMailToQueue(
1622                         $data['subject'],
1623                         $data['text'],
1624                         $receiver,
1625                         $data['points'],
1626                         $data['seconds'],
1627                         $data['url'],
1628                         $data['cat'],
1629                         $mode,
1630                         $data['receiver']
1631                 );
1632
1633                 // Mail inserted into bonus pool
1634                 if ($output === TRUE) {
1635                         displayMessage('{--ADMIN_BONUS_SEND--}');
1636                 } // END - if
1637         } elseif ($output === TRUE) {
1638                 // More entered than can be reached!
1639                 displayMessage('{--ADMIN_MORE_SELECTED--}');
1640         } else {
1641                 // Debug log
1642                 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1643         }
1644 }
1645
1646 // Enables the hourly reset mode and runs it
1647 function doHourly () {
1648         // Enable the hourly reset mode
1649         $GLOBALS['hourly_enabled'] = TRUE;
1650
1651         // Run filters (one always!)
1652         runFilterChain('hourly');
1653
1654         // Do not update in hourly debug mode
1655         if ((!isConfigEntrySet('DEBUG_HOURLY')) || (!isDebugHourlyEnabled())) {
1656                 // Update database
1657                 updateConfiguration('last_hourly', getHour());
1658         } // END - if
1659 }
1660
1661 // Enables the daily reset mode and runs it
1662 function doDaily () {
1663         // Enable the reset mode
1664         $GLOBALS['daily_enabled'] = TRUE;
1665
1666         // Run filters
1667         runFilterChain('daily');
1668
1669         // Do not update in daily debug mode
1670         if ((!isConfigEntrySet('DEBUG_DAILY')) || (!isDebugDailyEnabled())) {
1671                 // Update database
1672                 updateConfiguration('last_daily', getDay());
1673         } // END - if
1674 }
1675
1676 // Enables the weekly reset mode and runs it
1677 function doWeekly () {
1678         // Enable the reset mode
1679         $GLOBALS['weekly_enabled'] = TRUE;
1680
1681         // Run filters
1682         runFilterChain('weekly');
1683
1684         // Do not update in weekly debug mode
1685         if ((!isConfigEntrySet('DEBUG_WEEKLY')) || (!isDebugWeeklyEnabled())) {
1686                 // Update database
1687                 updateConfiguration('last_weekly', getWeek());
1688         } // END - if
1689 }
1690
1691 // Enables the monthly reset mode and runs it
1692 function doMonthly () {
1693         // Enable the reset mode
1694         $GLOBALS['monthly_enabled'] = TRUE;
1695
1696         // Run filters
1697         runFilterChain('monthly');
1698
1699         // Do not update in monthly debug mode
1700         if ((!isConfigEntrySet('DEBUG_MONTHLY')) || (!isDebugMonthlyEnabled())) {
1701                 // Update database
1702                 updateConfiguration('last_monthly', getMonth());
1703         } // END - if
1704 }
1705
1706 // Enables the yearly reset mode and runs it
1707 function doYearly () {
1708         // Enable the reset mode
1709         $GLOBALS['yearly_enabled'] = TRUE;
1710
1711         // Run filters
1712         runFilterChain('yearly');
1713
1714         // Do not update in yearly debug mode
1715         if ((!isConfigEntrySet('DEBUG_YEARLY')) || (!isDebugYearlyEnabled())) {
1716                 // Update database
1717                 updateConfiguration('last_yearly', getYear());
1718         } // END - if
1719 }
1720
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);
1725
1726         // Check if link is up
1727         if (isSqlLinkUp()) {
1728                 // Close link
1729                 sqlCloseLink(__FUNCTION__, __LINE__);
1730         } elseif (!isInstaller()) {
1731                 // No database link
1732                 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1733         }
1734
1735         // Stop executing here
1736         exit;
1737 }
1738
1739 // Init member id
1740 function initMemberId () {
1741         $GLOBALS['member_id'] = '0';
1742 }
1743
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.');
1749         } // END - if
1750
1751         // Set it secured
1752         $GLOBALS['member_id'] = bigintval($memberId);
1753 }
1754
1755 // Getter for member id or returns zero
1756 function getMemberId () {
1757         // Default member id
1758         $memberId = '0';
1759
1760         // Is the member id set?
1761         if (isMemberIdSet()) {
1762                 // Then use it
1763                 $memberId = $GLOBALS['member_id'];
1764         } // END - if
1765
1766         // Return it
1767         return $memberId;
1768 }
1769
1770 // Checks ether the member id is set
1771 function isMemberIdSet () {
1772         return (isset($GLOBALS['member_id']));
1773 }
1774
1775 // Setter for extra title
1776 function setExtraTitle ($extraTitle) {
1777         $GLOBALS['extra_title'] = $extraTitle;
1778 }
1779
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!');
1786         } // END - if
1787
1788         // Return it
1789         return $GLOBALS['extra_title'];
1790 }
1791
1792 // Checks if the extra title is set
1793 function isExtraTitleSet () {
1794         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1795 }
1796
1797 /**
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.
1801  *
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
1813  */
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');
1817
1818         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1819         // Init found includes
1820         $foundMatches = array();
1821
1822         // Open directory
1823         $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1824
1825         // Read all entries
1826         while ($baseFile = readdir($dirPointer)) {
1827                 // Exclude '.', '..' and entries in $excludeArray automatically
1828                 if (in_array($baseFile, $excludeArray, TRUE))  {
1829                         // Exclude them
1830                         //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1831                         continue;
1832                 } // END - if
1833
1834                 // Construct include filename and FQFN
1835                 $fileName = $baseDir . $baseFile;
1836                 $FQFN = getPath() . $fileName;
1837
1838                 // Remove double slashes
1839                 $FQFN = str_replace('//', '/', $FQFN);
1840
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))) {
1843                         // Debug message
1844                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1845
1846                         // Exclude this one
1847                         continue;
1848                 } // END - if
1849
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));
1854
1855                         // And skip further processing
1856                         continue;
1857                 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1858                         // Skip this file
1859                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1860                         continue;
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);
1864                         continue;
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) . ')!');
1871                         continue;
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!');
1875                         continue;
1876                 }
1877
1878                 // Get file' extension (last 4 chars)
1879                 $fileExtension = substr($baseFile, -4, 4);
1880
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);
1888
1889                                 // Add file with or without base path
1890                                 if ($addBaseDir === TRUE) {
1891                                         // With base path
1892                                         array_push($foundMatches, $fileName);
1893                                 } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1894                                         // No prefix/suffix
1895                                         array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1896                                 } else {
1897                                         // No base path
1898                                         array_push($foundMatches, $baseFile);
1899                                 }
1900                         } else {
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 . ')');
1903                         }
1904                 } elseif ((($fileExtension == $extension) || (empty($extension))) && (isFileReadable($FQFN))) {
1905                         // Other, generic file found
1906                         if ($addBaseDir === TRUE) {
1907                                 // With base path
1908                                 array_push($foundMatches, $fileName);
1909                         } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1910                                 // No prefix/suffix
1911                                 array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1912                         } else {
1913                                 // No base path
1914                                 array_push($foundMatches, $baseFile);
1915                         }
1916                 }
1917         } // END - while
1918
1919         // Close directory
1920         closedir($dirPointer);
1921
1922         // Sort array
1923         sort($foundMatches);
1924
1925         // Return array with include files
1926         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1927         return $foundMatches;
1928 }
1929
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);
1934 }
1935
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';
1942                         break;
1943
1944                 case 'login': // ... and 'login' the member's menu
1945                         $moduleName = 'member';
1946                         break;
1947                 // Anything else will not be mapped, silently.
1948         } // END - switch
1949
1950         // Return result
1951         return $moduleName;
1952 }
1953
1954 // Add SQL debug data to array for later output
1955 function addSqlToDebug ($result, $sqlString, $timing, $file, $line) {
1956         // Is there cache?
1957         if (!isset($GLOBALS['debug_sql_available'])) {
1958                 // Check it and cache it in $GLOBALS
1959                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1960         } // END - if
1961
1962         // Don't execute anything here if we don't need or ext-other is missing
1963         if ($GLOBALS['debug_sql_available'] === FALSE) {
1964                 return;
1965         } // END - if
1966
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
1970                 return;
1971         } // END - if
1972
1973         // Remeber this as profiled (or not, but we don't care here)
1974         $GLOBALS['debug_sqls'][$file][$line][$sqlString] = TRUE;
1975
1976         // Generate record
1977         $record = array(
1978                 'num_rows' => sqlNumRows($result),
1979                 'affected' => sqlAffectedRows(),
1980                 'sql_str'  => $sqlString,
1981                 'timing'   => $timing,
1982                 'file'     => basename($file),
1983                 'line'     => $line
1984         );
1985
1986         // Add it
1987         array_push($GLOBALS['debug_sqls'], $record);
1988 }
1989
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']));
1996         } // END - if
1997
1998         // Load include for CacheSystem class
1999         loadIncludeOnce('inc/classes/cachesystem.class.php');
2000
2001         // Initialize cache system only when it's needed
2002         $GLOBALS['cache_instance'] = new CacheSystem();
2003
2004         // Did it work?
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());
2008         } // END - if
2009 }
2010
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];
2017         } else {
2018                 // ... else use default message
2019                 $ret = $message;
2020         }
2021
2022         // Return result
2023         return $ret;
2024 }
2025
2026 // Convert ';' to ', ' for e.g. receiver list
2027 function convertReceivers ($old) {
2028         return str_replace(';', ', ', $old);
2029 }
2030
2031 // Get a module from filename and access level
2032 function getModuleFromFileName ($file, $accessLevel) {
2033         // Default is 'invalid';
2034         $modCheck = 'invalid';
2035
2036         // @TODO This is still very static, rewrite it somehow
2037         switch ($accessLevel) {
2038                 case 'admin':
2039                         $modCheck = 'admin';
2040                         break;
2041
2042                 case 'sponsor':
2043                 case 'guest':
2044                 case 'member':
2045                         $modCheck = getModule();
2046                         break;
2047
2048                 default: // Unsupported file name / access level
2049                         reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2050                         break;
2051         } // END - switch
2052
2053         // Return result
2054         return $modCheck;
2055 }
2056
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
2062                 return $url;
2063         } // END - if
2064
2065         // Is there a valid session?
2066         if ((!isValidSession()) && (!isSpider())) {
2067                 // Determine right separator
2068                 $separator = '&amp;';
2069                 if (!isInString('?', $url)) {
2070                         // No question mark
2071                         $separator = '?';
2072                 } // END - if
2073
2074                 // Then add it to URL
2075                 $url .= $separator . session_name() . '=' . session_id();
2076         } // END - if
2077
2078         // Add {?URL?} ?
2079         if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2080                 // Add it
2081                 $url = '{?URL?}/' . $url;
2082         } // END - if
2083
2084         // Debug message
2085         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
2086
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');
2093         } // END - if
2094
2095         // Debug log
2096         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
2097
2098         // Return the encoded URL
2099         return $url;
2100 }
2101
2102 // Simple check for spider
2103 function isSpider () {
2104         // Get the UA and trim it down
2105         $userAgent = trim(detectUserAgent(TRUE));
2106
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
2110                 return FALSE;
2111         } // END - if
2112
2113         // Is it a spider?
2114         return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2115 }
2116
2117 // Function to search for the last modified file
2118 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2119         // Get dir as array
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)$@';
2124
2125         $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2126         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2127
2128         // Walk through all entries
2129         foreach ($ds as $d) {
2130                 // Generate proper FQFN
2131                 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2132
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);
2139
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;
2146                         } // END - if
2147                 } else {
2148                         // Not readable
2149                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2150                 }
2151         } // END - foreach
2152 }
2153
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) == '[]') {
2158                 /*
2159                  * Try to find one and replace it. I do it this way to allow easy
2160                  * extending of this code.
2161                  */
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])) {
2166                                 // Insert it
2167                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2168
2169                                 // And abort
2170                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2171                                 break;
2172                         } // END - if
2173                 } // END - foreach
2174         } // END - if
2175
2176         // Return it
2177         return $field;
2178 }
2179
2180 // Converts a zero or NULL to word 'NULL'
2181 function convertZeroToNull ($number) {
2182         // Is it a valid username?
2183         if (isValidNumber($number)) {
2184                 // Always secure it
2185                 $number = bigintval($number);
2186         } else {
2187                 // Is not valid or zero
2188                 $number = 'NULL';
2189         }
2190
2191         // Return it
2192         return $number;
2193 }
2194
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
2200                 $number = '0';
2201         } // END - if
2202
2203         // Return it
2204         return $number;
2205 }
2206
2207 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2208 // Note: This function is cached
2209 function capitalizeUnderscoreString ($str) {
2210         // Is there cache?
2211         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2212                 // Init target string
2213                 $capitalized = '';
2214
2215                 // Explode it with the underscore, but rewrite dashes to underscore before
2216                 $strArray = explode('_', str_replace('-', '_', $str));
2217
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);
2222                 } // END - foreach
2223
2224                 // Store the converted string in cache array
2225                 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2226         } // END - if
2227
2228         // Return cache
2229         return $GLOBALS[__FUNCTION__][$str];
2230 }
2231
2232 // Generate admin links for mail order
2233 // mailType can be: 'normal' or 'bonus'
2234 function generateAdminMailLinks ($mailType, $mailId) {
2235         // Init variables
2236         $OUT = '';
2237         $table = '';
2238
2239         // Default column for mail status is 'data_type'
2240         // @TODO Rename column data_type to e.g. mail_status
2241         $statusColumn = 'data_type';
2242
2243         // Which mail do we have?
2244         switch ($mailType) {
2245                 case 'bonus': // Bonus mail
2246                         $table = 'bonus';
2247                         break;
2248
2249                 case 'normal': // Member mail
2250                         $table = 'pool';
2251                         break;
2252
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>';
2256                         break;
2257         } // END - switch
2258
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",
2263                         array(
2264                                 $statusColumn,
2265                                 $table,
2266                                 bigintval($mailId)
2267                         ), __FILE__, __LINE__);
2268
2269                 // Is there one entry there?
2270                 if (sqlNumRows($result) == 1) {
2271                         // Load the entry
2272                         $content = sqlFetchArray($result);
2273
2274                         // Add output and type
2275                         $content['type']     = $mailType;
2276                         $content['__output'] = '';
2277
2278                         // Filter all data
2279                         $content = runFilterChain('generate_admin_mail_links', $content);
2280
2281                         // Get output back
2282                         $OUT = $content['__output'];
2283                 } // END - if
2284
2285                 // Free result
2286                 sqlFreeResult($result);
2287         } // END - if
2288
2289         // Return generated HTML code
2290         return $OUT;
2291 }
2292
2293
2294 /**
2295  * Determine if a string can represent a number in hexadecimal
2296  *
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
2301  */
2302 function isHexadecimal ($hex) {
2303         // Make it lowercase
2304         $hex = strtolower(trim(ltrim($hex, '0')));
2305
2306         // Fix empty strings to zero
2307         if (empty($hex)) {
2308                 $hex = 0;
2309         } // END - if
2310
2311         // Simply compare decode->encode result with original
2312         return ($hex == dechex(hexdec($hex)));
2313 }
2314
2315 /**
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.
2319  *
2320  * @param       $str    String to overwork
2321  * @return      $str    Overworked string
2322  */
2323 function replaceReturnNewLine ($str) {
2324         return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2325 }
2326
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) {
2330         // Init array
2331         $strArray = array();
2332
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);
2337         } // END - foreach
2338
2339         // Return array
2340         return $strArray;
2341 }
2342
2343 // Detects the prefix 'mb_' if a multi-byte string is given
2344 function detectMultiBytePrefix ($str) {
2345         // Default is without multi-byte
2346         $mbPrefix = '';
2347
2348         // Detect multi-byte (strictly)
2349         if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2350                 // With multi-byte encoded string
2351                 $mbPrefix = 'mb_';
2352         } // END - if
2353
2354         // Return the prefix
2355         return $mbPrefix;
2356 }
2357
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
2361         $keys = array();
2362
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);
2370                 } // END - if
2371         } // END - foreach
2372
2373         // Return the array
2374         return $keys;
2375 }
2376
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';
2382
2383         // Which points, locked or normal?
2384         if ($locked === TRUE) {
2385                 $pointsColumn = 'locked_points';
2386         } // END - if
2387
2388         // Prepare array for filter
2389         $filterData = array(
2390                 'subject' => $subject,
2391                 'locked'  => $locked,
2392                 'column'  => $pointsColumn
2393         );
2394
2395         // Run the filter
2396         $filterData = runFilterChain('determine_points_column_name', $filterData);
2397
2398         // Extract column name from array
2399         $pointsColumn = $filterData['column'];
2400
2401         // Return it
2402         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2403         return $pointsColumn;
2404 }
2405
2406 // Converts a boolean variable into 'Y' for true and 'N' for false
2407 function convertBooleanToYesNo ($boolean) {
2408         // Default is 'N'
2409         $converted = 'N';
2410         if ($boolean === TRUE) {
2411                 // Set 'Y'
2412                 $converted = 'Y';
2413         } // END - if
2414
2415         // Return it
2416         return $converted;
2417 }
2418
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);
2423
2424         // Is there cache?
2425         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2426                 // Trim it lower-case for validation
2427                 $strTrimmed = trim(strtolower($str));
2428
2429                 // Is it valid?
2430                 if (!in_array($strTrimmed, array('true', 'false'))) {
2431                         // Not valid!
2432                         reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2433                 } // END - if
2434
2435                 // Determine it
2436                 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2437         } // END - if
2438
2439         // Return cache
2440         return $GLOBALS[__FUNCTION__][$str];
2441 }
2442
2443 /**
2444  * "Makes" a variable in given string parseable, this function will throw an
2445  * error if the first character is not a dollar sign.
2446  *
2447  * @param       $varString      String which contains a variable
2448  * @return      $return         String with added single quotes for better parsing
2449  */
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.');
2455         } // END - if
2456
2457         // Is there cache?
2458         if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2459                 // Snap them in, if [,] are there
2460                 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2461         } // END - if
2462
2463         // Return cache
2464         return $GLOBALS[__FUNCTION__][$varString];
2465 }
2466
2467 // "Getter" for random TAN
2468 function getRandomTan () {
2469         // Generate one
2470         return mt_rand(0, 99999);
2471 }
2472
2473 // Removes any : from subject
2474 function removeDoubleDotFromSubject ($subject) {
2475         // Remove it
2476         $subjectArray = explode(':', $subject);
2477         $subject = $subjectArray[0];
2478         unset($subjectArray);
2479
2480         // Return it
2481         return $subject;
2482 }
2483
2484 // Adds a given entry to the database
2485 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2486         // Is it a member?
2487         if (!isMember()) {
2488                 // Then abort here
2489                 return FALSE;
2490         } // END - if
2491
2492         // Set POST data generic userid
2493         setPostRequestElement('userid', getMemberId());
2494
2495         // Call inner function
2496         doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2497
2498         // Entry has been added?
2499         if ((!ifSqlHasZeroAffectedRows()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2500                 // Display success message
2501                 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2502         } else {
2503                 // Display failed message
2504                 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2505         }
2506 }
2507
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);
2523         } // END - if
2524
2525         // Shall we change here or list for editing?
2526         if ($editNow[0] === TRUE) {
2527                 // Add generic userid field
2528                 setPostRequestElement('userid', getMemberId());
2529
2530                 // Call generic change method
2531                 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2532
2533                 // Was this fine?
2534                 if ($affected == countPostSelection($idColumn[0])) {
2535                         // All deleted
2536                         displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2537                 } else {
2538                         // Some are still there :(
2539                         displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2540                 }
2541         } else {
2542                 // List for editing
2543                 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2544         }
2545 }
2546
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
2550         assert(isMember());
2551
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);
2565         } // END - if
2566
2567         // Shall we delete here or list for deletion?
2568         if ($deleteNow[0] === TRUE) {
2569                 // Add generic userid field
2570                 setPostRequestElement('userid', getMemberId());
2571
2572                 // Call generic function
2573                 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2574
2575                 // Was this fine?
2576                 if ($affected == countPostSelection($idColumn[0])) {
2577                         // All deleted
2578                         displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2579                 } else {
2580                         // Some are still there :(
2581                         displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), sqlAffectedRows(), countPostSelection($idColumn[0])));
2582                 }
2583         } else {
2584                 // List for deletion confirmation
2585                 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2586         }
2587 }
2588
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
2593         assert(isMember());
2594
2595         // Call inner (general) function
2596         doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2597 }
2598
2599 // Checks whether given address is IPv4
2600 function isIp4AddressValid ($address) {
2601         // Is there cache?
2602         if (!isset($GLOBALS[__FUNCTION__][$address])) {
2603                 // Determine it ...
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);
2605         } // END - if
2606
2607         // Return cache
2608         return $GLOBALS[__FUNCTION__][$address];
2609 }
2610
2611 // Returns the string if not empty or FALSE if empty
2612 function validateIsEmpty ($str) {
2613         // Trim it
2614         $trimmed = trim($str);
2615
2616         // Is the string empty?
2617         if (empty($trimmed)) {
2618                 // Then set FALSE
2619                 $str = FALSE;
2620         } // END - if
2621
2622         // Return it
2623         return $str;
2624 }
2625
2626 // "Getter" for seconds from given time unit
2627 function getSecondsFromTimeUnit ($timeUnit) {
2628         // Default is not found
2629         $seconds = NULL;
2630
2631         // "Detect" it
2632         switch ($timeUnit) {
2633                 case 's': // Seconds = 1
2634                         $seconds = 1;
2635                         break;
2636
2637                 case 'm': // Minutes
2638                         $seconds = 60;
2639                         break;
2640
2641                 case 'h': // Hours
2642                         $seconds = 60*60;
2643                         break;
2644
2645                 case 'D': // Days
2646                         $seconds = 60*60*24;
2647                         break;
2648
2649                 case 'W': // Weeks
2650                         $seconds = 60*60*24*7;
2651                         break;
2652
2653                 default: // Unsupported
2654                         reportBug(__FUNCTION__, __LINE__, 'Unsupported time unit ' . $timeUnit . ' detected.');
2655                         break;
2656         } // END - switch
2657
2658         // Return value
2659         return $seconds;
2660 }
2661
2662 // Calulates value for given seconds and time unit
2663 function caluculateTimeUnitValue ($seconds, $timeUnit) {
2664         // Calculate it
2665         return ($seconds / getSecondsFromTimeUnit($timeUnit));
2666 }
2667
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]));
2672
2673         // Init new array
2674         $newArray = array();
2675
2676         // "Walk" through all elements
2677         foreach ($array as $element) {
2678                 $newArray[] = $element[$key];
2679         } // END - if
2680
2681         // Return it
2682         return $newArray;
2683 }
2684
2685 /**
2686  * Compress given data and encodes it into BASE64 to be stored in database with
2687  * sqlQueryEscaped()
2688  *
2689  * @param       $data   Data to be compressed and encoded
2690  * @return      $data   Compressed+encoded data
2691  */
2692 function compress ($data) {
2693         // Compress it
2694         return base64_encode(gzcompress($data));
2695 }
2696
2697 /**
2698  * Decompress given data previously compressed with compress().
2699  *
2700  * @param       $data   Data compressed with compress()
2701  * @reurn       $data   Uncompressed data
2702  */
2703 function decompress ($data) {
2704         // Decompress it
2705         return gzuncompress(base64_decode($data));
2706 }
2707
2708 /**
2709  * Converts given charset in given string to UTF-8 if not UTF-8. This function
2710  * is currently limited to iconv().
2711  *
2712  * @param       $str            String to convert charset in
2713  * @param       $charset        Charset to convert from
2714  * @return      $str            Converted string
2715  */
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.');
2721         } // END - if
2722
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);
2727         } // END - if
2728
2729         // Return converted string
2730         return $str;
2731 }
2732
2733 // Hash string with SHA256 and encode it to hex
2734 function hashSha256 ($str) {
2735         /// Hash string
2736         $hash = mhash(MHASH_SHA256, $str);
2737
2738         // Encode it to hexadecimal
2739         $hex = '';
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);
2743         } // END - if
2744
2745         // Make sure 'length modulo 2' = 0
2746         assert((strlen($hex) % 2) == 0);
2747
2748         // Return it
2749         return $hex;
2750 }
2751
2752 // ----------------------------------------------------------------------------
2753 //              "Translatation" functions for points_data table
2754 // ----------------------------------------------------------------------------
2755
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)) {
2760                 // Is NULL
2761                 $data = 'NULL';
2762         } elseif (empty($data)) {
2763                 // Is empty (string)
2764                 $data = 'EMPTY';
2765         } // END - if
2766
2767         // Default column name is unknown
2768         $return = '{%message,' . $messagePrefix . '_UNKNOWN' . $messageSuffix . '=' . strtoupper($data) . '%}';
2769
2770         // Construct message id
2771         $messageId = $messagePrefix . '_' . strtoupper($data) . $messageSuffix;
2772
2773         // Is it there?
2774         if (isMessageIdValid($messageId)) {
2775                 // Then use it as message string
2776                 $return = '{--' . $messageId . '--}';
2777         } // END - if
2778
2779         // Return the column name
2780         return $return;
2781 }
2782
2783 // Translates points subject to human-readable
2784 function translatePointsSubject ($subject) {
2785         // Remove any :x
2786         $subject = removeDoubleDotFromSubject($subject);
2787
2788         // Return it
2789         return translateGeneric('POINTS_SUBJECT', $subject);
2790 }
2791
2792 // "Translates" given points account type
2793 function translatePointsAccountType ($accountType) {
2794         // Return it
2795         return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2796 }
2797
2798 // "Translates" given points "locked mode"
2799 function translatePointsLockedMode ($lockedMode) {
2800         // Return it
2801         return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2802 }
2803
2804 // "Translates" given points payment method
2805 function translatePointsPaymentMethod ($paymentMethod) {
2806         // Return it
2807         return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2808 }
2809
2810 // "Translates" given points account provider
2811 function translatePointsAccountProvider ($accountProvider) {
2812         // Return it
2813         return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2814 }
2815
2816 // "Translates" given points notify recipient
2817 function translatePointsNotifyRecipient ($notifyRecipient) {
2818         // Return it
2819         return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2820 }
2821
2822 // "Translates" given mode to a human-readable version
2823 function translatePointsMode ($pointsMode) {
2824         // Return it
2825         return translateGeneric('POINTS_MODE', $pointsMode);
2826 }
2827
2828 // "Translates" task type to a human-readable version
2829 function translateTaskType ($taskType) {
2830         // Return it
2831         return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2832 }
2833
2834 // "Translates" task status to a human-readable version
2835 function translateTaskStatus ($taskStatus) {
2836         // Return it
2837         return translateGeneric('ADMIN_TASK_STATUS', $taskStatus);
2838 }
2839
2840 /*
2841  *-----------------------------------------------------------------------------
2842  * Automatically re-created functions, all taken from user comments on
2843  * www.php.net
2844  *-----------------------------------------------------------------------------
2845  */
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);
2852         }
2853 } // END - if
2854
2855 // "Calculates" password strength
2856 function calculatePasswordStrength ($password, $configEntry = 'min_password_length') {
2857         // Default score
2858         $score = 1;
2859
2860         if ((strlen($password) < 1) || (strlen($password) < getConfig($configEntry))) {
2861                 // Is to weak
2862                 return 0;
2863         } // END - if
2864
2865         // At least 8 chars long?
2866         if (strlen($password) >= 8) {
2867                 // Add score
2868                 $score++;
2869         } // END - if
2870
2871         // At least 10 chars long?
2872         if (strlen($password) >= 10) {
2873                 // Add score
2874                 $score++;
2875         } // END - if
2876
2877         // Lower and upper cases?
2878         if ((preg_match('/[a-z]/', $password)) && (preg_match('/[A-Z]/', $password))) {
2879                 // Add score
2880                 $score++;
2881         } // END - if
2882
2883         // Also numbers?
2884         if (preg_match('/[0-9]/', $password))  {
2885                 // Add score
2886                 $score++;
2887         } // END - if
2888
2889         // Special characters?
2890         if (preg_match('/.[!,@,#,$,%,^,&,*,?,\/,_,~,+,-,(,)]/', $password)) {
2891                 // Add score
2892                 $score++;
2893         } // END - if
2894
2895         // Return password score
2896         return $score;
2897 }
2898
2899 // "Translates" password strength/score
2900 function translatePasswordStrength ($strength) {
2901         // Return it translated
2902         return '{--PASSWORD_SCORE_' . bigintval($strength) . '--}';
2903 }
2904
2905 // Checks whether given password is strong enough
2906 function isStrongPassword ($password) {
2907         // Determine it
2908         return (calculatePasswordStrength($password) >= getConfig('min_password_score'));
2909 }
2910
2911 // "Getter" for base path from theme
2912 function getBasePathFromTheme ($theme) {
2913         return sprintf('%stheme/%s/css/', getPath(), $theme);
2914 }
2915
2916 // Wrapper to check whether given theme is readable
2917 function isThemeReadable ($theme) {
2918         // Is there cache?
2919         if (!isset($GLOBALS[__FUNCTION__][$theme])) {
2920                 // Determine it
2921                 $GLOBALS[__FUNCTION__][$theme] = (isIncludeReadable(sprintf('theme/%s/theme.php', $theme)));
2922         } // END - if
2923
2924         // Return cache
2925         return $GLOBALS[__FUNCTION__][$theme];
2926 }
2927
2928 // [EOF]
2929 ?>