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