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