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