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