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