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