Some fixes for password scrambling.
[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  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
14  * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
15  * For more information visit: http://mxchange.org                      *
16  *                                                                      *
17  * This program is free software; you can redistribute it and/or modify *
18  * it under the terms of the GNU General Public License as published by *
19  * the Free Software Foundation; either version 2 of the License, or    *
20  * (at your option) any later version.                                  *
21  *                                                                      *
22  * This program is distributed in the hope that it will be useful,      *
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
25  * GNU General Public License for more details.                         *
26  *                                                                      *
27  * You should have received a copy of the GNU General Public License    *
28  * along with this program; if not, write to the Free Software          *
29  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
30  * MA  02110-1301  USA                                                  *
31  ************************************************************************/
32
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
35         die();
36 } // END - if
37
38 // Init fatal message array
39 function initFatalMessages () {
40         $GLOBALS['fatal_messages'] = array();
41 }
42
43 // Getter for whole fatal error messages
44 function getFatalArray () {
45         return $GLOBALS['fatal_messages'];
46 }
47
48 // Add a fatal error message to the queue array
49 function addFatalMessage ($file, $line, $message, $extra = '') {
50         if (is_array($extra)) {
51                 // Multiple extras for a message with masks
52                 $message = call_user_func_array('sprintf', $extra);
53         } elseif (!empty($extra)) {
54                 // $message is text with a mask plus extras to insert into the text
55                 $message = sprintf($message, $extra);
56         }
57
58         // Add message to $GLOBALS['fatal_messages']
59         array_push($GLOBALS['fatal_messages'], $message);
60
61         // Log fatal messages away
62         logDebugMessage($file, $line, 'Fatal error message: ' . compileCode($message));
63 }
64
65 // Getter for total fatal message count
66 function getTotalFatalErrors () {
67         // Init count
68         $count = 0;
69
70         // Is there at least the first entry?
71         if (!empty($GLOBALS['fatal_messages'][0])) {
72                 // Get total count
73                 $count = count($GLOBALS['fatal_messages']);
74                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - FROM ARRAY');
75         } // END - if
76
77         // Return value
78         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - EXIT!');
79         return $count;
80 }
81
82 // Generate a password in a specified length or use default password length
83 function generatePassword ($length = '0', $exclude = array()) {
84         // Auto-fix invalid length of zero
85         if ($length == '0') {
86                 $length = getMinPasswordLength();
87         } // END - if
88
89         // Exclude some entries
90         $localAbc = array_diff($GLOBALS['_abc'], $exclude);
91
92         // $localAbc must have at least 10 entries
93         assert(count($localAbc) >= 10);
94
95         // Start creating password
96         $password = '';
97         while (strlen($password) < $length) {
98                 $password .= $localAbc[mt_rand(0, count($localAbc) -1)];
99         } // END - while
100
101         /*
102          * When the length of the password is below 40 characters additional
103          * security can be added by scrambling it. Otherwise the hash may
104          * corrupted.
105          */
106         if (strlen($password) <= 40) {
107                 // Also scramble the password
108                 $password = scrambleString($password);
109         } // END - if
110
111         // Return the password
112         return $password;
113 }
114
115 // Generates a human-readable timestamp from the Uni* stamp
116 function generateDateTime ($time, $mode = '0') {
117         // Is there cache?
118         if (isset($GLOBALS[__FUNCTION__][$time][$mode])) {
119                 // Return it instead
120                 return $GLOBALS[__FUNCTION__][$time][$mode];
121         } // END - if
122
123         // If the stamp is zero it mostly didn't "happen"
124         if (($time == '0') || (is_null($time))) {
125                 // Never happend
126                 return '{--NEVER_HAPPENED--}';
127         } // END - if
128
129         // Filter out numbers
130         $timeSecured = bigintval($time);
131
132         // Detect language
133         switch (getLanguage()) {
134                 case 'de': // German date / time format
135                         switch ($mode) {
136                                 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break;
137                                 case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break;
138                                 case '2': $ret = date('d.m.Y|H:i', $timeSecured); break;
139                                 case '3': $ret = date('d.m.Y', $timeSecured); break;
140                                 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
141                                 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
142                                 case '6': $ret = date('Ymd', $timeSecured); break;
143                                 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
144                                 default:
145                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
146                                         break;
147                         } // END - switch
148                         break;
149
150                 default: // Default is the US date / time format!
151                         switch ($mode) {
152                                 case '0': $ret = date('r', $timeSecured); break;
153                                 case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break;
154                                 case '2': $ret = date('y-m-d|H:i', $timeSecured); break;
155                                 case '3': $ret = date('y-m-d', $timeSecured); break;
156                                 case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break;
157                                 case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break;
158                                 case '6': $ret = date('Ymd', $timeSecured); break;
159                                 case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP
160                                 default:
161                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf('Invalid date mode %s detected.', $mode));
162                                         break;
163                         } // END - switch
164         } // END - switch
165
166         // Store it in cache
167         $GLOBALS[__FUNCTION__][$time][$mode] = $ret;
168
169         // Return result
170         return $ret;
171 }
172
173 // Translates Y/N to yes/no
174 function translateYesNo ($yn) {
175         // Is it cached?
176         if (!isset($GLOBALS[__FUNCTION__][$yn])) {
177                 // Default
178                 $GLOBALS[__FUNCTION__][$yn] = '??? (' . $yn . ')';
179                 switch ($yn) {
180                         case 'Y': // Yes
181                                 $GLOBALS[__FUNCTION__][$yn] = '{--YES--}';
182                                 break;
183
184                         case 'N': // No
185                                 $GLOBALS[__FUNCTION__][$yn] = '{--NO--}';
186                                 break;
187
188                         default: // Log unknown value
189                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $yn));
190                                 break;
191                 } // END - switch
192         } // END - if
193
194         // Return it
195         return $GLOBALS[__FUNCTION__][$yn];
196 }
197
198 // "Translates" Y/N into "de-/active"
199 function translateActivationStatus ($status) {
200         // Is it cached?
201         if (!isset($GLOBALS[__FUNCTION__][$status])) {
202                 // Default
203                 $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')';
204                 switch ($status) {
205                         case 'Y': // Activated
206                                 $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}';
207                                 break;
208
209                         case 'N': // Deactivated
210                                 $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}';
211                                 break;
212
213                         default: // Log unknown value
214                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown value %s. Expected: Y/N', $status));
215                                 break;
216                 } // END - switch
217         } // END - if
218
219         // Return it
220         return $GLOBALS[__FUNCTION__][$status];
221 }
222
223 // Translates the american decimal dot into a german comma
224 // OPPOMENT: convertCommaToDot()
225 function translateComma ($dotted, $cut = TRUE, $max = '0') {
226         // First, cast all to double, due to PHP changes
227         $dotted = (double) $dotted;
228
229         // Default is 3 you can change this in admin area "Settings -> Misc Options"
230         if (!isConfigEntrySet('max_comma')) {
231                 setConfigEntry('max_comma', 3);
232         } // END - if
233
234         // Use from config is default
235         $maxComma = getConfig('max_comma');
236
237         // Use from parameter?
238         if ($max > 0) {
239                 $maxComma = $max;
240         } // END - if
241
242         // Cut zeros off?
243         if (($cut === TRUE) && ($max == '0')) {
244                 // Test for commata if in cut-mode
245                 $com = explode('.', $dotted);
246                 if (count($com) < 2) {
247                         // Don't display commatas even if there are none... ;-)
248                         $maxComma = '0';
249                 } // END - if
250         } // END - if
251
252         // Debug log
253
254         // Translate it now
255         $translated = $dotted;
256         switch (getLanguage()) {
257                 case 'de': // German language
258                         $translated = number_format($dotted, $maxComma, ',', '.');
259                         break;
260
261                 default: // All others
262                         $translated = number_format($dotted, $maxComma, '.', ',');
263                         break;
264         } // END - switch
265
266         // Return translated value
267         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dotted=' . $dotted . ',translated=' . $translated . ',maxComma=' . $maxComma);
268         return $translated;
269 }
270
271 // Translate Uni*-like gender to human-readable
272 function translateGender ($gender) {
273         // Default
274         $ret = '!' . $gender . '!';
275
276         // Male/female or company?
277         switch ($gender) {
278                 case 'M': // Male
279                 case 'F': // Female
280                 case 'C': // Company
281                         // Use generic function
282                         $ret = translateGeneric('GENDER', $gender);
283                         break;
284
285                 default:
286                         // Please report bugs on unknown genders
287                         reportBug(__FUNCTION__, __LINE__, sprintf('Unknown gender %s detected.', $gender));
288                         break;
289         } // END - switch
290
291         // Return translated gender
292         return $ret;
293 }
294
295 // "Translates" the user status
296 function translateUserStatus ($status) {
297         // Default status is unknown if something goes through
298         $ret = '{--ACCOUNT_STATUS_UNKNOWN--}';
299
300         // Generate message depending on status
301         switch ($status) {
302                 case 'UNCONFIRMED':
303                 case 'CONFIRMED':
304                 case 'LOCKED':
305                         // Use generic function for all "normal" cases
306                         $ret = translateGeneric('ACCOUNT_STATUS', $status);
307                         break;
308
309                 case '': // Account deleted
310                 case NULL: // Account deleted
311                         $ret = '{--ACCOUNT_STATUS_DELETED--}';
312                         break;
313
314                 default: // Please report all unknown status
315                         reportBug(__FUNCTION__, __LINE__, sprintf('Unknown status %s(%s) detected.', $status, gettype($status)));
316                         break;
317         } // END - switch
318
319         // Return it
320         return $ret;
321 }
322
323 // "Translates" 'visible' and 'locked' to a CSS class
324 function translateMenuVisibleLocked ($content, $prefix = '') {
325         // Default is 'menu_unknown'
326         $content['visible_css'] = $prefix . 'menu_unknown';
327
328         // Translate 'visible' and keep an eye on the prefix
329         switch ($content['visible']) {
330                 case 'Y': // Should be visible
331                         $content['visible_css'] = $prefix . 'menu_visible';
332                         break;
333
334                 case 'N': // Is invisible
335                         $content['visible_css'] = $prefix . 'menu_invisible';
336                         break;
337
338                 default: // Please report this
339                         reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
340                         break;
341         } // END - switch
342
343         // Translate 'locked' and keep an eye on the prefix
344         switch ($content['locked']) {
345                 case 'Y': // Should be locked, only admins can call this
346                         $content['locked_css'] = $prefix . 'menu_locked';
347                         break;
348
349                 case 'N': // Is unlocked and visible to members/guests/sponsors
350                         $content['locked_css'] = $prefix . 'menu_unlocked';
351                         break;
352
353                 default: // Please report this
354                         reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=<pre>' . print_r($content, TRUE) . '</pre>');
355                         break;
356         } // END - switch
357
358         // Return the resulting array
359         return $content;
360 }
361
362 // Generates an URL for the dereferer
363 function generateDereferrerUrl ($url) {
364         // Don't de-refer our own links!
365         if ((!empty($url)) && (substr($url, 0, strlen(getUrl())) != getUrl())) {
366                 // Encode URL
367                 $encodedUrl = encodeString(compileUriCode($url));
368
369                 // Generate hash
370                 $hash = generateHash($url . getSiteKey() . getDateKey());
371
372                 // Log plain URL and hash
373                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',hash=' . $hash . '(' . strlen($hash) . ')');
374
375                 // De-refer this URL
376                 $url = '{%url=modules.php?module=loader&amp;url=' . $encodedUrl . '&amp;hash=' . encodeHashForCookie($hash) . '&amp;salt=' . substr($hash, 0, getSaltLength()) . '%}';
377         } // END - if
378
379         // Return link
380         return $url;
381 }
382
383 // Generates an URL for the frametester
384 function generateFrametesterUrl ($url) {
385         // Prepare frametester URL
386         $frametesterUrl = sprintf('{%%url=modules.php?module=frametester&amp;url=%s%%}',
387                 encodeString(compileUriCode($url))
388         );
389
390         // Return the new URL
391         return $frametesterUrl;
392 }
393
394 // Count entries from e.g. a selection box
395 function countSelection ($array) {
396         // Integrity check
397         if (!is_array($array)) {
398                 // Not an array!
399                 reportBug(__FUNCTION__, __LINE__, 'No array provided.');
400         } // END - if
401
402         // Init count
403         $ret = '0';
404
405         // Count all entries
406         foreach ($array as $key => $selected) {
407                 // Is it checked?
408                 if (!empty($selected)) {
409                         // Yes, then count it
410                         $ret++;
411                 } // END - if
412         } // END - foreach
413
414         // Return counted selections
415         return $ret;
416 }
417
418 // Generates a timestamp (some wrapper for mktime())
419 function makeTime ($hours, $minutes, $seconds, $stamp) {
420         // Extract day, month and year from given timestamp
421         $days   = getDay($stamp);
422         $months = getMonth($stamp);
423         $years  = getYear($stamp);
424
425         // Create timestamp for wished time which depends on extracted date
426         return mktime(
427                 $hours,
428                 $minutes,
429                 $seconds,
430                 $months,
431                 $days,
432                 $years
433         );
434 }
435
436 // Redirects to an URL and if neccessarry extends it with own base URL
437 function redirectToUrl ($url, $allowSpider = TRUE) {
438         // Is the output mode -2?
439         if (isAjaxOutputMode()) {
440                 // This is always (!) an AJAX request and shall not be redirected
441                 return;
442         } // END - if
443
444         // Remove {%url=
445         if (substr($url, 0, 6) == '{%url=') {
446                 $url = substr($url, 6, -2);
447         } // END - if
448
449         // Compile out codes
450         eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
451
452         // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
453         $rel = ' rel="external"';
454
455         // Is there internal or external URL?
456         if (substr($url, 0, strlen(getUrl())) == getUrl()) {
457                 // Own (=internal) URL
458                 $rel = '';
459         } // END - if
460
461         // Three different ways to debug...
462         //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'URL=' . $url);
463         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
464         //* DEBUG: */ die($url);
465
466         // We should not sent a redirect if headers are already sent
467         if (!headers_sent()) {
468                 // Load URL when headers are not sent
469                 sendRawRedirect(doFinalCompilation(str_replace('&amp;', '&', $url), FALSE));
470         } else {
471                 // Output error message
472                 loadPageHeader();
473                 loadTemplate('redirect_url', FALSE, str_replace('&amp;', '&', $url));
474                 loadPageFooter();
475         }
476
477         // Shut the mailer down here
478         doShutdown();
479 }
480
481 /************************************************************************
482  *                                                                      *
483  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
484  * $a_sort sortiert:                                                    *
485  *                                                                      *
486  * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
487  * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben    *
488  * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird  *
489  * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a             *
490  * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren   *
491  *                                                                      *
492  * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array    *
493  * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
494  * Sie, dass es doch nicht so schwer ist! :-)                           *
495  *                                                                      *
496  ************************************************************************/
497 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) {
498         $temporaryArray = $array;
499         while ($primary_key < count($a_sort)) {
500                 foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) {
501                         foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) {
502                                 $match = FALSE;
503                                 if ($nums === FALSE) {
504                                         // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
505                                         if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE;
506                                 } elseif ($key != $key2) {
507                                         // Sort numbers (E.g.: 9 < 10)
508                                         if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
509                                         if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order ==  1)) $match = TRUE;
510                                 }
511
512                                 if ($match) {
513                                         // We have found two different values, so let's sort whole array
514                                         foreach ($temporaryArray as $sort_key => $sort_val) {
515                                                 $t                       = $temporaryArray[$sort_key][$key];
516                                                 $temporaryArray[$sort_key][$key]  = $temporaryArray[$sort_key][$key2];
517                                                 $temporaryArray[$sort_key][$key2] = $t;
518                                                 unset($t);
519                                         } // END - foreach
520                                 } // END - if
521                         } // END - foreach
522                 } // END - foreach
523
524                 // Count one up
525                 $primary_key++;
526         } // END - while
527
528         // Write back sorted array
529         $array = $temporaryArray;
530 }
531
532
533 //
534 // Deprecated : $length (still has one reference in this function)
535 // Optional   : $extraData
536 //
537 function generateRandomCode ($length, $code, $userid, $extraData = '') {
538         // Build server string
539         $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
540
541         // Build key string
542         $keys = getSiteKey() . getEncryptSeparator() . getDateKey();
543         if (isConfigEntrySet('secret_key')) {
544                 $keys .= getEncryptSeparator() . getSecretKey();
545         } // END - if
546         if (isConfigEntrySet('file_hash')) {
547                 $keys .= getEncryptSeparator() . getFileHash();
548         } // END - if
549
550         if (isConfigEntrySet('master_salt')) {
551                 $keys .= getEncryptSeparator() . getMasterSalt();
552         } // END - if
553
554         // Build string from misc data
555         $data  = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData;
556
557         // Add more additional data
558         if (isSessionVariableSet('u_hash')) {
559                 $data .= getEncryptSeparator() . getSession('u_hash');
560         } // END - if
561
562         // Add referral id, language, theme and userid
563         $data .= getEncryptSeparator() . determineReferralId();
564         $data .= getEncryptSeparator() . getLanguage();
565         $data .= getEncryptSeparator() . getCurrentTheme();
566         $data .= getEncryptSeparator() . getMemberId();
567
568         // Calculate number for generating the code
569         $a = $code + getConfig('_ADD') - 1;
570
571         if (isConfigEntrySet('master_salt')) {
572                 // Generate hash with master salt from modula of number with the prime number and other data
573                 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt());
574         } else {
575                 // Generate hash with "hash of site key" from modula of number with the prime number and other data
576                 $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength()));
577         }
578
579         // Create number from hash
580         $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi();
581
582         // At least 10 numbers shall be secure enought!
583         if (isExtensionActive('other')) {
584                 $len = getCodeLength();
585         } else {
586                 $len = $length;
587         } // END - if
588
589         // Smaller 1 is not okay
590         if ($len < 1) {
591                 // Fix it to 10
592                 $len = 10;
593         } // END - if
594
595         // Cut off requested counts of number, but skip first digit (which is mostly a zero)
596         $return = substr($rcode, (strpos($rcode, '.') + 1), $len);
597
598         // Done building code
599         return $return;
600 }
601
602 // Does only allow numbers
603 function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) {
604         //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!');
605         // Filter all non-number chars out, so only number chars will remain
606         $ret = preg_replace('/[^0123456789]/', '', $num);
607
608         // Shall we cast?
609         if ($castValue === TRUE) {
610                 // Cast to biggest numeric type
611                 $ret = (double) $ret;
612         } // END - if
613
614         // Has the whole value changed?
615         if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) {
616                 // Log the values
617                 reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num);
618         } // END - if
619
620         // Return result
621         //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!');
622         return $ret;
623 }
624
625 // Creates a Uni* timestamp from given selection data and prefix
626 function createEpocheTimeFromSelections ($prefix, $postData) {
627         // Assert on typical array element (maybe all?)
628         assert(isset($postData[$prefix . '_ye']));
629
630         // Initial return value
631         $ret = '0';
632
633         // Is there a leap year?
634         $SWITCH = '0';
635         $TEST   = getYear() / 4;
636         $M1     = getMonth();
637
638         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
639         // 01     2     2         1    1           1    123     4                          43    3                                 32    233    4                          43    3                                 3210
640         if ((floor($TEST) == $TEST) && ($M1 == '02') && (((isset($postData[$prefix . '_mo'])) && ($postData[$prefix . '_mo'] > '02')) || ((isset($postData[$prefix . '_mn'])) && ($postData[$prefix . '_mn'] > '02')))) {
641                 $SWITCH = getOneDay();
642         } // END - if
643
644         // First add years...
645         $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
646
647         // Next months...
648         if (isset($postData[$prefix . '_mo'])) {
649                 $ret += $postData[$prefix . '_mo'] * 2628000;
650         } elseif (isset($postData[$prefix . '_mn'])) {
651                 $ret += $postData[$prefix . '_mn'] * 2628000;
652         }
653
654         // Next weeks
655         $ret += $postData[$prefix . '_we'] * 604800;
656
657         // Next days...
658         $ret += $postData[$prefix . '_da'] * 86400;
659
660         // Next hours...
661         $ret += $postData[$prefix . '_ho'] * 3600;
662
663         // Next minutes..
664         $ret += $postData[$prefix . '_mi'] * 60;
665
666         // And at last seconds...
667         $ret += $postData[$prefix . '_se'];
668
669         // Return calculated value
670         return $ret;
671 }
672
673 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
674 function createFancyTime ($stamp) {
675         // Get data array with years/months/weeks/days/...
676         $data = createTimeSelections($stamp, '', '', '', TRUE);
677         $ret = '';
678         foreach ($data as $k => $v) {
679                 if ($v > 0) {
680                         // Value is greater than 0 "eval" data to return string
681                         $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
682                         break;
683                 } // END - if
684         } // END - foreach
685
686         // Is something there?
687         if (!empty($ret)) {
688                 // Remove leading commata and space
689                 $ret = substr($ret, 2);
690         } else {
691                 // Zero seconds
692                 $ret = '0 {--TIME_UNIT_SECOND--}';
693         }
694
695         // Return fancy time string
696         return $ret;
697 }
698
699 // Taken from www.php.net isInStringIgnoreCase() user comments
700 function isEmailValid ($email) {
701         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
702
703         // Is there cache?
704         if (!isset($GLOBALS[__FUNCTION__][$email])) {
705                 // Check first part of email address
706                 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
707
708                 //  Check domain
709                 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
710
711                 // Generate pattern
712                 $regex = '@^' . $first . '\@' . $domain . '$@iU';
713
714                 // Determine it
715                 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
716         } // END - if
717
718         // Return check result
719         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
720         return $GLOBALS[__FUNCTION__][$email];
721 }
722
723 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
724 function isUrlValid ($url, $compile = TRUE) {
725         // Trim URL a little
726         $url = trim(urldecode($url));
727         //* DEBUG: */ debugOutput($url);
728
729         // Compile some chars out...
730         if ($compile === TRUE) {
731                 $url = compileUriCode($url, FALSE, FALSE, FALSE);
732         } // END - if
733         //* DEBUG: */ debugOutput($url);
734
735         // Check for the extension filter
736         if (isExtensionActive('filter')) {
737                 // Use the extension's filter set
738                 return FILTER_VALIDATE_URL($url, FALSE);
739         } // END - if
740
741         /*
742          * If not installed, perform a simple test. Just make it sure there is always a
743          * http:// or https:// in front of the URLs.
744          */
745         return isUrlValidSimple($url);
746 }
747
748 // Generate a hash for extra-security for all passwords
749 function generateHash ($plainText, $salt = '', $hash = TRUE) {
750         // Debug output
751         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
752
753         // Is the required extension 'sql_patches' there and a salt is not given?
754         // 123                            4                      43    3     4     432    2                  3             32    2                             3                32    2      3     3      21
755         if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
756                 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
757                 if ($hash === TRUE) {
758                         // Is plain password
759                         return md5($plainText);
760                 } else {
761                         // Is already a hash
762                         return $plainText;
763                 }
764         } // END - if
765
766         // Is an arry element missing here?
767         if (!isConfigEntrySet('file_hash')) {
768                 // Stop here
769                 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
770         } // END - if
771
772         // When the salt is empty build a new one, else use the first x configured characters as the salt
773         if (empty($salt)) {
774                 // Build server string for more entropy
775                 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
776
777                 // Build key string
778                 $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getMasterSalt();
779
780                 // Is the secret_key config entry set?
781                 if (isConfigEntrySet('secret_key')) {
782                         // Add it
783                         $keys .= getEncryptSeparator() . getSecretKey();
784                 } // END - if
785
786                 // Additional data
787                 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
788
789                 // Calculate number for generating the code
790                 $a = time() + getConfig('_ADD') - 1;
791
792                 // Generate SHA1 sum from modula of number and the prime number
793                 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
794                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
795                 $sha1 = scrambleString($sha1);
796                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
797                 //* DEBUG: */ $sha1b = descrambleString($sha1);
798                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
799
800                 // Generate the password salt string
801                 $salt = substr($sha1, 0, getSaltLength());
802                 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
803         } else {
804                 // Use given salt
805                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
806                 $salt = substr($salt, 0, getSaltLength());
807                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
808
809                 // Sanity check on salt
810                 if (strlen($salt) != getSaltLength()) {
811                         // Not the same!
812                         reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
813                 } // END - if
814         }
815
816         // Generate final hash (for debug output)
817         $finalHash = $salt . sha1($salt . $plainText);
818
819         // Debug output
820         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
821
822         // Return hash
823         return $finalHash;
824 }
825
826 // Scramble a string
827 function scrambleString ($str) {
828         // Init
829         $scrambled = '';
830
831         // Final check, in case of failure it will return unscrambled string
832         if (strlen($str) > 40) {
833                 // The string is to long
834                 return $str;
835         } elseif ((strlen($str) == 40) && (getPassScramble() != '')) {
836                 // From database
837                 $scramble = getPassScramble();
838         } else {
839                 // Generate new numbers
840                 $scramble = genScrambleString(strlen($str));
841         }
842
843         // Convert it into an array
844         $scrambleNums = explode(':', $scramble);
845
846         // Assert on both lengths
847         assert(strlen($str) == count($scrambleNums));
848
849         // Scramble string here
850         //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
851         for ($idx = 0; $idx < strlen($str); $idx++) {
852                 // Get char on scrambled position
853                 $char = substr($str, $scrambleNums[$idx], 1);
854
855                 // Add it to final output string
856                 $scrambled .= $char;
857         } // END - for
858
859         // Return scrambled string
860         //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
861         return $scrambled;
862 }
863
864 // De-scramble a string scrambled by scrambleString()
865 function descrambleString ($str) {
866         // Scramble only 40 chars long strings
867         if (strlen($str) != 40) {
868                 return $str;
869         } // END - if
870
871         // Load numbers from config
872         $scrambleNums = explode(':', getPassScramble());
873
874         // Validate numbers
875         if (count($scrambleNums) != 40) {
876                 return $str;
877         } // END - if
878
879         // Begin descrambling
880         $orig = str_repeat(' ', 40);
881         //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
882         for ($idx = 0; $idx < 40; $idx++) {
883                 $char = substr($str, $idx, 1);
884                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
885         } // END - for
886
887         // Return scrambled string
888         //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
889         return $orig;
890 }
891
892 // Generated a "string" for scrambling
893 function genScrambleString ($len) {
894         // Prepare array for the numbers
895         $scrambleNumbers = array();
896
897         // First we need to setup randomized numbers from 0 to 31
898         for ($idx = 0; $idx < $len; $idx++) {
899                 // Generate number
900                 $rand = mt_rand(0, ($len - 1));
901
902                 // Check for it by creating more numbers
903                 while (array_key_exists($rand, $scrambleNumbers)) {
904                         $rand = mt_rand(0, ($len - 1));
905                 } // END - while
906
907                 // Add number
908                 $scrambleNumbers[$rand] = $rand;
909         } // END - for
910
911         // So let's create the string for storing it in database
912         $scrambleString = implode(':', $scrambleNumbers);
913
914         // Return it
915         return $scrambleString;
916 }
917
918 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
919 function encodeHashForCookie ($passHash) {
920         // Return vanilla password hash
921         $ret = $passHash;
922
923         // Is a secret key and master salt already initialized?
924         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
925         if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
926                 // Only calculate when the secret key is generated
927                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
928                 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
929                         // Both keys must have same length so return unencrypted
930                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 -  EXIT!');
931                         return $ret;
932                 } // END - if
933
934                 $newHash = ''; $start = 9;
935                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
936                 for ($idx = 0; $idx < 20; $idx++) {
937                         // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
938                         $part1 = hexdec(substr($passHash     , $start, 2));
939                         $part2 = hexdec(substr(getSecretKey(), $start, 2));
940
941                         // Default is hexadecimal of index if both are same
942                         $mod = dechex($idx);
943
944                         // Is part1 larger or part2 than its counter part?
945                         if ($part1 > $part2) {
946                                 // part1 is larger
947                                 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
948                         } elseif ($part2 > $part1) {
949                                 // part2 is larger
950                                 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
951                         }
952
953                         $mod = substr($mod, 0, 2);
954                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
955                         $mod = padLeftZero($mod, 2);
956                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
957                         $start += 2;
958                         $newHash .= $mod;
959                 } // END - for
960
961                 // Just copy it over, as the master salt is not really helpful here
962                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
963                 $ret = $newHash;
964         } // END - if
965
966         // Return result
967         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
968         return $ret;
969 }
970
971 // Fix "deleted" cookies
972 function fixDeletedCookies ($cookies) {
973         // Is this an array with entries?
974         if (isFilledArray($cookies)) {
975                 // Then check all cookies if they are marked as deleted!
976                 foreach ($cookies as $cookieName) {
977                         // Is the cookie set to "deleted"?
978                         if (getSession($cookieName) == 'deleted') {
979                                 setSession($cookieName, '');
980                         } // END - if
981                 } // END - foreach
982         } // END - if
983 }
984
985 // Checks if a given apache module is loaded
986 function isApacheModuleLoaded ($apacheModule) {
987         // Check it and return result
988         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
989 }
990
991 // Get current theme name
992 function getCurrentTheme () {
993         // The default theme is 'default'... ;-)
994         $ret = 'default';
995
996         // Is there ext-theme installed and active or is 'theme' in URL or POST data?
997         if (isExtensionActive('theme')) {
998                 // Call inner method
999                 $ret = getActualTheme();
1000         } elseif ((isPostRequestElementSet('theme')) && (isThemeReadable(postRequestElement('theme')))) {
1001                 // Use value from POST data
1002                 $ret = postRequestElement('theme');
1003         } elseif ((isGetRequestElementSet('theme')) && (isThemeReadable(getRequestElement('theme')))) {
1004                 // Use value from GET data
1005                 $ret = getRequestElement('theme');
1006         } elseif ((isMailerThemeSet()) && (isThemeReadable(getMailerTheme()))) {
1007                 // Use value from GET data
1008                 $ret = getMailerTheme();
1009         }
1010
1011         // Return theme value
1012         return $ret;
1013 }
1014
1015 // Generates an error code from given account status
1016 function generateErrorCodeFromUserStatus ($status = '') {
1017         // If no status is provided, use the default, cached
1018         if ((empty($status)) && (isMember())) {
1019                 // Get user status
1020                 $status = getUserData('status');
1021         } // END - if
1022
1023         // Default error code if unknown account status
1024         $errorCode = getCode('ACCOUNT_UNKNOWN');
1025
1026         // Generate constant name
1027         $codeName = sprintf('ACCOUNT_%s', strtoupper($status));
1028
1029         // Is the constant there?
1030         if (isCodeSet($codeName)) {
1031                 // Then get it!
1032                 $errorCode = getCode($codeName);
1033         } else {
1034                 // Unknown status
1035                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown error status %s detected.', $status));
1036         }
1037
1038         // Return error code
1039         return $errorCode;
1040 }
1041
1042 // Back-ported from the new ship-simu engine. :-)
1043 function debug_get_printable_backtrace () {
1044         // Init variable
1045         $backtrace = '<ol>';
1046
1047         // Get and prepare backtrace for output
1048         $backtraceArray = debug_backtrace();
1049         foreach ($backtraceArray as $key => $trace) {
1050                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1051                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1052                 if (!isset($trace['args'])) $trace['args'] = array();
1053                 $backtrace .= '<li class="debug_list"><span class="backtrace_file">' . basename($trace['file']) . '</span>:' . $trace['line'] . ', <span class="backtrace_function">' . $trace['function'] . '(' . count($trace['args']) . ')</span></li>';
1054         } // END - foreach
1055
1056         // Close it
1057         $backtrace .= '</ol>';
1058
1059         // Return the backtrace
1060         return $backtrace;
1061 }
1062
1063 // A mail-able backtrace
1064 function debug_get_mailable_backtrace () {
1065         // Init variable
1066         $backtrace = '';
1067
1068         // Get and prepare backtrace for output
1069         $backtraceArray = debug_backtrace();
1070         foreach ($backtraceArray as $key => $trace) {
1071                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1072                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1073                 if (!isset($trace['args'])) $trace['args'] = array();
1074                 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1075         } // END - foreach
1076
1077         // Return the backtrace
1078         return $backtrace;
1079 }
1080
1081 // Generates a ***weak*** seed
1082 function generateSeed () {
1083         return microtime(TRUE) * 100000;
1084 }
1085
1086 // Converts a message code to a human-readable message
1087 function getMessageFromErrorCode ($code) {
1088         // Default is an unknown error code
1089         $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1090
1091         // Which code is provided?
1092         switch ($code) {
1093                 case '':
1094                         // No error code is bad coding practice
1095                         reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1096                         break;
1097
1098                 // All error messages
1099                 case getCode('LOGOUT_DONE')         : $message = '{--LOGOUT_DONE--}'; break;
1100                 case getCode('LOGOUT_FAILED')       : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1101                 case getCode('DATA_INVALID')        : $message = '{--MAIL_DATA_INVALID--}'; break;
1102                 case getCode('POSSIBLE_INVALID')    : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1103                 case getCode('USER_404')            : $message = '{--USER_404--}'; break;
1104                 case getCode('STATS_404')           : $message = '{--MAIL_STATS_404--}'; break;
1105                 case getCode('ALREADY_CONFIRMED')   : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1106                 case getCode('BEG_SAME_AS_OWN')     : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1107                 case getCode('LOGIN_FAILED')        : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1108                 case getCode('MODULE_MEMBER_ONLY')  : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1109                 case getCode('OVERLENGTH')          : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1110                 case getCode('URL_FOUND')           : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1111                 case getCode('SUBJECT_URL')         : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1112                 case getCode('BLIST_URL')           : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1113                 case getCode('NO_RECS_LEFT')        : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1114                 case getCode('INVALID_TAGS')        : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1115                 case getCode('MORE_POINTS')         : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1116                 case getCode('MORE_RECEIVERS1')     : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1117                 case getCode('MORE_RECEIVERS2')     : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1118                 case getCode('MORE_RECEIVERS3')     : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1119                 case getCode('INVALID_URL')         : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1120                 case getCode('NO_MAIL_TYPE')        : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1121                 case getCode('PROFILE_UPDATED')     : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1122                 case getCode('UNKNOWN_REDIRECT')    : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1123                 case getCode('WRONG_PASS')          : $message = '{--LOGIN_WRONG_PASS--}'; break;
1124                 case getCode('WRONG_ID')            : $message = '{--LOGIN_WRONG_ID--}'; break;
1125                 case getCode('ACCOUNT_LOCKED')      : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1126                 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1127                 case getCode('COOKIES_DISABLED')    : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1128                 case getCode('UNKNOWN_ERROR')       : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1129                 case getCode('UNKNOWN_STATUS')      : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1130                 case getCode('LOGIN_EMPTY_ID')      : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1131                 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1132
1133                 case getCode('ERROR_MAILID'):
1134                         if (isExtensionActive('mailid', TRUE)) {
1135                                 $message = '{--ERROR_CONFIRMING_MAIL--}';
1136                         } else {
1137                                 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1138                         }
1139                         break;
1140
1141                 case getCode('EXTENSION_PROBLEM'):
1142                         if (isGetRequestElementSet('ext')) {
1143                                 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1144                         } else {
1145                                 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1146                         }
1147                         break;
1148
1149                 case getCode('URL_TIME_LOCK'):
1150                         // Load timestamp from last order
1151                         $content = getPoolDataFromId(getRequestElement('id'));
1152
1153                         // Translate it for templates
1154                         $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1155
1156                         // Calculate hours...
1157                         $content['hours'] = round(getUrlTlock() / 60 / 60);
1158
1159                         // Minutes...
1160                         $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1161
1162                         // And seconds
1163                         $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1164
1165                         // Finally contruct the message
1166                         $message = loadTemplate('tlock_message', TRUE, $content);
1167                         break;
1168
1169                 default:
1170                         // Log missing/invalid error codes
1171                         logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1172                         break;
1173         } // END - switch
1174
1175         // Return the message
1176         return $message;
1177 }
1178
1179 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1180 function isUrlValidSimple ($url) {
1181         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1182         // Prepare URL
1183         $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1184
1185         // Allows http and https
1186         $http      = "(http|https)+(:\/\/)";
1187         // Test domain
1188         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1189         // Test double-domains (e.g. .de.vu)
1190         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1191         // Test IP number
1192         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1193         // ... directory
1194         $dir       = "((/)+([-_\.[:alnum:]])+)*";
1195         // ... page
1196         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1197         // ... and the string after and including question character
1198         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1199         // Pattern for URLs like http://url/dir/doc.html?var=value
1200         $pattern['d1dpg1']  = $http . $domain1 . $dir . $page . $getstring1;
1201         $pattern['d2dpg1']  = $http . $domain2 . $dir . $page . $getstring1;
1202         $pattern['ipdpg1']  = $http . $ip . $dir . $page . $getstring1;
1203         // Pattern for URLs like http://url/dir/?var=value
1204         $pattern['d1dg1']  = $http . $domain1 . $dir.'/' . $getstring1;
1205         $pattern['d2dg1']  = $http . $domain2 . $dir.'/' . $getstring1;
1206         $pattern['ipdg1']  = $http . $ip . $dir.'/' . $getstring1;
1207         // Pattern for URLs like http://url/dir/page.ext
1208         $pattern['d1dp']  = $http . $domain1 . $dir . $page;
1209         $pattern['d1dp']  = $http . $domain2 . $dir . $page;
1210         $pattern['ipdp']  = $http . $ip . $dir . $page;
1211         // Pattern for URLs like http://url/dir
1212         $pattern['d1d']  = $http . $domain1 . $dir;
1213         $pattern['d2d']  = $http . $domain2 . $dir;
1214         $pattern['ipd']  = $http . $ip . $dir;
1215         // Pattern for URLs like http://url/?var=value
1216         $pattern['d1g1']  = $http . $domain1 . '/' . $getstring1;
1217         $pattern['d2g1']  = $http . $domain2 . '/' . $getstring1;
1218         $pattern['ipg1']  = $http . $ip . '/' . $getstring1;
1219         // Pattern for URLs like http://url?var=value
1220         $pattern['d1g12']  = $http . $domain1 . $getstring1;
1221         $pattern['d2g12']  = $http . $domain2 . $getstring1;
1222         $pattern['ipg12']  = $http . $ip . $getstring1;
1223
1224         // Test all patterns
1225         $reg = FALSE;
1226         foreach ($pattern as $key => $pat) {
1227                 // Debug regex?
1228                 if (isDebugRegularExpressionEnabled()) {
1229                         // @TODO Are these convertions still required?
1230                         $pat = str_replace('.', '&#92;&#46;', $pat);
1231                         $pat = str_replace('@', '&#92;&#64;', $pat);
1232                         //* DEBUG: */ debugOutput($key . '=&nbsp;' . $pat);
1233                 } // END - if
1234
1235                 // Check if expression matches
1236                 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1237
1238                 // Does it match?
1239                 if ($reg === TRUE) {
1240                         break;
1241                 } // END - if
1242         } // END - foreach
1243
1244         // Return true/false
1245         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1246         return $reg;
1247 }
1248
1249 // Wtites data to a config.php-style file
1250 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1251 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek = 0) {
1252         // Initialize some variables
1253         $done = FALSE;
1254         $seek++;
1255         $next  = -1;
1256         $found = FALSE;
1257
1258         // Is the file there and read-/write-able?
1259         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1260                 $search = 'CFG: ' . $comment;
1261                 $tmp = $FQFN . '.tmp';
1262
1263                 // Open the source file
1264                 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1265
1266                 // Is the resource valid?
1267                 if (is_resource($fp)) {
1268                         // Open temporary file
1269                         $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1270
1271                         // Is the resource again valid?
1272                         if (is_resource($fp_tmp)) {
1273                                 // Mark temporary file as readable
1274                                 $GLOBALS['file_readable'][$tmp] = TRUE;
1275
1276                                 // Start reading
1277                                 while (!feof($fp)) {
1278                                         // Read from source file
1279                                         $line = fgets($fp, 1024);
1280
1281                                         if (isInString($search, $line)) {
1282                                                 $next = '0';
1283                                                 $found = TRUE;
1284                                         } // END - if
1285
1286                                         if ($next > -1) {
1287                                                 if ($next === $seek) {
1288                                                         $next = -1;
1289                                                         $line = $prefix . $inserted . $suffix . PHP_EOL;
1290                                                 } else {
1291                                                         $next++;
1292                                                 }
1293                                         } // END - if
1294
1295                                         // Write to temp file
1296                                         fwrite($fp_tmp, $line);
1297                                 } // END - while
1298
1299                                 // Close temp file
1300                                 fclose($fp_tmp);
1301
1302                                 // Finished writing tmp file
1303                                 $done = TRUE;
1304                         } // END - if
1305
1306                         // Close source file
1307                         fclose($fp);
1308
1309                         if (($done === TRUE) && ($found === TRUE)) {
1310                                 // Copy back temporary->FQFN file and ...
1311                                 copyFileVerified($tmp, $FQFN, 0644);
1312
1313                                 // ... delete temporay file :-)
1314                                 return removeFile($tmp);
1315                         } elseif ($found === FALSE) {
1316                                 // Entry not found
1317                                 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!');
1318                         } else {
1319                                 // Temporary file not fully written
1320                                 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - Temporary file unfinished!');
1321                         }
1322                 }
1323         } else {
1324                 // File not found, not readable or writeable
1325                 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN) . ',comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek);
1326         }
1327
1328         // An error was detected!
1329         return FALSE;
1330 }
1331
1332 // Debug message logger
1333 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1334         // Is debug mode enabled?
1335         if ((isDebugModeEnabled()) || ($force === TRUE)) {
1336                 // Remove CRLF
1337                 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1338
1339                 // Log this message away
1340                 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1341         } // END - if
1342 }
1343
1344 // Handle extra values
1345 function handleExtraValues ($filterFunction, $value, $extraValue) {
1346         // Default is the value itself
1347         $ret = $value;
1348
1349         // Is there a special filter function?
1350         if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1351                 // Call-back function does not exist or is empty
1352                 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1353         } // END - if
1354
1355         // Is there extra parameters here?
1356         if ((!is_null($extraValue)) && (!empty($extraValue))) {
1357                 // Put both parameters in one new array by default
1358                 $args = array($value, $extraValue);
1359
1360                 // If we have an array simply use it and pre-extend it with our value
1361                 if (is_array($extraValue)) {
1362                         // Make the new args array
1363                         $args = merge_array(array($value), $extraValue);
1364                 } // END - if
1365
1366                 // Call the multi-parameter call-back
1367                 $ret = call_user_func_array($filterFunction, $args);
1368
1369                 // Is $ret 'true'?
1370                 if ($ret === TRUE) {
1371                         // Test passed, so write direct value
1372                         $ret = $args;
1373                 } // END - if
1374         } else {
1375                 // One parameter call
1376                 $ret = call_user_func($filterFunction, $value);
1377                 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1378
1379                 // Is $ret 'true'?
1380                 if ($ret === TRUE) {
1381                         // Test passed, so write direct value
1382                         $ret = $value;
1383                 } // END - if
1384         }
1385
1386         // Return the value
1387         return $ret;
1388 }
1389
1390 // Tries to determine if call-back functions and/or extra values shall be parsed
1391 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1392         // Debug mode enabled?
1393         if (isDebugModeEnabled()) {
1394                 // Debug message
1395                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1396         } // END - if
1397
1398         // Send data through the filter function if found
1399         if ($key === $userIdColumn[0]) {
1400                 // Is the userid, we have to process it with convertZeroToNull()
1401                 $entries = convertZeroToNull($entries);
1402         } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1403                 // Debug mode enabled?
1404                 if (isDebugModeEnabled()) {
1405                         // Then log it
1406                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1407                 } // END - if
1408
1409                 // Filter function + extra value set
1410                 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1411
1412                 // Debug mode enabled?
1413                 if (isDebugModeEnabled()) {
1414                         // Then log it
1415                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1416                 } // END - if
1417         } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1418                 // Debug mode enabled?
1419                 if (isDebugModeEnabled()) {
1420                         // Then log it
1421                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1422                 } // END - if
1423
1424                 // Handle extra values
1425                 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1426
1427                 // Debug mode enabled?
1428                 if (isDebugModeEnabled()) {
1429                         // Then log it
1430                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1431                 } // END - if
1432
1433                 // Make sure entries is not bool, then something went wrong
1434                 assert(!is_bool($entries));
1435         } elseif (!empty($filterFunctions[$search])) {
1436                 // Debug mode enabled?
1437                 if (isDebugModeEnabled()) {
1438                         // Then log it
1439                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1440                 } // END - if
1441
1442                 // Handle extra values
1443                 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1444
1445                 // Debug mode enabled?
1446                 if (isDebugModeEnabled()) {
1447                         // Then log it
1448                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1449                 } // END - if
1450
1451                 // Make sure entries is not bool, then something went wrong
1452                 assert(!is_bool($entries));
1453         }
1454
1455         // Return value
1456         return $entries;
1457 }
1458
1459 // Converts timestamp selections into a timestamp
1460 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1461         // Init test variable
1462         $skip  = FALSE;
1463         $test2 = '';
1464
1465         // Get last three chars
1466         $test = substr($id, -3);
1467
1468         // Improved way of checking! :-)
1469         if (in_array($test, array('_ye', '_mo', '_mn', '_we', '_da', '_ho', '_mi', '_se'))) {
1470                 // Found a multi-selection for timings?
1471                 $test = substr($id, 0, -3);
1472                 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)) {
1473                         // Generate timestamp
1474                         $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1475                         array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1476                         $GLOBALS['skip_config'][$test] = TRUE;
1477
1478                         // Remove data from array
1479                         foreach (array('ye', 'mo', 'mn', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1480                                 unset($postData[$test . '_' . $rem]);
1481                         } // END - foreach
1482
1483                         // Skip adding
1484                         unset($id);
1485                         $skip = TRUE;
1486                         $test2 = $test;
1487                 } // END - if
1488         } // END - if
1489 }
1490
1491 // Reverts the german decimal comma into Computer decimal dot
1492 // OPPOMENT: translateComma()
1493 function convertCommaToDot ($str) {
1494         // Default float is not a float... ;-)
1495         $float = FALSE;
1496
1497         // Which language is selected?
1498         switch (getLanguage()) {
1499                 case 'de': // German language
1500                         // Remove german thousand dots first
1501                         $str = str_replace('.', '', $str);
1502
1503                         // Replace german commata with decimal dot and cast it
1504                         $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str));
1505                         break;
1506
1507                 default: // US and so on
1508                         // Remove thousand commatas first and cast
1509                         $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str));
1510                         break;
1511         } // END - switch
1512
1513         // Return float
1514         return $float;
1515 }
1516
1517 // Handle menu-depending failed logins and return the rendered content
1518 function handleLoginFailures ($accessLevel) {
1519         // Default output is empty ;-)
1520         $OUT = '';
1521
1522         // Is the session data set?
1523         if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1524                 // Ignore zero values
1525                 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1526                         // Non-guest has login failures found, get both data and prepare it for template
1527                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1528                         $content = array(
1529                                 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1530                                 'last_failure'   => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1531                         );
1532
1533                         // Load template
1534                         $OUT = loadTemplate('login_failures', TRUE, $content);
1535                 } // END - if
1536
1537                 // Reset session data
1538                 setSession('mailer_' . $accessLevel . '_failures', '');
1539                 setSession('mailer_' . $accessLevel . '_last_failure', '');
1540         } // END - if
1541
1542         // Return rendered content
1543         return $OUT;
1544 }
1545
1546 // Rebuild cache
1547 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1548         // Debug message
1549         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1550
1551         // Shall I remove the cache file?
1552         if ((isExtensionInstalled('cache')) && (isValidCacheInstance()) && (isHtmlOutputMode())) {
1553                 // Rebuild cache only in HTML output-mode
1554                 // @TODO This should be rewritten not to load the cache file for just checking if it is there for save removal.
1555                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1556                         // Destroy it
1557                         $GLOBALS['cache_instance']->removeCacheFile($force);
1558                 } // END - if
1559
1560                 // Include file given?
1561                 if (!empty($inc)) {
1562                         // Construct FQFN
1563                         $inc = sprintf('inc/loader/load-%s.php', $inc);
1564
1565                         // Is the include there?
1566                         if (isIncludeReadable($inc)) {
1567                                 // And rebuild it from scratch
1568                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1569                                 loadInclude($inc);
1570                         } else {
1571                                 // Include not found, which needs now tracing
1572                                 reportBug(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1573                         }
1574                 } // END - if
1575         } // END - if
1576 }
1577
1578 // Determines the real remote address
1579 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1580         // Default is 127.0.0.1
1581         $address = '127.0.0.1';
1582
1583         // Is a proxy in use?
1584         if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1585                 // Proxy was used
1586                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1587         } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1588                 // Yet, another proxy
1589                 $address = $_SERVER['HTTP_CLIENT_IP'];
1590         } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1591                 // The regular address when no proxy was used
1592                 $address = $_SERVER['REMOTE_ADDR'];
1593         }
1594
1595         // This strips out the real address from proxy output
1596         if (strstr($address, ',')) {
1597                 $addressArray = explode(',', $address);
1598                 $address = $addressArray[0];
1599         } // END - if
1600
1601         // Return the result
1602         return $address;
1603 }
1604
1605 // Adds a bonus mail to the queue
1606 // This is a high-level function!
1607 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1608         // Use mode from data if not set and availble ;-)
1609         if ((empty($mode)) && (isset($data['mail_mode']))) {
1610                 $mode = $data['mail_mode'];
1611         } // END - if
1612
1613         // Generate receiver list
1614         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1615
1616         // Receivers added?
1617         if (!empty($receiver)) {
1618                 // Add bonus mail to queue
1619                 addBonusMailToQueue(
1620                         $data['subject'],
1621                         $data['text'],
1622                         $receiver,
1623                         $data['points'],
1624                         $data['seconds'],
1625                         $data['url'],
1626                         $data['cat'],
1627                         $mode,
1628                         $data['receiver']
1629                 );
1630
1631                 // Mail inserted into bonus pool
1632                 if ($output === TRUE) {
1633                         displayMessage('{--ADMIN_BONUS_SEND--}');
1634                 } // END - if
1635         } elseif ($output === TRUE) {
1636                 // More entered than can be reached!
1637                 displayMessage('{--ADMIN_MORE_SELECTED--}');
1638         } else {
1639                 // Debug log
1640                 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1641         }
1642 }
1643
1644 // Enables the hourly reset mode and runs it
1645 function doHourly () {
1646         // Enable the hourly reset mode
1647         $GLOBALS['hourly_enabled'] = TRUE;
1648
1649         // Run filters (one always!)
1650         runFilterChain('hourly');
1651
1652         // Do not update in hourly debug mode
1653         if ((!isConfigEntrySet('DEBUG_HOURLY')) || (!isDebugHourlyEnabled())) {
1654                 // Update database
1655                 updateConfiguration('last_hourly', getHour());
1656         } // END - if
1657 }
1658
1659 // Enables the daily reset mode and runs it
1660 function doDaily () {
1661         // Enable the reset mode
1662         $GLOBALS['daily_enabled'] = TRUE;
1663
1664         // Run filters
1665         runFilterChain('daily');
1666
1667         // Do not update in daily debug mode
1668         if ((!isConfigEntrySet('DEBUG_DAILY')) || (!isDebugDailyEnabled())) {
1669                 // Update database
1670                 updateConfiguration('last_daily', getDay());
1671         } // END - if
1672 }
1673
1674 // Enables the weekly reset mode and runs it
1675 function doWeekly () {
1676         // Enable the reset mode
1677         $GLOBALS['weekly_enabled'] = TRUE;
1678
1679         // Run filters
1680         runFilterChain('weekly');
1681
1682         // Do not update in weekly debug mode
1683         if ((!isConfigEntrySet('DEBUG_WEEKLY')) || (!isDebugWeeklyEnabled())) {
1684                 // Update database
1685                 updateConfiguration('last_weekly', getWeek());
1686         } // END - if
1687 }
1688
1689 // Enables the monthly reset mode and runs it
1690 function doMonthly () {
1691         // Enable the reset mode
1692         $GLOBALS['monthly_enabled'] = TRUE;
1693
1694         // Run filters
1695         runFilterChain('monthly');
1696
1697         // Do not update in monthly debug mode
1698         if ((!isConfigEntrySet('DEBUG_MONTHLY')) || (!isDebugMonthlyEnabled())) {
1699                 // Update database
1700                 updateConfiguration('last_monthly', getMonth());
1701         } // END - if
1702 }
1703
1704 // Enables the yearly reset mode and runs it
1705 function doYearly () {
1706         // Enable the reset mode
1707         $GLOBALS['yearly_enabled'] = TRUE;
1708
1709         // Run filters
1710         runFilterChain('yearly');
1711
1712         // Do not update in yearly debug mode
1713         if ((!isConfigEntrySet('DEBUG_YEARLY')) || (!isDebugYearlyEnabled())) {
1714                 // Update database
1715                 updateConfiguration('last_yearly', getYear());
1716         } // END - if
1717 }
1718
1719 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1720 function doShutdown () {
1721         // Call the filter chain 'shutdown'
1722         runFilterChain('shutdown', NULL);
1723
1724         // Check if link is up
1725         if (isSqlLinkUp()) {
1726                 // Close link
1727                 sqlCloseLink(__FUNCTION__, __LINE__);
1728         } elseif (!isInstaller()) {
1729                 // No database link
1730                 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1731         }
1732
1733         // Stop executing here
1734         exit;
1735 }
1736
1737 // Init member id
1738 function initMemberId () {
1739         $GLOBALS['member_id'] = '0';
1740 }
1741
1742 // Setter for member id
1743 function setMemberId ($memberId) {
1744         // We should not set member id to zero
1745         if (!isValidId($memberId)) {
1746                 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1747         } // END - if
1748
1749         // Set it secured
1750         $GLOBALS['member_id'] = bigintval($memberId);
1751 }
1752
1753 // Getter for member id or returns zero
1754 function getMemberId () {
1755         // Default member id
1756         $memberId = '0';
1757
1758         // Is the member id set?
1759         if (isMemberIdSet()) {
1760                 // Then use it
1761                 $memberId = $GLOBALS['member_id'];
1762         } // END - if
1763
1764         // Return it
1765         return $memberId;
1766 }
1767
1768 // Checks ether the member id is set
1769 function isMemberIdSet () {
1770         return (isset($GLOBALS['member_id']));
1771 }
1772
1773 // Setter for extra title
1774 function setExtraTitle ($extraTitle) {
1775         $GLOBALS['extra_title'] = $extraTitle;
1776 }
1777
1778 // Getter for extra title
1779 function getExtraTitle () {
1780         // Is the extra title set?
1781         if (!isExtraTitleSet()) {
1782                 // No, then abort here
1783                 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1784         } // END - if
1785
1786         // Return it
1787         return $GLOBALS['extra_title'];
1788 }
1789
1790 // Checks if the extra title is set
1791 function isExtraTitleSet () {
1792         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1793 }
1794
1795 /**
1796  * Reads a directory recursively by default and searches for files not matching
1797  * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1798  * a whole directory.
1799  *
1800  * @param       $baseDir                        Relative base directory to PATH to scan from
1801  * @param       $prefix                         Prefix for all positive matches (which files should be found)
1802  * @param       $fileIncludeDirs        Whether to include directories in the final output array
1803  * @param       $addBaseDir                     Whether to add $baseDir to all array entries
1804  * @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'
1805  * @param       $extension                      File extension for all positive matches
1806  * @param       $excludePattern         Regular expression to exclude more files (preg_match())
1807  * @param       $recursive                      Whether to scan recursively
1808  * @param       $suffix                         Suffix for positive matches ($extension will be appended, too)
1809  * @param       $withPrefixSuffix       Whether to include prefix/suffix in found entries
1810  * @return      $foundMatches           All found positive matches for above criteria
1811  */
1812 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '', $withPrefixSuffix = TRUE) {
1813         // Add default entries we should always exclude
1814         array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1815
1816         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1817         // Init found includes
1818         $foundMatches = array();
1819
1820         // Open directory
1821         $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1822
1823         // Read all entries
1824         while ($baseFile = readdir($dirPointer)) {
1825                 // Exclude '.', '..' and entries in $excludeArray automatically
1826                 if (in_array($baseFile, $excludeArray, TRUE))  {
1827                         // Exclude them
1828                         //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1829                         continue;
1830                 } // END - if
1831
1832                 // Construct include filename and FQFN
1833                 $fileName = $baseDir . $baseFile;
1834                 $FQFN = getPath() . $fileName;
1835
1836                 // Remove double slashes
1837                 $FQFN = str_replace('//', '/', $FQFN);
1838
1839                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1840                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1841                         // Debug message
1842                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1843
1844                         // Exclude this one
1845                         continue;
1846                 } // END - if
1847
1848                 // Skip also files with non-matching prefix genericly
1849                 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1850                         // Is a redirectory so read it as well
1851                         $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1852
1853                         // And skip further processing
1854                         continue;
1855                 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1856                         // Skip this file
1857                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1858                         continue;
1859                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1860                         // Skip wrong suffix as well
1861                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1862                         continue;
1863                 } elseif (!isFileReadable($FQFN)) {
1864                         // Not readable so skip it
1865                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1866                 } elseif (filesize($FQFN) < 50) {
1867                         // Might be deprecated
1868                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1869                         continue;
1870                 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1871                         // This PHP script is deprecated
1872                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1873                         continue;
1874                 }
1875
1876                 // Get file' extension (last 4 chars)
1877                 $fileExtension = substr($baseFile, -4, 4);
1878
1879                 // Is the file a PHP script or other?
1880                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1881                 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1882                         // Is this a valid include file?
1883                         if ($extension == '.php') {
1884                                 // Remove both for extension name
1885                                 $extName = substr($baseFile, strlen($prefix), -4);
1886
1887                                 // Add file with or without base path
1888                                 if ($addBaseDir === TRUE) {
1889                                         // With base path
1890                                         array_push($foundMatches, $fileName);
1891                                 } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1892                                         // No prefix/suffix
1893                                         array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1894                                 } else {
1895                                         // No base path
1896                                         array_push($foundMatches, $baseFile);
1897                                 }
1898                         } else {
1899                                 // We found .php file but should not search for them, why?
1900                                 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1901                         }
1902                 } elseif ((($fileExtension == $extension) || (empty($extension))) && (isFileReadable($FQFN))) {
1903                         // Other, generic file found
1904                         if ($addBaseDir === TRUE) {
1905                                 // With base path
1906                                 array_push($foundMatches, $fileName);
1907                         } elseif (($withPrefixSuffix === FALSE) && (!empty($extension))) {
1908                                 // No prefix/suffix
1909                                 array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
1910                         } else {
1911                                 // No base path
1912                                 array_push($foundMatches, $baseFile);
1913                         }
1914                 }
1915         } // END - while
1916
1917         // Close directory
1918         closedir($dirPointer);
1919
1920         // Sort array
1921         sort($foundMatches);
1922
1923         // Return array with include files
1924         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1925         return $foundMatches;
1926 }
1927
1928 // Checks whether $prefix is found in $fileName
1929 function isFilePrefixFound ($fileName, $prefix) {
1930         // @TODO Find a way to cache this
1931         return (substr($fileName, 0, strlen($prefix)) == $prefix);
1932 }
1933
1934 // Maps a module name into a database table name
1935 function mapModuleToTable ($moduleName) {
1936         // Map only these, still lame code...
1937         switch ($moduleName) {
1938                 case 'index': // 'index' is the guest's menu
1939                         $moduleName = 'guest';
1940                         break;
1941
1942                 case 'login': // ... and 'login' the member's menu
1943                         $moduleName = 'member';
1944                         break;
1945                 // Anything else will not be mapped, silently.
1946         } // END - switch
1947
1948         // Return result
1949         return $moduleName;
1950 }
1951
1952 // Add SQL debug data to array for later output
1953 function addSqlToDebug ($result, $sqlString, $timing, $file, $line) {
1954         // Is there cache?
1955         if (!isset($GLOBALS['debug_sql_available'])) {
1956                 // Check it and cache it in $GLOBALS
1957                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1958         } // END - if
1959
1960         // Don't execute anything here if we don't need or ext-other is missing
1961         if ($GLOBALS['debug_sql_available'] === FALSE) {
1962                 return;
1963         } // END - if
1964
1965         // Already executed?
1966         if (isset($GLOBALS['debug_sqls'][$file][$line][$sqlString])) {
1967                 // Then abort here, we don't need to profile a query twice
1968                 return;
1969         } // END - if
1970
1971         // Remeber this as profiled (or not, but we don't care here)
1972         $GLOBALS['debug_sqls'][$file][$line][$sqlString] = TRUE;
1973
1974         // Generate record
1975         $record = array(
1976                 'num_rows' => sqlNumRows($result),
1977                 'affected' => sqlAffectedRows(),
1978                 'sql_str'  => $sqlString,
1979                 'timing'   => $timing,
1980                 'file'     => basename($file),
1981                 'line'     => $line
1982         );
1983
1984         // Add it
1985         array_push($GLOBALS['debug_sqls'], $record);
1986 }
1987
1988 // Initializes the cache instance
1989 function initCacheInstance () {
1990         // Check for double-initialization
1991         if (isset($GLOBALS['cache_instance'])) {
1992                 // This should not happen and must be fixed
1993                 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1994         } // END - if
1995
1996         // Load include for CacheSystem class
1997         loadIncludeOnce('inc/classes/cachesystem.class.php');
1998
1999         // Initialize cache system only when it's needed
2000         $GLOBALS['cache_instance'] = new CacheSystem();
2001
2002         // Did it work?
2003         if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
2004                 // Failed to initialize cache sustem
2005                 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
2006         } // END - if
2007 }
2008
2009 // Getter for message from array or raw message
2010 function getMessageFromIndexedArray ($message, $pos, $array) {
2011         // Check if the requested message was found in array
2012         if (isset($array[$pos])) {
2013                 // ... if yes then use it!
2014                 $ret = $array[$pos];
2015         } else {
2016                 // ... else use default message
2017                 $ret = $message;
2018         }
2019
2020         // Return result
2021         return $ret;
2022 }
2023
2024 // Convert ';' to ', ' for e.g. receiver list
2025 function convertReceivers ($old) {
2026         return str_replace(';', ', ', $old);
2027 }
2028
2029 // Get a module from filename and access level
2030 function getModuleFromFileName ($file, $accessLevel) {
2031         // Default is 'invalid';
2032         $modCheck = 'invalid';
2033
2034         // @TODO This is still very static, rewrite it somehow
2035         switch ($accessLevel) {
2036                 case 'admin':
2037                         $modCheck = 'admin';
2038                         break;
2039
2040                 case 'sponsor':
2041                 case 'guest':
2042                 case 'member':
2043                         $modCheck = getModule();
2044                         break;
2045
2046                 default: // Unsupported file name / access level
2047                         reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
2048                         break;
2049         } // END - switch
2050
2051         // Return result
2052         return $modCheck;
2053 }
2054
2055 // Encodes an URL for adding session id, etc.
2056 function encodeUrl ($url, $outputMode = '0') {
2057         // Is there already have a PHPSESSID inside or view.php is called? Then abort here
2058         if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
2059                 // Raw output mode detected or session_name() found in URL
2060                 return $url;
2061         } // END - if
2062
2063         // Is there a valid session?
2064         if ((!isValidSession()) && (!isSpider())) {
2065                 // Determine right separator
2066                 $separator = '&amp;';
2067                 if (!isInString('?', $url)) {
2068                         // No question mark
2069                         $separator = '?';
2070                 } // END - if
2071
2072                 // Then add it to URL
2073                 $url .= $separator . session_name() . '=' . session_id();
2074         } // END - if
2075
2076         // Add {?URL?} ?
2077         if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
2078                 // Add it
2079                 $url = '{?URL?}/' . $url;
2080         } // END - if
2081
2082         // Debug message
2083         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
2084
2085         // Is there to decode entities?
2086         if (!isHtmlOutputMode()) {
2087                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
2088                 // Decode them for e.g. JavaScript parts
2089                 $url = decodeEntities($url);
2090                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
2091         } // END - if
2092
2093         // Debug log
2094         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
2095
2096         // Return the encoded URL
2097         return $url;
2098 }
2099
2100 // Simple check for spider
2101 function isSpider () {
2102         // Get the UA and trim it down
2103         $userAgent = trim(detectUserAgent(TRUE));
2104
2105         // It should not be empty, if so it is better a browser
2106         if (empty($userAgent)) {
2107                 // It is a browser that blocks its UA string
2108                 return FALSE;
2109         } // END - if
2110
2111         // Is it a spider?
2112         return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2113 }
2114
2115 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2116 function handleFieldWithBraces ($field) {
2117         // Are there braces [] at the end?
2118         if (substr($field, -2, 2) == '[]') {
2119                 /*
2120                  * Try to find one and replace it. I do it this way to allow easy
2121                  * extending of this code.
2122                  */
2123                 foreach (array('admin_list_builder_id_value') as $key) {
2124                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2125                         // Is the cache entry set?
2126                         if (isset($GLOBALS[$key])) {
2127                                 // Insert it
2128                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2129
2130                                 // And abort
2131                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2132                                 break;
2133                         } // END - if
2134                 } // END - foreach
2135         } // END - if
2136
2137         // Return it
2138         return $field;
2139 }
2140
2141 // Converts a zero or NULL to word 'NULL'
2142 function convertZeroToNull ($number) {
2143         // Is it a valid username?
2144         if (isValidNumber($number)) {
2145                 // Always secure it
2146                 $number = bigintval($number);
2147         } else {
2148                 // Is not valid or zero
2149                 $number = 'NULL';
2150         }
2151
2152         // Return it
2153         return $number;
2154 }
2155
2156 // Converts an empty string to NULL, else leaves it untouched
2157 function convertEmptyToNull ($str) {
2158         // Is the string empty?
2159         if (strlen($str) == 0) {
2160                 // Is really empty
2161                 $str = NULL;
2162         } // END - if
2163
2164         // Return it
2165         return $str;
2166 }
2167
2168 // Converts a NULL|empty string|< 1 to zero
2169 function convertNullToZero ($number) {
2170         // Is it a valid username?
2171         if (!isValidNumber($number)) {
2172                 // Is not valid or zero
2173                 $number = '0';
2174         } // END - if
2175
2176         // Return it
2177         return $number;
2178 }
2179
2180 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2181 // Note: This function is cached
2182 function capitalizeUnderscoreString ($str) {
2183         // Is there cache?
2184         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2185                 // Init target string
2186                 $capitalized = '';
2187
2188                 // Explode it with the underscore, but rewrite dashes to underscore before
2189                 $strArray = explode('_', str_replace('-', '_', $str));
2190
2191                 // "Walk" through all elements and make them lower-case but first upper-case
2192                 foreach ($strArray as $part) {
2193                         // Capitalize the string part
2194                         $capitalized .= firstCharUpperCase($part);
2195                 } // END - foreach
2196
2197                 // Store the converted string in cache array
2198                 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2199         } // END - if
2200
2201         // Return cache
2202         return $GLOBALS[__FUNCTION__][$str];
2203 }
2204
2205 // Generate admin links for mail order
2206 // mailType can be: 'normal' or 'bonus'
2207 function generateAdminMailLinks ($mailType, $mailId) {
2208         // Init variables
2209         $OUT = '';
2210         $table = '';
2211
2212         // Default column for mail status is 'data_type'
2213         // @TODO Rename column data_type to e.g. mail_status
2214         $statusColumn = 'data_type';
2215
2216         // Which mail do we have?
2217         switch ($mailType) {
2218                 case 'bonus': // Bonus mail
2219                         $table = 'bonus';
2220                         break;
2221
2222                 case 'normal': // Member mail
2223                         $table = 'pool';
2224                         break;
2225
2226                 default: // Handle unsupported types
2227                         logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2228                         $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2229                         break;
2230         } // END - switch
2231
2232         // Is the mail type supported?
2233         if (!empty($table)) {
2234                 // Query for the mail
2235                 $result = sqlQueryEscaped("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2236                         array(
2237                                 $statusColumn,
2238                                 $table,
2239                                 bigintval($mailId)
2240                         ), __FILE__, __LINE__);
2241
2242                 // Is there one entry there?
2243                 if (sqlNumRows($result) == 1) {
2244                         // Load the entry
2245                         $content = sqlFetchArray($result);
2246
2247                         // Add output and type
2248                         $content['type']     = $mailType;
2249                         $content['__output'] = '';
2250
2251                         // Filter all data
2252                         $content = runFilterChain('generate_admin_mail_links', $content);
2253
2254                         // Get output back
2255                         $OUT = $content['__output'];
2256                 } // END - if
2257
2258                 // Free result
2259                 sqlFreeResult($result);
2260         } // END - if
2261
2262         // Return generated HTML code
2263         return $OUT;
2264 }
2265
2266
2267 /**
2268  * Determine if a string can represent a number in hexadecimal
2269  *
2270  * @param       $hex    A string to check if it is hex-encoded
2271  * @return      $foo    True if the string is a hex, otherwise false
2272  * @author      Marques Johansson
2273  * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
2274  */
2275 function isHexadecimal ($hex) {
2276         // Make it lowercase
2277         $hex = strtolower(trim(ltrim($hex, '0')));
2278
2279         // Fix empty strings to zero
2280         if (empty($hex)) {
2281                 $hex = 0;
2282         } // END - if
2283
2284         // Simply compare decode->encode result with original
2285         return ($hex == dechex(hexdec($hex)));
2286 }
2287
2288 /**
2289  * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2290  * them visible to the developer. Use this function to debug e.g. buggy HTTP
2291  * response handler functions.
2292  *
2293  * @param       $str    String to overwork
2294  * @return      $str    Overworked string
2295  */
2296 function replaceReturnNewLine ($str) {
2297         return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2298 }
2299
2300 // Converts a given string by splitting it up with given delimiter similar to
2301 // explode(), but appending the delimiter again
2302 function stringToArray ($delimiter, $string) {
2303         // Init array
2304         $strArray = array();
2305
2306         // "Walk" through all entries
2307         foreach (explode($delimiter, $string) as $split) {
2308                 //  Append the delimiter and add it to the array
2309                 array_push($strArray, $split . $delimiter);
2310         } // END - foreach
2311
2312         // Return array
2313         return $strArray;
2314 }
2315
2316 // Detects the prefix 'mb_' if a multi-byte string is given
2317 function detectMultiBytePrefix ($str) {
2318         // Default is without multi-byte
2319         $mbPrefix = '';
2320
2321         // Detect multi-byte (strictly)
2322         if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2323                 // With multi-byte encoded string
2324                 $mbPrefix = 'mb_';
2325         } // END - if
2326
2327         // Return the prefix
2328         return $mbPrefix;
2329 }
2330
2331 // Searches given array for a sub-string match and returns all found keys in an array
2332 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2333         // Init array for all found keys
2334         $keys = array();
2335
2336         // Now check all entries
2337         foreach ($needles as $key => $needle) {
2338                 // Is there found a partial string?
2339                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2340                 if (strpos($heystack, $needle, $offset) !== FALSE) {
2341                         // Add the found key
2342                         array_push($keys, $key);
2343                 } // END - if
2344         } // END - foreach
2345
2346         // Return the array
2347         return $keys;
2348 }
2349
2350 // Determines database column name from given subject and locked
2351 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2352         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2353         // Default is 'normal' points
2354         $pointsColumn = 'points';
2355
2356         // Which points, locked or normal?
2357         if ($locked === TRUE) {
2358                 $pointsColumn = 'locked_points';
2359         } // END - if
2360
2361         // Prepare array for filter
2362         $filterData = array(
2363                 'subject' => $subject,
2364                 'locked'  => $locked,
2365                 'column'  => $pointsColumn
2366         );
2367
2368         // Run the filter
2369         $filterData = runFilterChain('determine_points_column_name', $filterData);
2370
2371         // Extract column name from array
2372         $pointsColumn = $filterData['column'];
2373
2374         // Return it
2375         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2376         return $pointsColumn;
2377 }
2378
2379 // Converts a boolean variable into 'Y' for true and 'N' for false
2380 function convertBooleanToYesNo ($boolean) {
2381         // Default is 'N'
2382         $converted = 'N';
2383         if ($boolean === TRUE) {
2384                 // Set 'Y'
2385                 $converted = 'Y';
2386         } // END - if
2387
2388         // Return it
2389         return $converted;
2390 }
2391
2392 // "Translates" 'true' to true and 'false' to false
2393 function convertStringToBoolean ($str) {
2394         // Debug message (to measure how often this function is called)
2395         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2396
2397         // Is there cache?
2398         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2399                 // Trim it lower-case for validation
2400                 $strTrimmed = trim(strtolower($str));
2401
2402                 // Is it valid?
2403                 if (!in_array($strTrimmed, array('true', 'false'))) {
2404                         // Not valid!
2405                         reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2406                 } // END - if
2407
2408                 // Determine it
2409                 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2410         } // END - if
2411
2412         // Return cache
2413         return $GLOBALS[__FUNCTION__][$str];
2414 }
2415
2416 /**
2417  * "Makes" a variable in given string parseable, this function will throw an
2418  * error if the first character is not a dollar sign.
2419  *
2420  * @param       $varString      String which contains a variable
2421  * @return      $return         String with added single quotes for better parsing
2422  */
2423 function makeParseableVariable ($varString) {
2424         // The first character must be a dollar sign
2425         if (substr($varString, 0, 1) != '$') {
2426                 // Please report this
2427                 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2428         } // END - if
2429
2430         // Is there cache?
2431         if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2432                 // Snap them in, if [,] are there
2433                 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2434         } // END - if
2435
2436         // Return cache
2437         return $GLOBALS[__FUNCTION__][$varString];
2438 }
2439
2440 // "Getter" for random TAN
2441 function getRandomTan () {
2442         // Generate one
2443         return mt_rand(0, 99999);
2444 }
2445
2446 // Removes any : from subject
2447 function removeDoubleDotFromSubject ($subject) {
2448         // Remove it
2449         $subjectArray = explode(':', $subject);
2450         $subject = $subjectArray[0];
2451         unset($subjectArray);
2452
2453         // Return it
2454         return $subject;
2455 }
2456
2457 // Adds a given entry to the database
2458 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2459         // Is it a member?
2460         if (!isMember()) {
2461                 // Then abort here
2462                 return FALSE;
2463         } // END - if
2464
2465         // Set POST data generic userid
2466         setPostRequestElement('userid', getMemberId());
2467
2468         // Call inner function
2469         doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2470
2471         // Entry has been added?
2472         if ((!ifSqlHasZeroAffectedRows()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2473                 // Display success message
2474                 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2475         } else {
2476                 // Display failed message
2477                 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2478         }
2479 }
2480
2481 // Edit rows by given id numbers
2482 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()) {
2483         // $tableName must be an array
2484         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2485                 // No tableName specified
2486                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2487         } elseif (!is_array($idColumn)) {
2488                 // $idColumn is no array
2489                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2490         } elseif (!is_array($userIdColumn)) {
2491                 // $userIdColumn is no array
2492                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2493         } elseif (!is_array($editNow)) {
2494                 // $editNow is no array
2495                 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2496         } // END - if
2497
2498         // Shall we change here or list for editing?
2499         if ($editNow[0] === TRUE) {
2500                 // Add generic userid field
2501                 setPostRequestElement('userid', getMemberId());
2502
2503                 // Call generic change method
2504                 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2505
2506                 // Was this fine?
2507                 if ($affected == countPostSelection($idColumn[0])) {
2508                         // All deleted
2509                         displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2510                 } else {
2511                         // Some are still there :(
2512                         displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2513                 }
2514         } else {
2515                 // List for editing
2516                 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2517         }
2518 }
2519
2520 // Delete rows by given id numbers
2521 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()) {
2522         // Do this only for members
2523         assert(isMember());
2524
2525         // $tableName must be an array
2526         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2527                 // No tableName specified
2528                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2529         } elseif (!is_array($idColumn)) {
2530                 // $idColumn is no array
2531                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2532         } elseif (!is_array($userIdColumn)) {
2533                 // $userIdColumn is no array
2534                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2535         } elseif (!is_array($deleteNow)) {
2536                 // $deleteNow is no array
2537                 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2538         } // END - if
2539
2540         // Shall we delete here or list for deletion?
2541         if ($deleteNow[0] === TRUE) {
2542                 // Add generic userid field
2543                 setPostRequestElement('userid', getMemberId());
2544
2545                 // Call generic function
2546                 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2547
2548                 // Was this fine?
2549                 if ($affected == countPostSelection($idColumn[0])) {
2550                         // All deleted
2551                         displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2552                 } else {
2553                         // Some are still there :(
2554                         displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), sqlAffectedRows(), countPostSelection($idColumn[0])));
2555                 }
2556         } else {
2557                 // List for deletion confirmation
2558                 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2559         }
2560 }
2561
2562 // Build a special template list
2563 // @TODO cacheFiles is not yet supported
2564 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2565         // Do this only for logged in member
2566         assert(isMember());
2567
2568         // Call inner (general) function
2569         doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2570 }
2571
2572 // Checks whether given address is IPv4
2573 function isIp4AddressValid ($address) {
2574         // Is there cache?
2575         if (!isset($GLOBALS[__FUNCTION__][$address])) {
2576                 // Determine it ...
2577                 $GLOBALS[__FUNCTION__][$address] = preg_match('/((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))/', $address);
2578         } // END - if
2579
2580         // Return cache
2581         return $GLOBALS[__FUNCTION__][$address];
2582 }
2583
2584 // Returns the string if not empty or FALSE if empty
2585 function validateIsEmpty ($str) {
2586         // Trim it
2587         $trimmed = trim($str);
2588
2589         // Is the string empty?
2590         if (empty($trimmed)) {
2591                 // Then set FALSE
2592                 $str = FALSE;
2593         } // END - if
2594
2595         // Return it
2596         return $str;
2597 }
2598
2599 // "Getter" for seconds from given time unit
2600 function getSecondsFromTimeUnit ($timeUnit) {
2601         // Default is not found
2602         $seconds = NULL;
2603
2604         // "Detect" it
2605         switch ($timeUnit) {
2606                 case 's': // Seconds = 1
2607                         $seconds = 1;
2608                         break;
2609
2610                 case 'm': // Minutes
2611                         $seconds = 60;
2612                         break;
2613
2614                 case 'h': // Hours
2615                         $seconds = 60*60;
2616                         break;
2617
2618                 case 'D': // Days
2619                         $seconds = 60*60*24;
2620                         break;
2621
2622                 case 'W': // Weeks
2623                         $seconds = 60*60*24*7;
2624                         break;
2625
2626                 default: // Unsupported
2627                         reportBug(__FUNCTION__, __LINE__, 'Unsupported time unit ' . $timeUnit . ' detected.');
2628                         break;
2629         } // END - switch
2630
2631         // Return value
2632         return $seconds;
2633 }
2634
2635 // Calulates value for given seconds and time unit
2636 function caluculateTimeUnitValue ($seconds, $timeUnit) {
2637         // Calculate it
2638         return ($seconds / getSecondsFromTimeUnit($timeUnit));
2639 }
2640
2641 // "Getter" for an array from given one but only one index of it
2642 function getArrayFromArrayIndex ($array, $key) {
2643         // Some simple validation
2644         assert(isset($array[0][$key]));
2645
2646         // Init new array
2647         $newArray = array();
2648
2649         // "Walk" through all elements
2650         foreach ($array as $element) {
2651                 $newArray[] = $element[$key];
2652         } // END - if
2653
2654         // Return it
2655         return $newArray;
2656 }
2657
2658 /**
2659  * Compress given data and encodes it into BASE64 to be stored in database with
2660  * sqlQueryEscaped()
2661  *
2662  * @param       $data   Data to be compressed and encoded
2663  * @return      $data   Compressed+encoded data
2664  */
2665 function compress ($data) {
2666         // Compress it
2667         return base64_encode(gzcompress($data));
2668 }
2669
2670 /**
2671  * Decompress given data previously compressed with compress().
2672  *
2673  * @param       $data   Data compressed with compress()
2674  * @reurn       $data   Uncompressed data
2675  */
2676 function decompress ($data) {
2677         // Decompress it
2678         return gzuncompress(base64_decode($data));
2679 }
2680
2681 /**
2682  * Converts given charset in given string to UTF-8 if not UTF-8. This function
2683  * is currently limited to iconv().
2684  *
2685  * @param       $str            String to convert charset in
2686  * @param       $charset        Charset to convert from
2687  * @return      $str            Converted string
2688  */
2689 function convertCharsetToUtf8 ($str, $charset) {
2690         // Is iconv() available?
2691         if (!function_exists('iconv')) {
2692                 // Please make it sure
2693                 reportBug(__FUNCTION__, __LINE__, 'PHP function iconv() is currently required to do charset convertion.');
2694         } // END - if
2695
2696         // Is the charset not UTF-8?
2697         if (strtoupper($charset) != 'UTF-8') {
2698                 // Convert it to UTF-8
2699                 $str = iconv(strtoupper($charset), 'UTF-8//TRANSLIT', $str);
2700         } // END - if
2701
2702         // Return converted string
2703         return $str;
2704 }
2705
2706 // Hash string with SHA256 and encode it to hex
2707 function hashSha256 ($str) {
2708         /// Hash string
2709         $hash = mhash(MHASH_SHA256, $str);
2710
2711         // Encode it to hexadecimal
2712         $hex = '';
2713         for ($i = 0; $i < strlen($hash); $i++) {
2714                 // Encode char to decimal, pad it with zero, add it
2715                 $hex .= padLeftZero(dechex(ord(substr($hash, $i, 1))), 2);
2716         } // END - if
2717
2718         // Make sure 'length modulo 2' = 0
2719         assert((strlen($hex) % 2) == 0);
2720
2721         // Return it
2722         return $hex;
2723 }
2724
2725 // ----------------------------------------------------------------------------
2726 //              "Translatation" functions for points_data table
2727 // ----------------------------------------------------------------------------
2728
2729 // Translates generically some data into a target string
2730 function translateGeneric ($messagePrefix, $data, $messageSuffix = '') {
2731         // Is the method null or empty?
2732         if (is_null($data)) {
2733                 // Is NULL
2734                 $data = 'NULL';
2735         } elseif (empty($data)) {
2736                 // Is empty (string)
2737                 $data = 'EMPTY';
2738         } // END - if
2739
2740         // Default column name is unknown
2741         $return = '{%message,' . $messagePrefix . '_UNKNOWN' . $messageSuffix . '=' . strtoupper($data) . '%}';
2742
2743         // Construct message id
2744         $messageId = $messagePrefix . '_' . strtoupper($data) . $messageSuffix;
2745
2746         // Is it there?
2747         if (isMessageIdValid($messageId)) {
2748                 // Then use it as message string
2749                 $return = '{--' . $messageId . '--}';
2750         } // END - if
2751
2752         // Return the column name
2753         return $return;
2754 }
2755
2756 // Translates points subject to human-readable
2757 function translatePointsSubject ($subject) {
2758         // Remove any :x
2759         $subject = removeDoubleDotFromSubject($subject);
2760
2761         // Return it
2762         return translateGeneric('POINTS_SUBJECT', $subject);
2763 }
2764
2765 // "Translates" given points account type
2766 function translatePointsAccountType ($accountType) {
2767         // Return it
2768         return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2769 }
2770
2771 // "Translates" given points "locked mode"
2772 function translatePointsLockedMode ($lockedMode) {
2773         // Return it
2774         return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2775 }
2776
2777 // "Translates" given points payment method
2778 function translatePointsPaymentMethod ($paymentMethod) {
2779         // Return it
2780         return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2781 }
2782
2783 // "Translates" given points account provider
2784 function translatePointsAccountProvider ($accountProvider) {
2785         // Return it
2786         return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2787 }
2788
2789 // "Translates" given points notify recipient
2790 function translatePointsNotifyRecipient ($notifyRecipient) {
2791         // Return it
2792         return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2793 }
2794
2795 // "Translates" given mode to a human-readable version
2796 function translatePointsMode ($pointsMode) {
2797         // Return it
2798         return translateGeneric('POINTS_MODE', $pointsMode);
2799 }
2800
2801 // "Translates" task type to a human-readable version
2802 function translateTaskType ($taskType) {
2803         // Return it
2804         return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2805 }
2806
2807 // "Translates" task status to a human-readable version
2808 function translateTaskStatus ($taskStatus) {
2809         // Return it
2810         return translateGeneric('ADMIN_TASK_STATUS', $taskStatus);
2811 }
2812
2813 /*
2814  *-----------------------------------------------------------------------------
2815  * Automatically re-created functions, all taken from user comments on
2816  * www.php.net
2817  *-----------------------------------------------------------------------------
2818  */
2819 if (!function_exists('html_entity_decode')) {
2820         // Taken from documentation on www.php.net
2821         function html_entity_decode ($string) {
2822                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2823                 $trans_tbl = array_flip($trans_tbl);
2824                 return strtr($string, $trans_tbl);
2825         }
2826 } // END - if
2827
2828 // "Calculates" password strength
2829 function calculatePasswordStrength ($password, $configEntry = 'min_password_length') {
2830         // Default score
2831         $score = 1;
2832
2833         if ((strlen($password) < 1) || (strlen($password) < getConfig($configEntry))) {
2834                 // Is to weak
2835                 return 0;
2836         } // END - if
2837
2838         // At least 8 chars long?
2839         if (strlen($password) >= 8) {
2840                 // Add score
2841                 $score++;
2842         } // END - if
2843
2844         // At least 10 chars long?
2845         if (strlen($password) >= 10) {
2846                 // Add score
2847                 $score++;
2848         } // END - if
2849
2850         // Lower and upper cases?
2851         if ((preg_match('/[a-z]/', $password)) && (preg_match('/[A-Z]/', $password))) {
2852                 // Add score
2853                 $score++;
2854         } // END - if
2855
2856         // Also numbers?
2857         if (preg_match('/[0-9]/', $password))  {
2858                 // Add score
2859                 $score++;
2860         } // END - if
2861
2862         // Special characters?
2863         if (preg_match('/.[!,@,#,$,%,^,&,*,?,\/,_,~,+,-,(,)]/', $password)) {
2864                 // Add score
2865                 $score++;
2866         } // END - if
2867
2868         // Return password score
2869         return $score;
2870 }
2871
2872 // "Translates" password strength/score
2873 function translatePasswordStrength ($strength) {
2874         // Return it translated
2875         return '{--PASSWORD_SCORE_' . bigintval($strength) . '--}';
2876 }
2877
2878 // Checks whether given password is strong enough
2879 function isStrongPassword ($password) {
2880         // Determine it
2881         return (calculatePasswordStrength($password) >= getConfig('min_password_score'));
2882 }
2883
2884 // "Getter" for base path from theme
2885 function getBasePathFromTheme ($theme) {
2886         return sprintf('%stheme/%s/css/', getPath(), $theme);
2887 }
2888
2889 // Wrapper to check whether given theme is readable
2890 function isThemeReadable ($theme) {
2891         // Is there cache?
2892         if (!isset($GLOBALS[__FUNCTION__][$theme])) {
2893                 // Determine it
2894                 $GLOBALS[__FUNCTION__][$theme] = (isIncludeReadable(sprintf('theme/%s/theme.php', $theme)));
2895         } // END - if
2896
2897         // Return cache
2898         return $GLOBALS[__FUNCTION__][$theme];
2899 }
2900
2901 // Checks whether a given PHP extension is loaded or can be loaded at runtime
2902 //
2903 // Supported OS: Windows, Linux, (Mac?)
2904 function isPhpExtensionLoaded ($extension) {
2905         // Is the extension loaded?
2906         if (extension_loaded($extension)) {
2907                 // All fine
2908                 return TRUE;
2909         } // END - if
2910
2911         // Try to load the extension
2912         return loadLibrary($extension);
2913 }
2914
2915 // Loads given library (aka. PHP extension)
2916 // Credits: shaunspiller at spammenot-gmail dot com ( http://de.php.net/dl#88566 )
2917 function loadLibrary ($n, $f = NULL) {
2918         return extension_loaded($n) or dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
2919 }
2920
2921 // "Translates" given PHP extension name into a readable version
2922 function translatePhpExtension ($extension) {
2923         // Return the language element
2924         return '{--PHP_EXTENSION_' . strtoupper($extension) . '--}';
2925 }
2926
2927 // [EOF]
2928 ?>