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