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