]> git.mxchange.org Git - mailer.git/blob - inc/functions.php
Code improved:
[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 // Enables the reset mode and runs it
1497 function doReset () {
1498         // Enable the reset mode
1499         $GLOBALS['reset_enabled'] = true;
1500
1501         // Run filters
1502         runFilterChain('reset');
1503 }
1504
1505 // Enables the reset mode (hourly, weekly and monthly) and runs it
1506 function doHourly () {
1507         // Enable the hourly reset mode
1508         $GLOBALS['hourly_enabled'] = true;
1509
1510         // Run filters (one always!)
1511         runFilterChain('hourly');
1512 }
1513
1514 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
1515 function doShutdown () {
1516         // Call the filter chain 'shutdown'
1517         runFilterChain('shutdown', NULL);
1518
1519         // Check if not in installation phase and the link is up
1520         if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
1521                 // Close link
1522                 SQL_CLOSE(__FUNCTION__, __LINE__);
1523         } elseif (!isInstallationPhase()) {
1524                 // No database link
1525                 reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
1526         }
1527
1528         // Stop executing here
1529         exit;
1530 }
1531
1532 // Init member id
1533 function initMemberId () {
1534         $GLOBALS['member_id'] = '0';
1535 }
1536
1537 // Setter for member id
1538 function setMemberId ($memberid) {
1539         // We should not set member id to zero
1540         if ($memberid == '0') {
1541                 reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
1542         } // END - if
1543
1544         // Set it secured
1545         $GLOBALS['member_id'] = bigintval($memberid);
1546 }
1547
1548 // Getter for member id or returns zero
1549 function getMemberId () {
1550         // Default member id
1551         $memberid = '0';
1552
1553         // Is the member id set?
1554         if (isMemberIdSet()) {
1555                 // Then use it
1556                 $memberid = $GLOBALS['member_id'];
1557         } // END - if
1558
1559         // Return it
1560         return $memberid;
1561 }
1562
1563 // Checks ether the member id is set
1564 function isMemberIdSet () {
1565         return (isset($GLOBALS['member_id']));
1566 }
1567
1568 // Setter for extra title
1569 function setExtraTitle ($extraTitle) {
1570         $GLOBALS['extra_title'] = $extraTitle;
1571 }
1572
1573 // Getter for extra title
1574 function getExtraTitle () {
1575         // Is the extra title set?
1576         if (!isExtraTitleSet()) {
1577                 // No, then abort here
1578                 reportBug(__FUNCTION__, __LINE__, 'extra_title is not set!');
1579         } // END - if
1580
1581         // Return it
1582         return $GLOBALS['extra_title'];
1583 }
1584
1585 // Checks if the extra title is set
1586 function isExtraTitleSet () {
1587         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
1588 }
1589
1590 /**
1591  * Reads a directory recursively by default and searches for files not matching
1592  * an exclusion pattern. You can now keep the exclusion pattern empty for reading
1593  * a whole directory.
1594  *
1595  * @param       $baseDir                        Relative base directory to PATH to scan from
1596  * @param       $prefix                         Prefix for all positive matches (which files should be found)
1597  * @param       $fileIncludeDirs        whether to include directories in the final output array
1598  * @param       $addBaseDir                     whether to add $baseDir to all array entries
1599  * @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'
1600  * @param       $extension                      File extension for all positive matches
1601  * @param       $excludePattern         Regular expression to exclude more files (preg_match())
1602  * @param       $recursive                      whether to scan recursively
1603  * @param       $suffix                         Suffix for positive matches ($extension will be appended, too)
1604  * @return      $foundMatches           All found positive matches for above criteria
1605  */
1606 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
1607         // Add default entries we should always exclude
1608         array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
1609
1610         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ' - Entered!');
1611         // Init found includes
1612         $foundMatches = array();
1613
1614         // Open directory
1615         $dirPointer = opendir(getPath() . $baseDir) or reportBug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
1616
1617         // Read all entries
1618         while ($baseFile = readdir($dirPointer)) {
1619                 // Exclude '.', '..' and entries in $excludeArray automatically
1620                 if (in_array($baseFile, $excludeArray, true))  {
1621                         // Exclude them
1622                         //* DEBUG: */ debugOutput('excluded=' . $baseFile);
1623                         continue;
1624                 } // END - if
1625
1626                 // Construct include filename and FQFN
1627                 $fileName = $baseDir . $baseFile;
1628                 $FQFN = getPath() . $fileName;
1629
1630                 // Remove double slashes
1631                 $FQFN = str_replace('//', '/', $FQFN);
1632
1633                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
1634                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
1635                         // Debug message
1636                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',baseFile=' . $baseFile . ',FQFN=' . $FQFN);
1637
1638                         // Exclude this one
1639                         continue;
1640                 } // END - if
1641
1642                 // Skip also files with non-matching prefix genericly
1643                 if (($recursive === true) && (isDirectory($FQFN))) {
1644                         // Is a redirectory so read it as well
1645                         $foundMatches = merge_array($foundMatches, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
1646
1647                         // And skip further processing
1648                         continue;
1649                 } elseif (!isFilePrefixFound($baseFile, $prefix)) {
1650                         // Skip this file
1651                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid prefix in file ' . $baseFile . ', prefix=' . $prefix);
1652                         continue;
1653                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
1654                         // Skip wrong suffix as well
1655                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Invalid suffix in file ' . $baseFile . ', suffix=' . $suffix);
1656                         continue;
1657                 } elseif (!isFileReadable($FQFN)) {
1658                         // Not readable so skip it
1659                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is not readable!');
1660                 } elseif (filesize($FQFN) < 50) {
1661                         // Might be deprecated
1662                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is to small (' . filesize($FQFN) . ')!');
1663                         continue;
1664                 } elseif (($extension == '.php') && (filesize($FQFN) < 50)) {
1665                         // This PHP script is deprecated
1666                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File ' . $FQFN . ' is a deprecated PHP script!');
1667                         continue;
1668                 }
1669
1670                 // Get file' extension (last 4 chars)
1671                 $fileExtension = substr($baseFile, -4, 4);
1672
1673                 // Is the file a PHP script or other?
1674                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'baseDir=' . $baseDir . ',prefix=' . $prefix . ',baseFile=' . $baseFile);
1675                 if (($fileExtension == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
1676                         // Is this a valid include file?
1677                         if ($extension == '.php') {
1678                                 // Remove both for extension name
1679                                 $extName = substr($baseFile, strlen($prefix), -4);
1680
1681                                 // Add file with or without base path
1682                                 if ($addBaseDir === true) {
1683                                         // With base path
1684                                         array_push($foundMatches, $fileName);
1685                                 } else {
1686                                         // No base path
1687                                         array_push($foundMatches, $baseFile);
1688                                 }
1689                         } else {
1690                                 // We found .php file but should not search for them, why?
1691                                 reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
1692                         }
1693                 } elseif ($fileExtension == $extension) {
1694                         // Other, generic file found
1695                         array_push($foundMatches, $fileName);
1696                 }
1697         } // END - while
1698
1699         // Close directory
1700         closedir($dirPointer);
1701
1702         // Sort array
1703         sort($foundMatches);
1704
1705         // Return array with include files
1706         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
1707         return $foundMatches;
1708 }
1709
1710 // Checks whether $prefix is found in $fileName
1711 function isFilePrefixFound ($fileName, $prefix) {
1712         // @TODO Find a way to cache this
1713         return (substr($fileName, 0, strlen($prefix)) == $prefix);
1714 }
1715
1716 // Maps a module name into a database table name
1717 function mapModuleToTable ($moduleName) {
1718         // Map only these, still lame code...
1719         switch ($moduleName) {
1720                 case 'index': // 'index' is the guest's menu
1721                         $moduleName = 'guest'; 
1722                         break;
1723
1724                 case 'login': // ... and 'login' the member's menu
1725                         $moduleName = 'member';
1726                         break;
1727
1728                 // Anything else will not be mapped, silently.
1729         } // END - switch
1730
1731         // Return result
1732         return $moduleName;
1733 }
1734
1735 // Add SQL debug data to array for later output
1736 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
1737         // Do we have cache?
1738         if (!isset($GLOBALS['debug_sql_available'])) {
1739                 // Check it and cache it in $GLOBALS
1740                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
1741         } // END - if
1742         
1743         // Don't execute anything here if we don't need or ext-other is missing
1744         if ($GLOBALS['debug_sql_available'] === false) {
1745                 return;
1746         } // END - if
1747
1748         // Already executed?
1749         if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
1750                 // Then abort here, we don't need to profile a query twice
1751                 return;
1752         } // END - if
1753
1754         // Remeber this as profiled (or not, but we don't care here)
1755         $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
1756
1757         // Generate record
1758         $record = array(
1759                 'num_rows' => SQL_NUMROWS($result),
1760                 'affected' => SQL_AFFECTEDROWS(),
1761                 'sql_str'  => $sqlString,
1762                 'timing'   => $timing,
1763                 'file'     => basename($F),
1764                 'line'     => $L
1765         );
1766
1767         // Add it
1768         array_push($GLOBALS['debug_sqls'], $record);
1769 }
1770
1771 // Initializes the cache instance
1772 function initCacheInstance () {
1773         // Check for double-initialization
1774         if (isset($GLOBALS['cache_instance'])) {
1775                 // This should not happen and must be fixed
1776                 reportBug(__FUNCTION__, __LINE__, 'Double initialization of cache system detected. cache_instance[]=' . gettype($GLOBALS['cache_instance']));
1777         } // END - if
1778
1779         // Load include for CacheSystem class
1780         loadIncludeOnce('inc/classes/cachesystem.class.php');
1781
1782         // Initialize cache system only when it's needed
1783         $GLOBALS['cache_instance'] = new CacheSystem();
1784
1785         // Did it work?
1786         if ($GLOBALS['cache_instance']->getStatusCode() != 'done') {
1787                 // Failed to initialize cache sustem
1788                 reportBug(__FUNCTION__, __LINE__, 'Cache system returned with unexpected error. getStatusCode()=' . $GLOBALS['cache_instance']->getStatusCode());
1789         } // END - if
1790 }
1791
1792 // Getter for message from array or raw message
1793 function getMessageFromIndexedArray ($message, $pos, $array) {
1794         // Check if the requested message was found in array
1795         if (isset($array[$pos])) {
1796                 // ... if yes then use it!
1797                 $ret = $array[$pos];
1798         } else {
1799                 // ... else use default message
1800                 $ret = $message;
1801         }
1802
1803         // Return result
1804         return $ret;
1805 }
1806
1807 // Convert ';' to ', ' for e.g. receiver list
1808 function convertReceivers ($old) {
1809         return str_replace(';', ', ', $old);
1810 }
1811
1812 // Get a module from filename and access level
1813 function getModuleFromFileName ($file, $accessLevel) {
1814         // Default is 'invalid';
1815         $modCheck = 'invalid';
1816
1817         // @TODO This is still very static, rewrite it somehow
1818         switch ($accessLevel) {
1819                 case 'admin':
1820                         $modCheck = 'admin';
1821                         break;
1822
1823                 case 'sponsor':
1824                 case 'guest':
1825                 case 'member':
1826                         $modCheck = getModule();
1827                         break;
1828
1829                 default: // Unsupported file name / access level
1830                         reportBug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
1831                         break;
1832         } // END - switch
1833
1834         // Return result
1835         return $modCheck;
1836 }
1837
1838 // Encodes an URL for adding session id, etc.
1839 function encodeUrl ($url, $outputMode = '0') {
1840         // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
1841         if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
1842                 // Raw output mode detected or session_name() found in URL
1843                 return $url;
1844         } // END - if
1845
1846         // Do we have a valid session?
1847         if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
1848                 // Determine right separator
1849                 $separator = '&amp;';
1850                 if (!isInString('?', $url)) {
1851                         // No question mark
1852                         $separator = '?';
1853                 } // END - if
1854
1855                 // Add it to URL
1856                 if (session_id() != '') {
1857                         $url .= $separator . session_name() . '=' . session_id();
1858                 } // END - if
1859         } // END - if
1860
1861         // Add {?URL?} ?
1862         if ((substr($url, 0, strlen(getUrl())) != getUrl()) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
1863                 // Add it
1864                 $url = '{?URL?}/' . $url;
1865         } // END - if
1866
1867         // Do we have to decode entities?
1868         if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
1869                 // Decode them for e.g. JavaScript parts
1870                 $url = decodeEntities($url);
1871         } // END - if
1872
1873         // Debug log
1874         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',outputMode=' . $outputMode);
1875
1876         // Return the encoded URL
1877         return $url;
1878 }
1879
1880 // Simple check for spider
1881 function isSpider () {
1882         // Get the UA and trim it down
1883         $userAgent = trim(detectUserAgent(true));
1884
1885         // It should not be empty, if so it is better a spider/bot
1886         if (empty($userAgent)) {
1887                 // It is a spider/bot
1888                 return true;
1889         } // END - if
1890
1891         // Is it a spider?
1892         return ((isInStringIgnoreCase('spider', $userAgent)) || (isInStringIgnoreCase('slurp', $userAgent)) || (isInStringIgnoreCase('bot', $userAgent)) || (isInStringIgnoreCase('archiver', $userAgent)));
1893 }
1894
1895 // Function to search for the last modified file
1896 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
1897         // Get dir as array
1898         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
1899         // Does it match what we are looking for? (We skip a lot files already!)
1900         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
1901         $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
1902
1903         $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
1904         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
1905
1906         // Walk through all entries
1907         foreach ($ds as $d) {
1908                 // Generate proper FQFN
1909                 $FQFN = str_replace('//', '/', getPath() . $dir . '/' . $d);
1910
1911                 // Is it a file and readable?
1912                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
1913                 if (isFileReadable($FQFN)) {
1914                         // $FQFN is a readable file so extract the requested data from it
1915                         $check = extractRevisionInfoFromFile($FQFN, $lookFor);
1916                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
1917
1918                         // Is the file more recent?
1919                         if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
1920                                 // This file is newer as the file before
1921                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
1922                                 $last_changed['path_name'] = $FQFN;
1923                                 $last_changed[$lookFor] = $check;
1924                         } // END - if
1925                 } else {
1926                         // Not readable
1927                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
1928                 }
1929         } // END - foreach
1930 }
1931
1932 // Handles the braces [] of a field (e.g. value of 'name' attribute)
1933 function handleFieldWithBraces ($field) {
1934         // Are there braces [] at the end?
1935         if (substr($field, -2, 2) == '[]') {
1936                 /*
1937                  * Try to find one and replace it. I do it this way to allow easy
1938                  * extending of this code.
1939                  */
1940                 foreach (array('admin_list_builder_id_value') as $key) {
1941                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key);
1942                         // Is the cache entry set?
1943                         if (isset($GLOBALS[$key])) {
1944                                 // Insert it
1945                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
1946
1947                                 // And abort
1948                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key, 'field=' . $field);
1949                                 break;
1950                         } // END - if
1951                 } // END - foreach
1952         } // END - if
1953
1954         // Return it
1955         return $field;
1956 }
1957
1958 // Converts a zero or NULL to word 'NULL'
1959 function convertZeroToNull ($number) {
1960         // Is it a valid username?
1961         if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
1962                 // Always secure it
1963                 $number = bigintval($number);
1964         } else {
1965                 // Is not valid or zero
1966                 $number = 'NULL';
1967         }
1968
1969         // Return it
1970         return $number;
1971 }
1972
1973 // Converts a NULL to zero
1974 function convertNullToZero ($number) {
1975         // Is it a valid username?
1976         if ((!is_null($number)) && (!empty($number)) && ($number > 0)) {
1977                 // Always secure it
1978                 $number = bigintval($number);
1979         } else {
1980                 // Is not valid or zero
1981                 $number = '0';
1982         }
1983
1984         // Return it
1985         return $number;
1986 }
1987
1988 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
1989 // Note: This function is cached
1990 function capitalizeUnderscoreString ($str) {
1991         // Do we have cache?
1992         if (!isset($GLOBALS[__FUNCTION__][$str])) {
1993                 // Init target string
1994                 $capitalized = '';
1995
1996                 // Explode it with the underscore, but rewrite dashes to underscore before
1997                 $strArray = explode('_', str_replace('-', '_', $str));
1998
1999                 // "Walk" through all elements and make them lower-case but first upper-case
2000                 foreach ($strArray as $part) {
2001                         // Capitalize the string part
2002                         $capitalized .= firstCharUpperCase($part);
2003                 } // END - foreach
2004
2005                 // Store the converted string in cache array
2006                 $GLOBALS[__FUNCTION__][$str] = $capitalized;
2007         } // END - if
2008
2009         // Return cache
2010         return $GLOBALS[__FUNCTION__][$str];
2011 }
2012
2013 // Generate admin links for mail order
2014 // mailType can be: 'mid' or 'bid'
2015 function generateAdminMailLinks ($mailType, $mailId) {
2016         // Init variables
2017         $OUT = '';
2018         $table = '';
2019
2020         // Default column for mail status is 'data_type'
2021         // @TODO Rename column data_type to e.g. mail_status
2022         $statusColumn = 'data_type';
2023
2024         // Which mail do we have?
2025         switch ($mailType) {
2026                 case 'bid': // Bonus mail
2027                         $table = 'bonus';
2028                         break;
2029
2030                 case 'mid': // Member mail
2031                         $table = 'pool';
2032                         break;
2033
2034                 default: // Handle unsupported types
2035                         logDebugMessage(__FUNCTION__, __LINE__, 'Unsupported mail type ' . $mailType . ' for mailId=' . $mailId . ' detected.');
2036                         $OUT = '<div align="center">{%message,ADMIN_UNSUPPORTED_MAIL_TYPE_DETECTED=' . $mailType . '%}</div>';
2037                         break;
2038         } // END - switch
2039
2040         // Is the mail type supported?
2041         if (!empty($table)) {
2042                 // Query for the mail
2043                 $result = SQL_QUERY_ESC("SELECT `id`,`%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
2044                         array(
2045                                 $statusColumn,
2046                                 $table,
2047                                 bigintval($mailId)
2048                         ), __FILE__, __LINE__);
2049
2050                 // Do we have one entry there?
2051                 if (SQL_NUMROWS($result) == 1) {
2052                         // Load the entry
2053                         $content = SQL_FETCHARRAY($result);
2054
2055                         // Add output and type
2056                         $content['type']     = $mailType;
2057                         $content['__output'] = '';
2058
2059                         // Filter all data
2060                         $content = runFilterChain('generate_admin_mail_links', $content);
2061
2062                         // Get output back
2063                         $OUT = $content['__output'];
2064                 } // END - if
2065
2066                 // Free result
2067                 SQL_FREERESULT($result);
2068         } // END - if
2069
2070         // Return generated HTML code
2071         return $OUT;
2072 }
2073
2074
2075 /**
2076  * Determine if a string can represent a number in hexadecimal
2077  *
2078  * @param       $hex    A string to check if it is hex-encoded
2079  * @return      $foo    True if the string is a hex, otherwise false
2080  * @author      Marques Johansson
2081  * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
2082  */
2083 function isHexadecimal ($hex) {
2084         // Make it lowercase
2085         $hex = strtolower(trim(ltrim($hex, '0')));
2086
2087         // Fix empty strings to zero
2088         if (empty($hex)) {
2089                 $hex = 0;
2090         } // END - if
2091
2092         // Simply compare decode->encode result with original
2093         return ($hex == dechex(hexdec($hex)));
2094 }
2095
2096 /**
2097  * Replace chr(13) with "[r]" and chr(10) with "[n]" and add a final new-line to make
2098  * them visible to the developer. Use this function to debug e.g. buggy HTTP
2099  * response handler functions.
2100  *
2101  * @param       $str    String to overwork
2102  * @return      $str    Overworked string
2103  */
2104 function replaceReturnNewLine ($str) {
2105         return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
2106 }
2107
2108 // Converts a given string by splitting it up with given delimiter similar to
2109 // explode(), but appending the delimiter again
2110 function stringToArray ($delimiter, $string) {
2111         // Init array
2112         $strArray = array();
2113
2114         // "Walk" through all entries
2115         foreach (explode($delimiter, $string) as $split) {
2116                 //  Append the delimiter and add it to the array
2117                 array_push($strArray, $split . $delimiter);
2118         } // END - foreach
2119
2120         // Return array
2121         return $strArray;
2122 }
2123
2124 // Detects the prefix 'mb_' if a multi-byte string is given
2125 function detectMultiBytePrefix ($str) {
2126         // Default is without multi-byte
2127         $mbPrefix = '';
2128
2129         // Detect multi-byte (strictly)
2130         if (mb_detect_encoding($str, 'auto', true) !== false) {
2131                 // With multi-byte encoded string
2132                 $mbPrefix = 'mb_';
2133         } // END - if
2134
2135         // Return the prefix
2136         return $mbPrefix;
2137 }
2138
2139 // Searches the given array for a sub-string match and returns all found keys in an array
2140 function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
2141         // Init array for all found keys
2142         $keys = array();
2143
2144         // Now check all entries
2145         foreach ($needles as $key => $needle) {
2146                 // Do we have found a partial string?
2147                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
2148                 if (strpos($heystack, $needle, $offset) !== false) {
2149                         // Add the found key
2150                         array_push($keys, $key);
2151                 } // END - if
2152         } // END - foreach
2153
2154         // Return the array
2155         return $keys;
2156 }
2157
2158 // Determines database column name from given subject and locked
2159 function determinePointsColumnFromSubjectLocked ($subject, $locked) {
2160         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!');
2161         // Default is 'normal' points
2162         $pointsColumn = 'points';
2163
2164         // Which points, locked or normal?
2165         if ($locked === true) {
2166                 $pointsColumn = 'locked_points';
2167         } // END - if
2168
2169         // Prepare array for filter
2170         $filterData = array(
2171                 'subject' => $subject,
2172                 'locked'  => $locked,
2173                 'column'  => $pointsColumn
2174         );
2175
2176         // Run the filter
2177         $filterData = runFilterChain('determine_points_column_name', $filterData);
2178
2179         // Extract column name from array
2180         $pointsColumn = $filterData['column'];
2181
2182         // Return it
2183         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!');
2184         return $pointsColumn;
2185 }
2186
2187 // Converts a boolean variable into 'Y' for true and 'N' for false
2188 function convertBooleanToYesNo ($boolean) {
2189         // Default is 'N'
2190         $converted = 'N';
2191         if ($boolean === true) {
2192                 // Set 'Y'
2193                 $converted = 'Y';
2194         } // END - if
2195
2196         // Return it
2197         return $converted;
2198 }
2199
2200 // "Translates" 'true' to true and 'false' to false
2201 function convertStringToBoolean ($str) {
2202         // Debug message (to measure how often this function is called)
2203         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
2204
2205         // Do we have cache?
2206         if (!isset($GLOBALS[__FUNCTION__][$str])) {
2207                 // Trim it lower-case for validation
2208                 $strTrimmed = trim(strtolower($str));
2209
2210                 // Is it valid?
2211                 if (!in_array($strTrimmed, array('true', 'false'))) {
2212                         // Not valid!
2213                         reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false');
2214                 } // END - if
2215
2216                 // Determine it
2217                 $GLOBALS[__FUNCTION__][$str] = (($strTrimmed == 'true') ? true : false);
2218         } // END - if
2219
2220         // Return cache
2221         return $GLOBALS[__FUNCTION__][$str];
2222 }
2223
2224 /**
2225  * "Makes" a variable in given string parseable, this function will throw an
2226  * error if the first character is not a dollar sign.
2227  *
2228  * @param       $varString      String which contains a variable
2229  * @return      $return         String with added single quotes for better parsing
2230  */
2231 function makeParseableVariable ($varString) {
2232         // The first character must be a dollar sign
2233         if (substr($varString, 0, 1) != '$') {
2234                 // Please report this
2235                 reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
2236         } // END - if
2237
2238         // Do we have cache?
2239         if (!isset($GLOBALS[__FUNCTION__][$varString])) {
2240                 // Snap them in, if [,] are there
2241                 $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
2242         } // END - if
2243
2244         // Return cache
2245         return $GLOBALS[__FUNCTION__][$varString];
2246 }
2247
2248 // "Getter" for random TAN
2249 function getRandomTan () {
2250         // Generate one
2251         return mt_rand(0, 99999);
2252 }
2253
2254 // Removes any : from subject
2255 function removeDoubleDotFromSubject ($subject) {
2256         // Remove it
2257         $subjectArray = explode(':', $subject);
2258         $subject = $subjectArray[0];
2259         unset($subjectArray);
2260
2261         // Return it
2262         return $subject;
2263 }
2264
2265 // Translates generically some data into a target string
2266 function translateGeneric ($messagePrefix, $data) {
2267         // Is the method null or empty?
2268         if (is_null($data)) {
2269                 // Is NULL
2270                 $data = 'NULL';
2271         } elseif (empty($data)) {
2272                 // Is empty (string)
2273                 $data = 'EMPTY';
2274         } // END - if
2275
2276         // Default column name is unknown
2277         $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
2278
2279         // Construct message id
2280         $messageId = $messagePrefix . '_' . strtoupper($data);
2281
2282         // Is it there?
2283         if (isMessageIdValid($messageId)) {
2284                 // Then use it as message string
2285                 $return = '{--' . $messageId . '--}';
2286         } // END - if
2287
2288         // Return the column name
2289         return $return;
2290 }
2291
2292 // Translates task type to a human-readable version
2293 function translateTaskType ($taskType) {
2294         // Return it
2295         return translateGeneric('ADMIN_TASK_TYPE', $taskType);
2296 }
2297
2298 // ----------------------------------------------------------------------------
2299 //              "Translatation" functions for points_data table
2300 // ----------------------------------------------------------------------------
2301
2302 // Translates points subject to human-readable
2303 function translatePointsSubject ($subject) {
2304         // Remove any :x
2305         $subject = removeDoubleDotFromSubject($subject);
2306
2307         // Return it
2308         return translateGeneric('POINTS_SUBJECT', $subject);
2309 }
2310
2311 // "Translates" the given points account type
2312 function translatePointsAccountType ($accountType) {
2313         // Return it
2314         return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType);
2315 }
2316
2317 // "Translates" the given points "locked mode"
2318 function translatePointsLockedMode ($lockedMode) {
2319         // Return it
2320         return translateGeneric('POINTS_LOCKED_MODE', $lockedMode);
2321 }
2322
2323 // "Translates" the given points payment method
2324 function translatePointsPaymentMethod ($paymentMethod) {
2325         // Return it
2326         return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod);
2327 }
2328
2329 // "Translates" the given points account provider
2330 function translatePointsAccountProvider ($accountProvider) {
2331         // Return it
2332         return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider);
2333 }
2334
2335 // "Translates" the given points notify recipient
2336 function translatePointsNotifyRecipient ($notifyRecipient) {
2337         // Return it
2338         return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
2339 }
2340
2341 //-----------------------------------------------------------------------------
2342 // Automatically re-created functions, all taken from user comments on www.php.net
2343 //-----------------------------------------------------------------------------
2344 if (!function_exists('html_entity_decode')) {
2345         // Taken from documentation on www.php.net
2346         function html_entity_decode ($string) {
2347                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2348                 $trans_tbl = array_flip($trans_tbl);
2349                 return strtr($string, $trans_tbl);
2350         }
2351 } // END - if
2352
2353 // [EOF]
2354 ?>