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