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