Mailer project rwritten:
[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         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02'))  {
631                 $SWITCH = getOneDay();
632         } // END - if
633
634         // First add years...
635         $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
636
637         // Next months...
638         $ret += $postData[$prefix . '_mo'] * 2628000;
639
640         // Next weeks
641         $ret += $postData[$prefix . '_we'] * 604800;
642
643         // Next days...
644         $ret += $postData[$prefix . '_da'] * 86400;
645
646         // Next hours...
647         $ret += $postData[$prefix . '_ho'] * 3600;
648
649         // Next minutes..
650         $ret += $postData[$prefix . '_mi'] * 60;
651
652         // And at last seconds...
653         $ret += $postData[$prefix . '_se'];
654
655         // Return calculated value
656         return $ret;
657 }
658
659 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
660 function createFancyTime ($stamp) {
661         // Get data array with years/months/weeks/days/...
662         $data = createTimeSelections($stamp, '', '', '', TRUE);
663         $ret = '';
664         foreach ($data as $k => $v) {
665                 if ($v > 0) {
666                         // Value is greater than 0 "eval" data to return string
667                         $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}';
668                         break;
669                 } // END - if
670         } // END - foreach
671
672         // Is something there?
673         if (!empty($ret)) {
674                 // Remove leading commata and space
675                 $ret = substr($ret, 2);
676         } else {
677                 // Zero seconds
678                 $ret = '0 {--TIME_UNIT_SECOND--}';
679         }
680
681         // Return fancy time string
682         return $ret;
683 }
684
685 // Taken from www.php.net isInStringIgnoreCase() user comments
686 function isEmailValid ($email) {
687         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!');
688
689         // Is there cache?
690         if (!isset($GLOBALS[__FUNCTION__][$email])) {
691                 // Check first part of email address
692                 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
693
694                 //  Check domain
695                 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
696
697                 // Generate pattern
698                 $regex = '@^' . $first . '\@' . $domain . '$@iU';
699
700                 // Determine it
701                 $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email)));
702         } // END - if
703
704         // Return check result
705         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!');
706         return $GLOBALS[__FUNCTION__][$email];;
707 }
708
709 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
710 function isUrlValid ($url, $compile = TRUE) {
711         // Trim URL a little
712         $url = trim(urldecode($url));
713         //* DEBUG: */ debugOutput($url);
714
715         // Compile some chars out...
716         if ($compile === TRUE) {
717                 $url = compileUriCode($url, FALSE, FALSE, FALSE);
718         } // END - if
719         //* DEBUG: */ debugOutput($url);
720
721         // Check for the extension filter
722         if (isExtensionActive('filter')) {
723                 // Use the extension's filter set
724                 return FILTER_VALIDATE_URL($url, FALSE);
725         } // END - if
726
727         /*
728          * If not installed, perform a simple test. Just make it sure there is always a
729          * http:// or https:// in front of the URLs.
730          */
731         return isUrlValidSimple($url);
732 }
733
734 // Generate a hash for extra-security for all passwords
735 function generateHash ($plainText, $salt = '', $hash = TRUE) {
736         // Debug output
737         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash));
738
739         // Is the required extension 'sql_patches' there and a salt is not given?
740         // 123                            4                      43    3     4     432    2                  3             32    2                             3                32    2      3     3      21
741         if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) {
742                 // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5
743                 if ($hash === TRUE) {
744                         // Is plain password
745                         return md5($plainText);
746                 } else {
747                         // Is already a hash
748                         return $plainText;
749                 }
750         } // END - if
751
752         // Is an arry element missing here?
753         if (!isConfigEntrySet('file_hash')) {
754                 // Stop here
755                 reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
756         } // END - if
757
758         // When the salt is empty build a new one, else use the first x configured characters as the salt
759         if (empty($salt)) {
760                 // Build server string for more entropy
761                 $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr();
762
763                 // Build key string
764                 $keys   = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt();
765
766                 // Additional data
767                 $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time();
768
769                 // Calculate number for generating the code
770                 $a = time() + getConfig('_ADD') - 1;
771
772                 // Generate SHA1 sum from modula of number and the prime number
773                 $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a);
774                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SHA1=' . $sha1.' ('.strlen($sha1).')');
775                 $sha1 = scrambleString($sha1);
776                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Scrambled=' . $sha1.' ('.strlen($sha1).')');
777                 //* DEBUG: */ $sha1b = descrambleString($sha1);
778                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Descrambled=' . $sha1b.' ('.strlen($sha1b).')');
779
780                 // Generate the password salt string
781                 $salt = substr($sha1, 0, getSaltLength());
782                 //* DEBUG: */ debugOutput($salt.' ('.strlen($salt).')');
783         } else {
784                 // Use given salt
785                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt);
786                 $salt = substr($salt, 0, getSaltLength());
787                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'salt=' . $salt . '(' . strlen($salt) . '/' . getSaltLength() . ')');
788
789                 // Sanity check on salt
790                 if (strlen($salt) != getSaltLength()) {
791                         // Not the same!
792                         reportBug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
793                 } // END - if
794         }
795
796         // Generate final hash (for debug output)
797         $finalHash = $salt . sha1($salt . $plainText);
798
799         // Debug output
800         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'finalHash('.strlen($finalHash).')=' . $finalHash);
801
802         // Return hash
803         return $finalHash;
804 }
805
806 // Scramble a string
807 function scrambleString ($str) {
808         // Init
809         $scrambled = '';
810
811         // Final check, in case of failure it will return unscrambled string
812         if (strlen($str) > 40) {
813                 // The string is to long
814                 return $str;
815         } elseif (strlen($str) == 40) {
816                 // From database
817                 $scrambleNums = explode(':', getPassScramble());
818         } else {
819                 // Generate new numbers
820                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
821         }
822
823         // Compare both lengths and abort if different
824         if (strlen($str) != count($scrambleNums)) {
825                 return $str;
826         } // END - if
827
828         // Scramble string here
829         //* DEBUG: */ debugOutput('***Original=' . $str.'***<br />');
830         for ($idx = 0; $idx < strlen($str); $idx++) {
831                 // Get char on scrambled position
832                 $char = substr($str, $scrambleNums[$idx], 1);
833
834                 // Add it to final output string
835                 $scrambled .= $char;
836         } // END - for
837
838         // Return scrambled string
839         //* DEBUG: */ debugOutput('***Scrambled=' . $scrambled.'***<br />');
840         return $scrambled;
841 }
842
843 // De-scramble a string scrambled by scrambleString()
844 function descrambleString ($str) {
845         // Scramble only 40 chars long strings
846         if (strlen($str) != 40) {
847                 return $str;
848         } // END - if
849
850         // Load numbers from config
851         $scrambleNums = explode(':', getPassScramble());
852
853         // Validate numbers
854         if (count($scrambleNums) != 40) {
855                 return $str;
856         } // END - if
857
858         // Begin descrambling
859         $orig = str_repeat(' ', 40);
860         //* DEBUG: */ debugOutput('+++Scrambled=' . $str.'+++<br />');
861         for ($idx = 0; $idx < 40; $idx++) {
862                 $char = substr($str, $idx, 1);
863                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
864         } // END - for
865
866         // Return scrambled string
867         //* DEBUG: */ debugOutput('+++Original=' . $orig.'+++<br />');
868         return $orig;
869 }
870
871 // Generated a "string" for scrambling
872 function genScrambleString ($len) {
873         // Prepare array for the numbers
874         $scrambleNumbers = array();
875
876         // First we need to setup randomized numbers from 0 to 31
877         for ($idx = 0; $idx < $len; $idx++) {
878                 // Generate number
879                 $rand = mt_rand(0, ($len - 1));
880
881                 // Check for it by creating more numbers
882                 while (array_key_exists($rand, $scrambleNumbers)) {
883                         $rand = mt_rand(0, ($len - 1));
884                 } // END - while
885
886                 // Add number
887                 $scrambleNumbers[$rand] = $rand;
888         } // END - for
889
890         // So let's create the string for storing it in database
891         $scrambleString = implode(':', $scrambleNumbers);
892         return $scrambleString;
893 }
894
895 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
896 function encodeHashForCookie ($passHash) {
897         // Return vanilla password hash
898         $ret = $passHash;
899
900         // Is a secret key and master salt already initialized?
901         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
902         if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
903                 // Only calculate when the secret key is generated
904                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getSecretKey()));
905                 if ((strlen($passHash) != 49) || (strlen(getSecretKey()) != 40)) {
906                         // Both keys must have same length so return unencrypted
907                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getSecretKey()) . '!=40 -  EXIT!');
908                         return $ret;
909                 } // END - if
910
911                 $newHash = ''; $start = 9;
912                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
913                 for ($idx = 0; $idx < 20; $idx++) {
914                         // Get hash parts and convert them (00-FF) to matching ASCII value (0-255)
915                         $part1 = hexdec(substr($passHash     , $start, 2));
916                         $part2 = hexdec(substr(getSecretKey(), $start, 2));
917
918                         // Default is hexadecimal of index if both are same
919                         $mod = dechex($idx);
920                         // Is part1 larger or part2 than its counter part?
921                         if ($part1 > $part2) {
922                                 // part1 is larger
923                                 $mod = dechex(sqrt(($part1 - $part2) * getPrime() / pi()));
924                         } elseif ($part2 > $part1) {
925                                 // part2 is larger
926                                 $mod = dechex(sqrt(($part2 - $part1) * getPrime() / pi()));
927                         }
928
929                         $mod = substr($mod, 0, 2);
930                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
931                         $mod = str_pad($mod, 2, '0', STR_PAD_LEFT);
932                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
933                         $start += 2;
934                         $newHash .= $mod;
935                 } // END - for
936
937                 // Just copy it over, as the master salt is not really helpful here
938                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . '(' . strlen($passHash) . '),' . $newHash . ' (' . strlen($newHash) . ')');
939                 $ret = $newHash;
940         } // END - if
941
942         // Return result
943         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
944         return $ret;
945 }
946
947 // Fix "deleted" cookies
948 function fixDeletedCookies ($cookies) {
949         // Is this an array with entries?
950         if ((is_array($cookies)) && (count($cookies) > 0)) {
951                 // Then check all cookies if they are marked as deleted!
952                 foreach ($cookies as $cookieName) {
953                         // Is the cookie set to "deleted"?
954                         if (getSession($cookieName) == 'deleted') {
955                                 setSession($cookieName, '');
956                         } // END - if
957                 } // END - foreach
958         } // END - if
959 }
960
961 // Checks if a given apache module is loaded
962 function isApacheModuleLoaded ($apacheModule) {
963         // Check it and return result
964         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
965 }
966
967 // Get current theme name
968 function getCurrentTheme () {
969         // The default theme is 'default'... ;-)
970         $ret = 'default';
971
972         // Is there ext-theme installed and active or is 'theme' in URL or POST data?
973         if (isExtensionActive('theme')) {
974                 // Call inner method
975                 $ret = getActualTheme();
976         } elseif ((isPostRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", postRequestElement('theme'))))) {
977                 // Use value from POST data
978                 $ret = postRequestElement('theme');
979         } elseif ((isGetRequestElementSet('theme')) && (isIncludeReadable(sprintf("theme/%s/theme.php", getRequestElement('theme'))))) {
980                 // Use value from GET data
981                 $ret = getRequestElement('theme');
982         } elseif ((isMailerThemeSet()) && (isIncludeReadable(sprintf("theme/%s/theme.php", getMailerTheme())))) {
983                 // Use value from GET data
984                 $ret = getMailerTheme();
985         }
986
987         // Return theme value
988         return $ret;
989 }
990
991 // Generates an error code from given account status
992 function generateErrorCodeFromUserStatus ($status = '') {
993         // If no status is provided, use the default, cached
994         if ((empty($status)) && (isMember())) {
995                 // Get user status
996                 $status = getUserData('status');
997         } // END - if
998
999         // Default error code if unknown account status
1000         $errorCode = getCode('ACCOUNT_UNKNOWN');
1001
1002         // Generate constant name
1003         $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
1004
1005         // Is the constant there?
1006         if (isCodeSet($codeName)) {
1007                 // Then get it!
1008                 $errorCode = getCode($codeName);
1009         } else {
1010                 // Unknown status
1011                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
1012         }
1013
1014         // Return error code
1015         return $errorCode;
1016 }
1017
1018 // Back-ported from the new ship-simu engine. :-)
1019 function debug_get_printable_backtrace () {
1020         // Init variable
1021         $backtrace = '<ol>';
1022
1023         // Get and prepare backtrace for output
1024         $backtraceArray = debug_backtrace();
1025         foreach ($backtraceArray as $key => $trace) {
1026                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1027                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1028                 if (!isset($trace['args'])) $trace['args'] = array();
1029                 $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>';
1030         } // END - foreach
1031
1032         // Close it
1033         $backtrace .= '</ol>';
1034
1035         // Return the backtrace
1036         return $backtrace;
1037 }
1038
1039 // A mail-able backtrace
1040 function debug_get_mailable_backtrace () {
1041         // Init variable
1042         $backtrace = '';
1043
1044         // Get and prepare backtrace for output
1045         $backtraceArray = debug_backtrace();
1046         foreach ($backtraceArray as $key => $trace) {
1047                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
1048                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
1049                 if (!isset($trace['args'])) $trace['args'] = array();
1050                 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
1051         } // END - foreach
1052
1053         // Return the backtrace
1054         return $backtrace;
1055 }
1056
1057 // Generates a ***weak*** seed
1058 function generateSeed () {
1059         return microtime(TRUE) * 100000;
1060 }
1061
1062 // Converts a message code to a human-readable message
1063 function getMessageFromErrorCode ($code) {
1064         // Default is an unknown error code
1065         $message = '{%message,UNKNOWN_ERROR_CODE=' . $code . '%}';
1066
1067         // Which code is provided?
1068         switch ($code) {
1069                 case '':
1070                         // No error code is bad coding practice
1071                         reportBug(__FUNCTION__, __LINE__, 'Empty error code supplied. Please fix your code.');
1072                         break;
1073
1074                 // All error messages
1075                 case getCode('LOGOUT_DONE')         : $message = '{--LOGOUT_DONE--}'; break;
1076                 case getCode('LOGOUT_FAILED')       : $message = '<span class="bad">{--LOGOUT_FAILED--}</span>'; break;
1077                 case getCode('DATA_INVALID')        : $message = '{--MAIL_DATA_INVALID--}'; break;
1078                 case getCode('POSSIBLE_INVALID')    : $message = '{--MAIL_POSSIBLE_INVALID--}'; break;
1079                 case getCode('USER_404')            : $message = '{--USER_404--}'; break;
1080                 case getCode('STATS_404')           : $message = '{--MAIL_STATS_404--}'; break;
1081                 case getCode('ALREADY_CONFIRMED')   : $message = '{--MAIL_ALREADY_CONFIRMED--}'; break;
1082                 case getCode('BEG_SAME_AS_OWN')     : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
1083                 case getCode('LOGIN_FAILED')        : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
1084                 case getCode('MODULE_MEMBER_ONLY')  : $message = '{%message,MODULE_MEMBER_ONLY=' . getRequestElement('mod') . '%}'; break;
1085                 case getCode('OVERLENGTH')          : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
1086                 case getCode('URL_FOUND')           : $message = '{--MEMBER_TEXT_CONTAINS_URL--}'; break;
1087                 case getCode('SUBJECT_URL')         : $message = '{--MEMBER_SUBJECT_CONTAINS_URL--}'; break;
1088                 case getCode('BLIST_URL')           : $message = '{--MEMBER_URL_BLACK_LISTED--}<br />{--MEMBER_BLIST_TIME--}: ' . generateDateTime(getRequestElement('blist'), 0); break;
1089                 case getCode('NO_RECS_LEFT')        : $message = '{--MEMBER_SELECTED_MORE_RECS--}'; break;
1090                 case getCode('INVALID_TAGS')        : $message = '{--MEMBER_HTML_INVALID_TAGS--}'; break;
1091                 case getCode('MORE_POINTS')         : $message = '{--MEMBER_MORE_POINTS_NEEDED--}'; break;
1092                 case getCode('MORE_RECEIVERS1')     : $message = '{--MEMBER_ENTER_MORE_RECEIVERS--}'; break;
1093                 case getCode('MORE_RECEIVERS2')     : $message = '{--MEMBER_NO_MORE_RECEIVERS_FOUND--}'; break;
1094                 case getCode('MORE_RECEIVERS3')     : $message = '{--MEMBER_ENTER_MORE_MIN_RECEIVERS--}'; break;
1095                 case getCode('INVALID_URL')         : $message = '{--MEMBER_ENTER_INVALID_URL--}'; break;
1096                 case getCode('NO_MAIL_TYPE')        : $message = '{--MEMBER_NO_MAIL_TYPE_SELECTED--}'; break;
1097                 case getCode('PROFILE_UPDATED')     : $message = '{--MEMBER_PROFILE_UPDATED--}'; break;
1098                 case getCode('UNKNOWN_REDIRECT')    : $message = '{--UNKNOWN_REDIRECT_VALUE--}'; break;
1099                 case getCode('WRONG_PASS')          : $message = '{--LOGIN_WRONG_PASS--}'; break;
1100                 case getCode('WRONG_ID')            : $message = '{--LOGIN_WRONG_ID--}'; break;
1101                 case getCode('ACCOUNT_LOCKED')      : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
1102                 case getCode('ACCOUNT_UNCONFIRMED') : $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
1103                 case getCode('COOKIES_DISABLED')    : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
1104                 case getCode('UNKNOWN_ERROR')       : $message = '{--LOGIN_UNKNOWN_ERROR--}'; break;
1105                 case getCode('UNKNOWN_STATUS')      : $message = '{--LOGIN_UNKNOWN_STATUS--}'; break;
1106                 case getCode('LOGIN_EMPTY_ID')      : $message = '{--LOGIN_ID_IS_EMPTY--}'; break;
1107                 case getCode('LOGIN_EMPTY_PASSWORD'): $message = '{--LOGIN_PASSWORD_IS_EMPTY--}'; break;
1108
1109                 case getCode('ERROR_MAILID'):
1110                         if (isExtensionActive('mailid', TRUE)) {
1111                                 $message = '{--ERROR_CONFIRMING_MAIL--}';
1112                         } else {
1113                                 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=mailid%}';
1114                         }
1115                         break;
1116
1117                 case getCode('EXTENSION_PROBLEM'):
1118                         if (isGetRequestElementSet('ext')) {
1119                                 $message = '{%pipe,generateExtensionInactiveNotInstalledMessage=' . getRequestElement('ext') . '%}';
1120                         } else {
1121                                 $message = '{--EXTENSION_PROBLEM_UNSET_EXT--}';
1122                         }
1123                         break;
1124
1125                 case getCode('URL_TIME_LOCK'):
1126                         // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
1127                         $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
1128                                 array(bigintval(getRequestElement('id'))), __FUNCTION__, __LINE__);
1129
1130                         // Load timestamp from last order
1131                         $content = SQL_FETCHARRAY($result);
1132
1133                         // Free memory
1134                         SQL_FREERESULT($result);
1135
1136                         // Translate it for templates
1137                         $content['timestamp'] = generateDateTime($content['timestamp'], 1);
1138
1139                         // Calculate hours...
1140                         $content['hours'] = round(getUrlTlock() / 60 / 60);
1141
1142                         // Minutes...
1143                         $content['minutes'] = round((getUrlTlock() - $content['hours'] * 60 * 60) / 60);
1144
1145                         // And seconds
1146                         $content['seconds'] = round(getUrlTlock() - $content['hours'] * 60 * 60 - $content['minutes'] * 60);
1147
1148                         // Finally contruct the message
1149                         $message = loadTemplate('tlock_message', TRUE, $content);
1150                         break;
1151
1152                 default:
1153                         // Log missing/invalid error codes
1154                         logDebugMessage(__FUNCTION__, __LINE__, getMessage('UNKNOWN_MAILID_CODE', $code));
1155                         break;
1156         } // END - switch
1157
1158         // Return the message
1159         return $message;
1160 }
1161
1162 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
1163 function isUrlValidSimple ($url) {
1164         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - ENTERED!');
1165         // Prepare URL
1166         $url = secureString(str_replace(chr(92), '', compileRawCode(urldecode($url))));
1167
1168         // Allows http and https
1169         $http      = "(http|https)+(:\/\/)";
1170         // Test domain
1171         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
1172         // Test double-domains (e.g. .de.vu)
1173         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
1174         // Test IP number
1175         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
1176         // ... directory
1177         $dir       = "((/)+([-_\.[:alnum:]])+)*";
1178         // ... page
1179         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
1180         // ... and the string after and including question character
1181         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
1182         // Pattern for URLs like http://url/dir/doc.html?var=value
1183         $pattern['d1dpg1']  = $http . $domain1 . $dir . $page . $getstring1;
1184         $pattern['d2dpg1']  = $http . $domain2 . $dir . $page . $getstring1;
1185         $pattern['ipdpg1']  = $http . $ip . $dir . $page . $getstring1;
1186         // Pattern for URLs like http://url/dir/?var=value
1187         $pattern['d1dg1']  = $http . $domain1 . $dir.'/' . $getstring1;
1188         $pattern['d2dg1']  = $http . $domain2 . $dir.'/' . $getstring1;
1189         $pattern['ipdg1']  = $http . $ip . $dir.'/' . $getstring1;
1190         // Pattern for URLs like http://url/dir/page.ext
1191         $pattern['d1dp']  = $http . $domain1 . $dir . $page;
1192         $pattern['d1dp']  = $http . $domain2 . $dir . $page;
1193         $pattern['ipdp']  = $http . $ip . $dir . $page;
1194         // Pattern for URLs like http://url/dir
1195         $pattern['d1d']  = $http . $domain1 . $dir;
1196         $pattern['d2d']  = $http . $domain2 . $dir;
1197         $pattern['ipd']  = $http . $ip . $dir;
1198         // Pattern for URLs like http://url/?var=value
1199         $pattern['d1g1']  = $http . $domain1 . '/' . $getstring1;
1200         $pattern['d2g1']  = $http . $domain2 . '/' . $getstring1;
1201         $pattern['ipg1']  = $http . $ip . '/' . $getstring1;
1202         // Pattern for URLs like http://url?var=value
1203         $pattern['d1g12']  = $http . $domain1 . $getstring1;
1204         $pattern['d2g12']  = $http . $domain2 . $getstring1;
1205         $pattern['ipg12']  = $http . $ip . $getstring1;
1206
1207         // Test all patterns
1208         $reg = FALSE;
1209         foreach ($pattern as $key => $pat) {
1210                 // Debug regex?
1211                 if (isDebugRegularExpressionEnabled()) {
1212                         // @TODO Are these convertions still required?
1213                         $pat = str_replace('.', '&#92;&#46;', $pat);
1214                         $pat = str_replace('@', '&#92;&#64;', $pat);
1215                         //* DEBUG: */ debugOutput($key . '=&nbsp;' . $pat);
1216                 } // END - if
1217
1218                 // Check if expression matches
1219                 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
1220
1221                 // Does it match?
1222                 if ($reg === TRUE) {
1223                         break;
1224                 } // END - if
1225         } // END - foreach
1226
1227         // Return true/false
1228         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',reg=' . intval($reg) . ' - EXIT!');
1229         return $reg;
1230 }
1231
1232 // Wtites data to a config.php-style file
1233 // @TODO Rewrite this function to use readFromFile() and writeToFile()
1234 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek = 0) {
1235         // Initialize some variables
1236         $done = FALSE;
1237         $seek++;
1238         $next  = -1;
1239         $found = FALSE;
1240
1241         // Is the file there and read-/write-able?
1242         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
1243                 $search = 'CFG: ' . $comment;
1244                 $tmp = $FQFN . '.tmp';
1245
1246                 // Open the source file
1247                 $fp = fopen($FQFN, 'r') or reportBug(__FUNCTION__, __LINE__, 'Cannot read. file=' . basename($FQFN));
1248
1249                 // Is the resource valid?
1250                 if (is_resource($fp)) {
1251                         // Open temporary file
1252                         $fp_tmp = fopen($tmp, 'w') or reportBug(__FUNCTION__, __LINE__, 'Cannot write. tmp=' . basename($tmp) . ',file=' . $FQFN);
1253
1254                         // Is the resource again valid?
1255                         if (is_resource($fp_tmp)) {
1256                                 // Mark temporary file as readable
1257                                 $GLOBALS['file_readable'][$tmp] = TRUE;
1258
1259                                 // Start reading
1260                                 while (!feof($fp)) {
1261                                         // Read from source file
1262                                         $line = fgets($fp, 1024);
1263
1264                                         if (isInString($search, $line)) {
1265                                                 $next = '0';
1266                                                 $found = TRUE;
1267                                         } // END - if
1268
1269                                         if ($next > -1) {
1270                                                 if ($next === $seek) {
1271                                                         $next = -1;
1272                                                         $line = $prefix . $inserted . $suffix . PHP_EOL;
1273                                                 } else {
1274                                                         $next++;
1275                                                 }
1276                                         } // END - if
1277
1278                                         // Write to temp file
1279                                         fwrite($fp_tmp, $line);
1280                                 } // END - while
1281
1282                                 // Close temp file
1283                                 fclose($fp_tmp);
1284
1285                                 // Finished writing tmp file
1286                                 $done = TRUE;
1287                         } // END - if
1288
1289                         // Close source file
1290                         fclose($fp);
1291
1292                         if (($done === TRUE) && ($found === TRUE)) {
1293                                 // Copy back temporary->FQFN file and ...
1294                                 copyFileVerified($tmp, $FQFN, 0644);
1295
1296                                 // ... delete temporay file :-)
1297                                 return removeFile($tmp);
1298                         } elseif ($found === FALSE) {
1299                                 // Entry not found
1300                                 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!');
1301                         } else {
1302                                 // Temporary file not fully written
1303                                 logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - Temporary file unfinished!');
1304                         }
1305                 }
1306         } else {
1307                 // File not found, not readable or writeable
1308                 reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN) . ',comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek);
1309         }
1310
1311         // An error was detected!
1312         return FALSE;
1313 }
1314
1315 // Debug message logger
1316 function logDebugMessage ($funcFile, $line, $message, $force=true) {
1317         // Is debug mode enabled?
1318         if ((isDebugModeEnabled()) || ($force === TRUE)) {
1319                 // Remove CRLF
1320                 $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message);
1321
1322                 // Log this message away
1323                 appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message);
1324         } // END - if
1325 }
1326
1327 // Handle extra values
1328 function handleExtraValues ($filterFunction, $value, $extraValue) {
1329         // Default is the value itself
1330         $ret = $value;
1331
1332         // Is there a special filter function?
1333         if ((empty($filterFunction)) || (!function_exists($filterFunction))) {
1334                 // Call-back function does not exist or is empty
1335                 reportBug(__FUNCTION__, __LINE__, 'Filter function ' . $filterFunction . ' does not exist or is empty: value[' . gettype($value) . ']=' . $value . ',extraValue[' . gettype($extraValue) . ']=' . $extraValue);
1336         } // END - if
1337
1338         // Is there extra parameters here?
1339         if ((!is_null($extraValue)) && (!empty($extraValue))) {
1340                 // Put both parameters in one new array by default
1341                 $args = array($value, $extraValue);
1342
1343                 // If we have an array simply use it and pre-extend it with our value
1344                 if (is_array($extraValue)) {
1345                         // Make the new args array
1346                         $args = merge_array(array($value), $extraValue);
1347                 } // END - if
1348
1349                 // Call the multi-parameter call-back
1350                 $ret = call_user_func_array($filterFunction, $args);
1351
1352                 // Is $ret 'true'?
1353                 if ($ret === TRUE) {
1354                         // Test passed, so write direct value
1355                         $ret = $args;
1356                 } // END - if
1357         } else {
1358                 // One parameter call
1359                 $ret = call_user_func($filterFunction, $value);
1360                 //* BUG */ die('ret['.gettype($ret).']=' . $ret . ',value=' . $value.',filterFunction=' . $filterFunction);
1361
1362                 // Is $ret 'true'?
1363                 if ($ret === TRUE) {
1364                         // Test passed, so write direct value
1365                         $ret = $value;
1366                 } // END - if
1367         }
1368
1369         // Return the value
1370         return $ret;
1371 }
1372
1373 // Tries to determine if call-back functions and/or extra values shall be parsed
1374 function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) {
1375         // Debug mode enabled?
1376         if (isDebugModeEnabled()) {
1377                 // Debug message
1378                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE));
1379         } // END - if
1380
1381         // Send data through the filter function if found
1382         if ($key === $userIdColumn[0]) {
1383                 // Is the userid, we have to process it with convertZeroToNull()
1384                 $entries = convertZeroToNull($entries);
1385         } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1386                 // Debug mode enabled?
1387                 if (isDebugModeEnabled()) {
1388                         // Then log it
1389                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1390                 } // END - if
1391
1392                 // Filter function + extra value set
1393                 $entries = handleExtraValues($filterFunctions[$key], $entries, $extraValues[$key]);
1394
1395                 // Debug mode enabled?
1396                 if (isDebugModeEnabled()) {
1397                         // Then log it
1398                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1399                 } // END - if
1400         } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) {
1401                 // Debug mode enabled?
1402                 if (isDebugModeEnabled()) {
1403                         // Then log it
1404                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1405                 } // END - if
1406
1407                 // Handle extra values
1408                 $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]);
1409
1410                 // Debug mode enabled?
1411                 if (isDebugModeEnabled()) {
1412                         // Then log it
1413                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1414                 } // END - if
1415
1416                 // Make sure entries is not bool, then something went wrong
1417                 assert(!is_bool($entries));
1418         } elseif (!empty($filterFunctions[$search])) {
1419                 // Debug mode enabled?
1420                 if (isDebugModeEnabled()) {
1421                         // Then log it
1422                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!');
1423                 } // END - if
1424
1425                 // Handle extra values
1426                 $entries = handleExtraValues($filterFunctions[$search], $entries, NULL);
1427
1428                 // Debug mode enabled?
1429                 if (isDebugModeEnabled()) {
1430                         // Then log it
1431                         /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!');
1432                 } // END - if
1433
1434                 // Make sure entries is not bool, then something went wrong
1435                 assert(!is_bool($entries));
1436         }
1437
1438         // Return value
1439         return $entries;
1440 }
1441
1442 // Converts timestamp selections into a timestamp
1443 function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id, &$skip) {
1444         // Init test variable
1445         $skip  = FALSE;
1446         $test2 = '';
1447
1448         // Get last three chars
1449         $test = substr($id, -3);
1450
1451         // Improved way of checking! :-)
1452         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
1453                 // Found a multi-selection for timings?
1454                 $test = substr($id, 0, -3);
1455                 if ((isset($postData[$test . '_ye'])) && (isset($postData[$test . '_mo'])) && (isset($postData[$test . '_we'])) && (isset($postData[$test . '_da'])) && (isset($postData[$test . '_ho'])) && (isset($postData[$test . '_mi'])) && (isset($postData[$test . '_se'])) && ($test != $test2)) {
1456                         // Generate timestamp
1457                         $postData[$test] = createEpocheTimeFromSelections($test, $postData);
1458                         array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
1459                         $GLOBALS['skip_config'][$test] = TRUE;
1460
1461                         // Remove data from array
1462                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
1463                                 unset($postData[$test . '_' . $rem]);
1464                         } // END - foreach
1465
1466                         // Skip adding
1467                         unset($id);
1468                         $skip = TRUE;
1469                         $test2 = $test;
1470                 } // END - if
1471         } // END - if
1472 }
1473
1474 // Reverts the german decimal comma into Computer decimal dot
1475 // OPPOMENT: translateComma()
1476 function convertCommaToDot ($str) {
1477         // Default float is not a float... ;-)
1478         $float = FALSE;
1479
1480         // Which language is selected?
1481         switch (getLanguage()) {
1482                 case 'de': // German language
1483                         // Remove german thousand dots first
1484                         $str = str_replace('.', '', $str);
1485
1486                         // Replace german commata with decimal dot and cast it
1487                         $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str));
1488                         break;
1489
1490                 default: // US and so on
1491                         // Remove thousand commatas first and cast
1492                         $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str));
1493                         break;
1494         } // END - switch
1495
1496         // Return float
1497         return $float;
1498 }
1499
1500 // Handle menu-depending failed logins and return the rendered content
1501 function handleLoginFailures ($accessLevel) {
1502         // Default output is empty ;-)
1503         $OUT = '';
1504
1505         // Is the session data set?
1506         if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
1507                 // Ignore zero values
1508                 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
1509                         // Non-guest has login failures found, get both data and prepare it for template
1510                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'accessLevel=' . $accessLevel . '<br />');
1511                         $content = array(
1512                                 'login_failures' => 'mailer_' . $accessLevel . '_failures',
1513                                 'last_failure'   => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
1514                         );
1515
1516                         // Load template
1517                         $OUT = loadTemplate('login_failures', TRUE, $content);
1518                 } // END - if
1519
1520                 // Reset session data
1521                 setSession('mailer_' . $accessLevel . '_failures', '');
1522                 setSession('mailer_' . $accessLevel . '_last_failure', '');
1523         } // END - if
1524
1525         // Return rendered content
1526         return $OUT;
1527 }
1528
1529 // Rebuild cache
1530 function rebuildCache ($cache, $inc = '', $force = FALSE) {
1531         // Debug message
1532         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
1533
1534         // Shall I remove the cache file?
1535         if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
1536                 // Rebuild cache only in HTML output-mode
1537                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
1538                         // Destroy it
1539                         $GLOBALS['cache_instance']->removeCacheFile($force);
1540                 } // END - if
1541
1542                 // Include file given?
1543                 if (!empty($inc)) {
1544                         // Construct FQFN
1545                         $inc = sprintf("inc/loader/load-%s.php", $inc);
1546
1547                         // Is the include there?
1548                         if (isIncludeReadable($inc)) {
1549                                 // And rebuild it from scratch
1550                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inc=' . $inc . ' - LOADED!');
1551                                 loadInclude($inc);
1552                         } else {
1553                                 // Include not found
1554                                 logDebugMessage(__FUNCTION__, __LINE__, 'Include ' . $inc . ' not found. cache=' . $cache);
1555                         }
1556                 } // END - if
1557         } // END - if
1558 }
1559
1560 // Determines the real remote address
1561 function determineRealRemoteAddress ($remoteAddr = FALSE) {
1562         // Default is 127.0.0.1
1563         $address = '127.0.0.1';
1564
1565         // Is a proxy in use?
1566         if ((isset($_SERVER['HTTP_X_FORWARDED_FOR'])) && (!$remoteAddr)) {
1567                 // Proxy was used
1568                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
1569         } elseif ((isset($_SERVER['HTTP_CLIENT_IP'])) && (!$remoteAddr)) {
1570                 // Yet, another proxy
1571                 $address = $_SERVER['HTTP_CLIENT_IP'];
1572         } elseif (isset($_SERVER['REMOTE_ADDR'])) {
1573                 // The regular address when no proxy was used
1574                 $address = $_SERVER['REMOTE_ADDR'];
1575         }
1576
1577         // This strips out the real address from proxy output
1578         if (strstr($address, ',')) {
1579                 $addressArray = explode(',', $address);
1580                 $address = $addressArray[0];
1581         } // END - if
1582
1583         // Return the result
1584         return $address;
1585 }
1586
1587 // Adds a bonus mail to the queue
1588 // This is a high-level function!
1589 function addNewBonusMail ($data, $mode = '', $output = TRUE) {
1590         // Use mode from data if not set and availble ;-)
1591         if ((empty($mode)) && (isset($data['mail_mode']))) {
1592                 $mode = $data['mail_mode'];
1593         } // END - if
1594
1595         // Generate receiver list
1596         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
1597
1598         // Receivers added?
1599         if (!empty($receiver)) {
1600                 // Add bonus mail to queue
1601                 addBonusMailToQueue(
1602                         $data['subject'],
1603                         $data['text'],
1604                         $receiver,
1605                         $data['points'],
1606                         $data['seconds'],
1607                         $data['url'],
1608                         $data['cat'],
1609                         $mode,
1610                         $data['receiver']
1611                 );
1612
1613                 // Mail inserted into bonus pool
1614                 if ($output === TRUE) {
1615                         displayMessage('{--ADMIN_BONUS_SEND--}');
1616                 } // END - if
1617         } elseif ($output === TRUE) {
1618                 // More entered than can be reached!
1619                 displayMessage('{--ADMIN_MORE_SELECTED--}');
1620         } else {
1621                 // Debug log
1622                 logDebugMessage(__FUNCTION__, __LINE__, 'cat=' . $data['cat'] . ',receiver=' . $data['receiver'] . ',data=' . base64_encode(serialize($data)) . ' More selected, than available!');
1623         }
1624 }
1625
1626 // Enables the reset mode and runs it
1627 function doReset () {
1628         // Enable the reset mode
1629         $GLOBALS['reset_enabled'] = TRUE;
1630
1631         // Run filters
1632         runFilterChain('reset');
1633 }
1634
1635 // Enables the reset mode (hourly, weekly and monthly) and runs it
1636 function doHourly () {
1637         // Enable the hourly reset mode
1638         $GLOBALS['hourly_enabled'] = TRUE;
1639
1640         // Run filters (one always!)
1641         runFilterChain('hourly');
1642 }
1643
1644 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1645 function doShutdown () {
1646         // Call the filter chain 'shutdown'
1647         runFilterChain('shutdown', NULL);
1648
1649         // Check if link is up
1650         if (SQL_IS_LINK_UP()) {
1651                 // Close link
1652                 SQL_CLOSE(__FUNCTION__, __LINE__);
1653         } elseif (!isInstallationPhase()) {
1654                 // No database link
1655                 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1656         }
1657
1658         // Stop executing here
1659         exit;
1660 }
1661
1662 // Init member id
1663 function initMemberId () {
1664         $GLOBALS['member_id'] = '0';
1665 }
1666
1667 // Setter for member id
1668 function setMemberId ($memberId) {
1669         // We should not set member id to zero
1670         if (!isValidId($memberId)) {
1671                 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1672         } // END - if
1673
1674         // Set it secured
1675         $GLOBALS['member_id'] = bigintval($memberId);
1676 }
1677
1678 // Getter for member id or returns zero
1679 function getMemberId () {
1680         // Default member id
1681         $memberId = '0';
1682
1683         // Is the member id set?
1684         if (isMemberIdSet()) {
1685                 // Then use it
1686                 $memberId = $GLOBALS['member_id'];
1687         } // END - if
1688
1689         // Return it
1690         return $memberId;
1691 }
1692
1693 // Checks ether the member id is set
1694 function isMemberIdSet () {
1695         return (isset($GLOBALS['member_id']));
1696 }
1697
1698 // Setter for extra title
1699 function setExtraTitle ($extraTitle) {
1700         $GLOBALS['extra_title'] = $extraTitle;
1701 }
1702
1703 // Getter for extra title
1704 function getExtraTitle () {
1705         // Is the extra title set?
1706         if (!isExtraTitleSet()) {
1707                 // No, then abort here
1708                 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1709         } // END - if
1710
1711         // Return it
1712         return $GLOBALS['extra_title'];
1713 }
1714
1715 // Checks if the extra title is set
1716 function isExtraTitleSet () {
1717         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1718 }
1719
1720 /**
1721  * Reads a directory recursively by default and searches for files not matching
1722  * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1723  * a whole directory.
1724  *
1725  * @param       $baseDir                        Relative base directory to PATH to scan from
1726  * @param       $prefix                         Prefix for all positive matches (which files should be found)
1727  * @param       $fileIncludeDirs        whether to include directories in the final output array
1728  * @param       $addBaseDir                     whether to add $baseDir to all array entries
1729  * @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'
1730  * @param       $extension                      File extension for all positive matches
1731  * @param       $excludePattern         Regular expression to exclude more files (preg_match())
1732  * @param       $recursive                      whether to scan recursively
1733  * @param       $suffix                         Suffix for positive matches ($extension will be appended, too)
1734  * @return      $foundMatches           All found positive matches for above criteria
1735  */
1736 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
1737         // Add default entries we should always exclude
1738         array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1739
1740         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1741         // Init found includes
1742         $foundMatches = array();
1743
1744         // Open directory
1745         $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1746
1747         // Read all entries
1748         while ($baseFile = readdir($dirPointer)) {
1749                 // Exclude '.', '..' and entries in $excludeArray automatically
1750                 if (in_array($baseFile, $excludeArray, TRUE))  {
1751                         // Exclude them
1752                         //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1753                         continue;
1754                 } // END - if
1755
1756                 // Construct include filename and FQFN
1757                 $fileName = $baseDir . $baseFile;
1758                 $FQFN = getPath() . $fileName;
1759
1760                 // Remove double slashes
1761                 $FQFN = str_replace('//', '/', $FQFN);
1762
1763                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1764                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1765                         // Debug message
1766                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1767
1768                         // Exclude this one
1769                         continue;
1770                 } // END - if
1771
1772                 // Skip also files with non-matching prefix genericly
1773                 if (($recursive === TRUE) && (isDirectory($FQFN))) {
1774                         // Is a redirectory so read it as well
1775                         $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1776
1777                         // And skip further processing
1778                         continue;
1779                 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1780                         // Skip this file
1781                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1782                         continue;
1783                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1784                         // Skip wrong suffix as well
1785                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1786                         continue;
1787                 } elseif (!isFileReadable($FQFN)) {
1788                         // Not readable so skip it
1789                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1790                 } elseif (filesize($FQFN) < 50) {
1791                         // Might be deprecated
1792                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1793                         continue;
1794                 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1795                         // This PHP script is deprecated
1796                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1797                         continue;
1798                 }
1799
1800                 // Get file' extension (last 4 chars)
1801                 $fileExtension = substr($baseFile, -4, 4);
1802
1803                 // Is the file a PHP script or other?
1804                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1805                 if (($fileExtension == '.php') || (($fileIncludeDirs === TRUE) && (isDirectory($FQFN)))) {
1806                         // Is this a valid include file?
1807                         if ($extension == '.php') {
1808                                 // Remove both for extension name
1809                                 $extName = substr($baseFile, strlen($prefix), -4);
1810
1811                                 // Add file with or without base path
1812                                 if ($addBaseDir === TRUE) {
1813                                         // With base path
1814                                         array_push($foundMatches, $fileName);
1815                                 } else {
1816                                         // No base path
1817                                         array_push($foundMatches, $baseFile);
1818                                 }
1819                         } else {
1820                                 // We found .php file but should not search for them, why?
1821                                 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1822                         }
1823                 } elseif ($fileExtension == $extension) {
1824                         // Other, generic file found
1825                         array_push($foundMatches, $fileName);
1826                 }
1827         } // END - while
1828
1829         // Close directory
1830         closedir($dirPointer);
1831
1832         // Sort array
1833         sort($foundMatches);
1834
1835         // Return array with include files
1836         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1837         return $foundMatches;
1838 }
1839
1840 // Checks whether $prefix is found in $fileName
1841 function isFilePrefixFound ($fileName, $prefix) {
1842         // @TODO Find a way to cache this
1843         return (substr($fileName, 0, strlen($prefix)) == $prefix);
1844 }
1845
1846 // Maps a module name into a database table name
1847 function mapModuleToTable ($moduleName) {
1848         // Map only these, still lame code...
1849         switch ($moduleName) {
1850                 case 'index': // 'index' is the guest's menu
1851                         $moduleName = 'guest'; 
1852                         break;
1853
1854                 case 'login': // ... and 'login' the member's menu
1855                         $moduleName = 'member';
1856                         break;
1857                 // Anything else will not be mapped, silently.
1858         } // END - switch
1859
1860         // Return result
1861         return $moduleName;
1862 }
1863
1864 // Add SQL debug data to array for later output
1865 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1866         // Is there cache?
1867         if (!isset($GLOBALS['debug_sql_available'])) {
1868                 // Check it and cache it in $GLOBALS
1869                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1870         } // END - if
1871         
1872         // Don't execute anything here if we don't need or ext-other is missing
1873         if ($GLOBALS['debug_sql_available'] === FALSE) {
1874                 return;
1875         } // END - if
1876
1877         // Already executed?
1878         if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1879                 // Then abort here, we don't need to profile a query twice
1880                 return;
1881         } // END - if
1882
1883         // Remeber this as profiled (or not, but we don't care here)
1884         $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
1885
1886         // Generate record
1887         $record = array(
1888                 'num_rows' => SQL_NUMROWS($result),
1889                 'affected' => SQL_AFFECTEDROWS(),
1890                 'sql_str'  => $sqlString,
1891                 'timing'   => $timing,
1892                 'file'     => basename($F),
1893                 'line'     => $L
1894         );
1895
1896         // Add it
1897         array_push($GLOBALS['debug_sqls'], $record);
1898 }
1899
1900 // Initializes the cache instance
1901 function initCacheInstance () {
1902         // Check for double-initialization
1903         if (isset($GLOBALS['cache_instance'])) {
1904                 // This should not happen and must be fixed
1905                 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1906         } // END - if
1907
1908         // Load include for CacheSystem class
1909         loadIncludeOnce('inc/classes/cachesystem.class.php');
1910
1911         // Initialize cache system only when it's needed
1912         $GLOBALS['cache_instance'] = new CacheSystem();
1913
1914         // Did it work?
1915         if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1916                 // Failed to initialize cache sustem
1917                 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1918         } // END - if
1919 }
1920
1921 // Getter for message from array or raw message
1922 function getMessageFromIndexedArray ($message, $pos, $array) {
1923         // Check if the requested message was found in array
1924         if (isset($array[$pos])) {
1925                 // ... if yes then use it!
1926                 $ret = $array[$pos];
1927         } else {
1928                 // ... else use default message
1929                 $ret = $message;
1930         }
1931
1932         // Return result
1933         return $ret;
1934 }
1935
1936 // Convert ';' to ', ' for e.g. receiver list
1937 function convertReceivers ($old) {
1938         return str_replace(';', ', ', $old);
1939 }
1940
1941 // Get a module from filename and access level
1942 function getModuleFromFileName ($file, $accessLevel) {
1943         // Default is 'invalid';
1944         $modCheck = 'invalid';
1945
1946         // @TODO This is still very static, rewrite it somehow
1947         switch ($accessLevel) {
1948                 case 'admin':
1949                         $modCheck = 'admin';
1950                         break;
1951
1952                 case 'sponsor':
1953                 case 'guest':
1954                 case 'member':
1955                         $modCheck = getModule();
1956                         break;
1957
1958                 default: // Unsupported file name / access level
1959                         reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1960                         break;
1961         } // END - switch
1962
1963         // Return result
1964         return $modCheck;
1965 }
1966
1967 // Encodes an URL for adding session id, etc.
1968 function encodeUrl ($url, $outputMode = '0') {
1969         // Is there already have a PHPSESSID inside or view.php is called? Then abort here
1970         if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1971                 // Raw output mode detected or session_name() found in URL
1972                 return $url;
1973         } // END - if
1974
1975         // Is there a valid session?
1976         if ((!isSessionValid()) && (!isSpider())) {
1977                 // Determine right separator
1978                 $separator = '&amp;';
1979                 if (!isInString('?', $url)) {
1980                         // No question mark
1981                         $separator = '?';
1982                 } // END - if
1983
1984                 // Then add it to URL
1985                 $url .= $separator . session_name() . '=' . session_id();
1986         } // END - if
1987
1988         // Add {?URL?} ?
1989         if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1990                 // Add it
1991                 $url = '{?URL?}/' . $url;
1992         } // END - if
1993
1994         // Debug message
1995         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
1996
1997         // Is there to decode entities?
1998         if (!isHtmlOutputMode()) {
1999                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
2000                 // Decode them for e.g. JavaScript parts
2001                 $url = decodeEntities($url);
2002                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - AFTER DECODING');
2003         } // END - if
2004
2005         // Debug log
2006         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
2007
2008         // Return the encoded URL
2009         return $url;
2010 }
2011
2012 // Simple check for spider
2013 function isSpider () {
2014         // Get the UA and trim it down
2015         $userAgent = trim(detectUserAgent(TRUE));
2016
2017         // It should not be empty, if so it is better a browser
2018         if (empty($userAgent)) {
2019                 // It is a browser that blocks its UA string
2020                 return FALSE;
2021         } // END - if
2022
2023         // Is it a spider?
2024         return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
2025 }
2026
2027 // Function to search for the last modified file
2028 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
2029         // Get dir as array
2030         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
2031         // Does it match what we are looking for? (We skip a lot files already!)
2032         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
2033         $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2034
2035         $ds = getArrayFromDirectory($dir, '', FALSE, TRUE, array(), '.php', $excludePattern);
2036         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
2037
2038         // Walk through all entries
2039         foreach ($ds as $d) {
2040                 // Generate proper FQFN
2041                 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
2042
2043                 // Is it a file and readable?
2044                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
2045                 if (isFileReadable($FQFN)) {
2046                         // $FQFN is a readable file so extract the requested data from it
2047                         $check = extractRevisionInfoFromFile($FQFN, $lookFor);
2048                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
2049
2050                         // Is the file more recent?
2051                         if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
2052                                 // This file is newer as the file before
2053                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
2054                                 $last_changed['path_name'] = $FQFN;
2055                                 $last_changed[$lookFor] = $check;
2056                         } // END - if
2057                 } else {
2058                         // Not readable
2059                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
2060                 }
2061         } // END - foreach
2062 }
2063
2064 // Handles the braces [] of a field (e.g. value of 'name' attribute)
2065 function handleFieldWithBraces ($field) {
2066         // Are there braces [] at the end?
2067         if (substr($field, -2, 2) == '[]') {
2068                 /*
2069                  * Try to find one and replace it. I do it this way to allow easy
2070                  * extending of this code.
2071                  */
2072                 foreach (array('admin_list_builder_id_value') as $key) {
2073                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
2074                         // Is the cache entry set?
2075                         if (isset($GLOBALS[$key])) {
2076                                 // Insert it
2077                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
2078
2079                                 // And abort
2080                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
2081                                 break;
2082                         } // END - if
2083                 } // END - foreach
2084         } // END - if
2085
2086         // Return it
2087         return $field;
2088 }
2089
2090 // Converts a zero or NULL to word 'NULL'
2091 function convertZeroToNull ($number) {
2092         // Is it a valid username?
2093         if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
2094                 // Always secure it
2095                 $number = bigintval($number);
2096         } else {
2097                 // Is not valid or zero
2098                 $number = 'NULL';
2099         }
2100
2101         // Return it
2102         return $number;
2103 }
2104
2105 // Converts a NULL|empty string|< 1 to zero
2106 function convertNullToZero ($number) {
2107         // Is it a valid username?
2108         if ((is_null($number)) || (empty($number)) || ($number < 1)) {
2109                 // Is not valid or zero
2110                 $number = '0';
2111         } // END - if
2112
2113         // Return it
2114         return $number;
2115 }
2116
2117 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
2118 // Note: This function is cached
2119 function capitalizeUnderscoreString ($str) {
2120         // Is there cache?
2121         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2122                 // Init target string
2123                 $capitalized = '';
2124
2125                 // Explode it with the underscore, but rewrite dashes to underscore before
2126                 $strArray = explode('_', str_replace('-', '_', $str));
2127
2128                 // "Walk" through all elements and make them lower-case but first upper-case
2129                 foreach ($strArray as $part) {
2130                         // Capitalize the string part
2131                         $capitalized .= firstCharUpperCase($part);
2132                 } // END - foreach
2133
2134                 // Store the converted string in cache array
2135                 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2136         } // END - if
2137
2138         // Return cache
2139         return $GLOBALS[__FUNCTION__][$str];
2140 }
2141
2142 // Generate admin links for mail order
2143 // mailType can be: 'mid' or 'bid'
2144 function generateAdminMailLinks ($mailType, $mailId) {
2145         // Init variables
2146         $OUT = '';
2147         $table = '';
2148
2149         // Default column for mail status is 'data_type'
2150         // @TODO Rename column data_type to e.g. mail_status
2151         $statusColumn = 'data_type';
2152
2153         // Which mail do we have?
2154         switch ($mailType) {
2155                 case 'bid': // Bonus mail
2156                         $table = 'bonus';
2157                         break;
2158
2159                 case 'mid': // Member mail
2160                         $table = 'pool';
2161                         break;
2162
2163                 default: // Handle unsupported types
2164                         logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2165                         $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2166                         break;
2167         } // END - switch
2168
2169         // Is the mail type supported?
2170         if (!empty($table)) {
2171                 // Query for the mail
2172                 $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2173                         array(
2174                                 $statusColumn,
2175                                 $table,
2176                                 bigintval($mailId)
2177                         ), __FILE__, __LINE__);
2178
2179                 // Is there one entry there?
2180                 if (SQL_NUMROWS($result) == 1) {
2181                         // Load the entry
2182                         $content = SQL_FETCHARRAY($result);
2183
2184                         // Add output and type
2185                         $content['type']     = $mailType;
2186                         $content['__output'] = '';
2187
2188                         // Filter all data
2189                         $content = runFilterChain('generate_admin_mail_links', $content);
2190
2191                         // Get output back
2192                         $OUT = $content['__output'];
2193                 } // END - if
2194
2195                 // Free result
2196                 SQL_FREERESULT($result);
2197         } // END - if
2198
2199         // Return generated HTML code
2200         return $OUT;
2201 }
2202
2203
2204 /**
2205  * Determine if a string can represent a number in hexadecimal
2206  *
2207  * @param       $hex    A string to check if it is hex-encoded
2208  * @return      $foo    True if the string is a hex, otherwise false
2209  * @author      Marques Johansson
2210  * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
2211  */
2212 function isHexadecimal ($hex) {
2213         // Make it lowercase
2214         $hex = strtolower(trim(ltrim($hex, '0')));
2215
2216         // Fix empty strings to zero
2217         if (empty($hex)) {
2218                 $hex = 0;
2219         } // END - if
2220
2221         // Simply compare decode->encode result with original
2222         return ($hex == dechex(hexdec($hex)));
2223 }
2224
2225 /**
2226  * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make
2227  * them visible to the developer. Use this function to debug e.g. buggy HTTP
2228  * response handler functions.
2229  *
2230  * @param       $str    String to overwork
2231  * @return      $str    Overworked string
2232  */
2233 function replaceReturnNewLine ($str) {
2234         return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2235 }
2236
2237 // Converts a given string by splitting it up with given delimiter similar to
2238 // explode(), but appending the delimiter again
2239 function stringToArray ($delimiter, $string) {
2240         // Init array
2241         $strArray = array();
2242
2243         // "Walk" through all entries
2244         foreach (explode($delimiter, $string) as $split) {
2245                 //  Append the delimiter and add it to the array
2246                 array_push($strArray, $split . $delimiter);
2247         } // END - foreach
2248
2249         // Return array
2250         return $strArray;
2251 }
2252
2253 // Detects the prefix 'mb_' if a multi-byte string is given
2254 function detectMultiBytePrefix ($str) {
2255         // Default is without multi-byte
2256         $mbPrefix = '';
2257
2258         // Detect multi-byte (strictly)
2259         if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) {
2260                 // With multi-byte encoded string
2261                 $mbPrefix = 'mb_';
2262         } // END - if
2263
2264         // Return the prefix
2265         return $mbPrefix;
2266 }
2267
2268 // Searches given array for a sub-string match and returns all found keys in an array
2269 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2270         // Init array for all found keys
2271         $keys = array();
2272
2273         // Now check all entries
2274         foreach ($needles as $key => $needle) {
2275                 // Is there found a partial string?
2276                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2277                 if (strpos($heystack, $needle, $offset) !== FALSE) {
2278                         // Add the found key
2279                         array_push($keys, $key);
2280                 } // END - if
2281         } // END - foreach
2282
2283         // Return the array
2284         return $keys;
2285 }
2286
2287 // Determines database column name from given subject and locked
2288 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2289         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2290         // Default is 'normal' points
2291         $pointsColumn = 'points';
2292
2293         // Which points, locked or normal?
2294         if ($locked === TRUE) {
2295                 $pointsColumn = 'locked_points';
2296         } // END - if
2297
2298         // Prepare array for filter
2299         $filterData = array(
2300                 'subject' => $subject,
2301                 'locked'  => $locked,
2302                 'column'  => $pointsColumn
2303         );
2304
2305         // Run the filter
2306         $filterData = runFilterChain('determine_points_column_name', $filterData);
2307
2308         // Extract column name from array
2309         $pointsColumn = $filterData['column'];
2310
2311         // Return it
2312         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2313         return $pointsColumn;
2314 }
2315
2316 // Converts a boolean variable into 'Y' for true and 'N' for false
2317 function convertBooleanToYesNo ($boolean) {
2318         // Default is 'N'
2319         $converted = 'N';
2320         if ($boolean === TRUE) {
2321                 // Set 'Y'
2322                 $converted = 'Y';
2323         } // END - if
2324
2325         // Return it
2326         return $converted;
2327 }
2328
2329 // "Translates" 'true' to true and 'false' to false
2330 function convertStringToBoolean ($str) {
2331         // Debug message (to measure how often this function is called)
2332         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2333
2334         // Is there cache?
2335         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2336                 // Trim it lower-case for validation
2337                 $strTrimmed = trim(strtolower($str));
2338
2339                 // Is it valid?
2340                 if (!in_array($strTrimmed, array('true', 'false'))) {
2341                         // Not valid!
2342                         reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2343                 } // END - if
2344
2345                 // Determine it
2346                 $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true');
2347         } // END - if
2348
2349         // Return cache
2350         return $GLOBALS[__FUNCTION__][$str];
2351 }
2352
2353 /**
2354  * "Makes" a variable in given string parseable, this function will throw an
2355  * error if the first character is not a dollar sign.
2356  *
2357  * @param       $varString      String which contains a variable
2358  * @return      $return         String with added single quotes for better parsing
2359  */
2360 function makeParseableVariable ($varString) {
2361         // The first character must be a dollar sign
2362         if (substr($varString, 0, 1) != '$') {
2363                 // Please report this
2364                 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2365         } // END - if
2366
2367         // Is there cache?
2368         if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2369                 // Snap them in, if [,] are there
2370                 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2371         } // END - if
2372
2373         // Return cache
2374         return $GLOBALS[__FUNCTION__][$varString];
2375 }
2376
2377 // "Getter" for random TAN
2378 function getRandomTan () {
2379         // Generate one
2380         return mt_rand(0, 99999);
2381 }
2382
2383 // Removes any : from subject
2384 function removeDoubleDotFromSubject ($subject) {
2385         // Remove it
2386         $subjectArray = explode(':', $subject);
2387         $subject = $subjectArray[0];
2388         unset($subjectArray);
2389
2390         // Return it
2391         return $subject;
2392 }
2393
2394 // Adds a given entry to the database
2395 function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2396         // Is it a member?
2397         if (!isMember()) {
2398                 // Then abort here
2399                 return FALSE;
2400         } // END - if
2401
2402         // Set POST data generic userid
2403         setPostRequestElement('userid', getMemberId());
2404
2405         // Call inner function
2406         doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
2407
2408         // Entry has been added?
2409         if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
2410                 // Display success message
2411                 displayMessage('{--MEMBER_ENTRY_ADDED--}');
2412         } else {
2413                 // Display failed message
2414                 displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
2415         }
2416 }
2417
2418 // Edit rows by given id numbers
2419 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()) {
2420         // $tableName must be an array
2421         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2422                 // No tableName specified
2423                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2424         } elseif (!is_array($idColumn)) {
2425                 // $idColumn is no array
2426                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2427         } elseif (!is_array($userIdColumn)) {
2428                 // $userIdColumn is no array
2429                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2430         } elseif (!is_array($editNow)) {
2431                 // $editNow is no array
2432                 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
2433         } // END - if
2434
2435         // Shall we change here or list for editing?
2436         if ($editNow[0] === TRUE) {
2437                 // Add generic userid field
2438                 setPostRequestElement('userid', getMemberId());
2439
2440                 // Call generic change method
2441                 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_edit');
2442
2443                 // Was this fine?
2444                 if ($affected == countPostSelection($idColumn[0])) {
2445                         // All deleted
2446                         displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
2447                 } else {
2448                         // Some are still there :(
2449                         displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
2450                 }
2451         } else {
2452                 // List for editing
2453                 memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2454         }
2455 }
2456
2457 // Delete rows by given id numbers
2458 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()) {
2459         // Do this only for members
2460         assert(isMember());
2461
2462         // $tableName must be an array
2463         if ((!is_array($tableName)) || (count($tableName) != 1)) {
2464                 // No tableName specified
2465                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2466         } elseif (!is_array($idColumn)) {
2467                 // $idColumn is no array
2468                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2469         } elseif (!is_array($userIdColumn)) {
2470                 // $userIdColumn is no array
2471                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2472         } elseif (!is_array($deleteNow)) {
2473                 // $deleteNow is no array
2474                 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
2475         } // END - if
2476
2477         // Shall we delete here or list for deletion?
2478         if ($deleteNow[0] === TRUE) {
2479                 // Add generic userid field
2480                 setPostRequestElement('userid', getMemberId());
2481
2482                 // Call generic function
2483                 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles, 'mem_delete');
2484
2485                 // Was this fine?
2486                 if ($affected == countPostSelection($idColumn[0])) {
2487                         // All deleted
2488                         displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
2489                 } else {
2490                         // Some are still there :(
2491                         displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
2492                 }
2493         } else {
2494                 // List for deletion confirmation
2495                 memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content);
2496         }
2497 }
2498
2499 // Build a special template list
2500 // @TODO cacheFiles is not yet supported
2501 function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2502         // Do this only for logged in member
2503         assert(isMember());
2504
2505         // Call inner (general) function
2506         doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
2507 }
2508
2509 // Checks whether given address is IPv4
2510 function isIp4AddressValid ($address) {
2511         // Is there cache?
2512         if (!isset($GLOBALS[__FUNCTION__][$address])) {
2513                 // Determine it ...
2514                 $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);
2515         } // END - if
2516
2517         // Return cache
2518         return $GLOBALS[__FUNCTION__][$address];
2519 }
2520
2521 // Returns the string if not empty or FALSE if empty
2522 function validateIsEmpty ($str) {
2523         // Trim it
2524         $trimmed = trim($str);
2525
2526         // Is the string empty?
2527         if (empty($trimmed)) {
2528                 // Then set FALSE
2529                 $str = FALSE;
2530         } // END - if
2531
2532         // Return it
2533         return $str;
2534 }
2535
2536 // "Getter" for seconds from given time unit
2537 function getSecondsFromTimeUnit ($timeUnit) {
2538         // Default is not found
2539         $seconds = NULL;
2540
2541         // "Detect" it
2542         switch ($timeUnit) {
2543                 case 's': // Seconds = 1
2544                         $seconds = 1;
2545                         break;
2546
2547                 case 'm': // Minutes
2548                         $seconds = 60;
2549                         break;
2550
2551                 case 'h': // Hours
2552                         $seconds = 60*60;
2553                         break;
2554
2555                 case 'D': // Days
2556                         $seconds = 60*60*24;
2557                         break;
2558
2559                 case 'W': // Weeks
2560                         $seconds = 60*60*24*7;
2561                         break;
2562
2563                 default: // Unsupported
2564                         reportBug(__FUNCTION__, __LINE__, 'Unsupported time unit ' . $timeUnit . ' detected.');
2565                         break;
2566         } // END - switch
2567
2568         // Return value
2569         return $seconds;
2570 }
2571
2572 // Calulates value for given seconds and time unit
2573 function caluculateTimeUnitValue ($seconds, $timeUnit) {
2574         // Calculate it
2575         return ($seconds / getSecondsFromTimeUnit($timeUnit));
2576 }
2577
2578 // "Getter" for an array from given one but only one index of it
2579 function getArrayFromArrayIndex ($array, $key) {
2580         // Some simple validation
2581         assert(isset($array[0][$key]));
2582
2583         // Init new array
2584         $newArray = array();
2585
2586         // "Walk" through all elements
2587         foreach ($array as $element) {
2588                 $newArray[] = $element[$key];
2589         } // END - if
2590
2591         // Return it
2592         return $newArray;
2593 }
2594
2595 /**
2596  * Compress given data and encodes it into BASE64 to be stored in database with
2597  * SQL_QUERY_ESC()
2598  *
2599  * @param       $data   Data to be compressed and encoded
2600  * @return      $data   Compressed+encoded data
2601  */
2602 function compress ($data) {
2603         // Compress it
2604         return base64_encode(gzcompress($data));
2605 }
2606
2607 /**
2608  * Decompress given data previously compressed with compress().
2609  *
2610  * @param       $data   Data compressed with compress()
2611  * @reurn       $data   Uncompressed data
2612  */
2613 function decompress ($data) {
2614         // Decompress it
2615         return gzuncompress(base64_decode($data));
2616 }
2617
2618 /**
2619  * Converts given charset in given string to UTF-8 if not UTF-8. This function
2620  * is currently limited to iconv().
2621  *
2622  * @param       $str            String to convert charset in
2623  * @param       $charset        Charset to convert from
2624  * @return      $str            Converted string
2625  */
2626 function convertCharsetToUtf8 ($str, $charset) {
2627         // Is iconv() available?
2628         if (!function_exists('iconv')) {
2629                 // Please make it sure
2630                 reportBug(__FUNCTION__, __LINE__, 'PHP function iconv() is currently required to do charset convertion.');
2631         } // END - if
2632
2633         // Is the charset not UTF-8?
2634         if (strtoupper($charset) != 'UTF-8') {
2635                 // Convert it to UTF-8
2636                 $str = iconv(strtoupper($charset), 'UTF-8//TRANSLIT', $str);
2637         } // END - if
2638
2639         // Return converted string
2640         return $str;
2641 }
2642
2643 // ----------------------------------------------------------------------------
2644 //              "Translatation" functions for points_data table
2645 // ----------------------------------------------------------------------------
2646
2647 // Translates generically some data into a target string
2648 function translateGeneric ($messagePrefix, $data, $messageSuffix = '') {
2649         // Is the method null or empty?
2650         if (is_null($data)) {
2651                 // Is NULL
2652                 $data = 'NULL';
2653         } elseif (empty($data)) {
2654                 // Is empty (string)
2655                 $data = 'EMPTY';
2656         } // END - if
2657
2658         // Default column name is unknown
2659         $return = '{%message,' . $messagePrefix . '_UNKNOWN' . $messageSuffix . '=' . strtoupper($data) . '%}';
2660
2661         // Construct message id
2662         $messageId = $messagePrefix . '_' . strtoupper($data) . $messageSuffix;
2663
2664         // Is it there?
2665         if (isMessageIdValid($messageId)) {
2666                 // Then use it as message string
2667                 $return = '{--' . $messageId . '--}';
2668         } // END - if
2669
2670         // Return the column name
2671         return $return;
2672 }
2673
2674 // Translates points subject to human-readable
2675 function translatePointsSubject ($subject) {
2676         // Remove any :x
2677         $subject = removeDoubleDotFromSubject($subject);
2678
2679         // Return it
2680         return translateGeneric('POINTS_SUBJECT', $subject);
2681 }
2682
2683 // "Translates" given points account type
2684 function translatePointsAccountType ($accountType) {
2685         // Return it
2686         return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2687 }
2688
2689 // "Translates" given points "locked mode"
2690 function translatePointsLockedMode ($lockedMode) {
2691         // Return it
2692         return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2693 }
2694
2695 // "Translates" given points payment method
2696 function translatePointsPaymentMethod ($paymentMethod) {
2697         // Return it
2698         return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2699 }
2700
2701 // "Translates" given points account provider
2702 function translatePointsAccountProvider ($accountProvider) {
2703         // Return it
2704         return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2705 }
2706
2707 // "Translates" given points notify recipient
2708 function translatePointsNotifyRecipient ($notifyRecipient) {
2709         // Return it
2710         return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2711 }
2712
2713 // "Translates" given mode to a human-readable version
2714 function translatePointsMode ($pointsMode) {
2715         // Return it
2716         return translateGeneric('POINTS_MODE', $pointsMode);
2717 }
2718
2719 // "Translates" task type to a human-readable version
2720 function translateTaskType ($taskType) {
2721         // Return it
2722         return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2723 }
2724
2725 //-----------------------------------------------------------------------------
2726 // Automatically re-created functions, all taken from user comments on www.php.net
2727 //-----------------------------------------------------------------------------
2728 if (!function_exists('html_entity_decode')) {
2729         // Taken from documentation on www.php.net
2730         function html_entity_decode ($string) {
2731                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2732                 $trans_tbl = array_flip($trans_tbl);
2733                 return strtr($string, $trans_tbl);
2734         }
2735 } // END - if
2736
2737 // [EOF]
2738 ?>