HTTP status codes added for missing/locked modules, fixed double-logging of debug...
[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-MySQL functions (also file access)      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
46 function outputHtml ($htmlCode, $newLine = true) {
47         // Init output
48         if (!isset($GLOBALS['output'])) {
49                 $GLOBALS['output'] = '';
50         } // END - if
51
52         // Transfer username
53         $username = getMessage('USERNAME_UNKNOWN');
54         if (isset($GLOBALS['username'])) $username = getUsername();
55
56         // Do we have HTML-Code here?
57         if (!empty($htmlCode)) {
58                 // Yes, so we handle it as you have configured
59                 switch (getConfig('OUTPUT_MODE')) {
60                         case 'render':
61                                 // That's why you don't need any \n at the end of your HTML code... :-)
62                                 if (getPhpCaching() == 'on') {
63                                         // Output into PHP's internal buffer
64                                         outputRawCode($htmlCode);
65
66                                         // That's why you don't need any \n at the end of your HTML code... :-)
67                                         if ($newLine === true) print("\n");
68                                 } else {
69                                         // Render mode for old or lame servers...
70                                         $GLOBALS['output'] .= $htmlCode;
71
72                                         // That's why you don't need any \n at the end of your HTML code... :-)
73                                         if ($newLine === true) $GLOBALS['output'] .= "\n";
74                                 }
75                                 break;
76
77                         case 'direct':
78                                 // If we are switching from render to direct output rendered code
79                                 if ((!empty($GLOBALS['output'])) && (getPhpCaching() != 'on')) { outputRawCode($GLOBALS['output']); $GLOBALS['output'] = ''; }
80
81                                 // The same as above... ^
82                                 outputRawCode($htmlCode);
83                                 if ($newLine === true) print("\n");
84                                 break;
85
86                         default:
87                                 // Huh, something goes wrong or maybe you have edited config.php ???
88                                 debug_report_bug(__FUNCTION__, __LINE__, '<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}');
89                                 break;
90                 } // END - switch
91         } elseif ((getPhpCaching() == 'on') && ((!isset($GLOBALS['header'])) || (count($GLOBALS['header']) == 0))) {
92                 // Output cached HTML code
93                 $GLOBALS['output'] = ob_get_contents();
94
95                 // Clear output buffer for later output if output is found
96                 if (!empty($GLOBALS['output'])) {
97                         clearOutputBuffer();
98                 } // END - if
99
100                 // Send all HTTP headers
101                 sendHttpHeaders();
102
103                 // Compile and run finished rendered HTML code
104                 compileFinalOutput();
105
106                 // Output code here, DO NOT REMOVE! ;-)
107                 outputRawCode($GLOBALS['output']);
108         } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($GLOBALS['output']))) {
109                 // Send all HTTP headers
110                 sendHttpHeaders();
111
112                 // Compile and run finished rendered HTML code
113                 compileFinalOutput();
114
115                 // Output code here, DO NOT REMOVE! ;-)
116                 outputRawCode($GLOBALS['output']);
117         } else {
118                 // And flush all headers
119                 flushHeaders();
120         }
121 }
122
123 // Sends out all headers required for HTTP/1.1 reply
124 function sendHttpHeaders () {
125         // Used later
126         $now = gmdate('D, d M Y H:i:s') . ' GMT';
127
128         // Send HTTP header
129         sendHeader('HTTP/1.1 ' . getHttpStatus());
130
131         // General headers for no caching
132         sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
133         sendHeader('Last-Modified: ' . $now);
134         sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
135         sendHeader('Pragma: no-cache'); // HTTP/1.0
136         sendHeader('Connection: Close');
137         sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
138         sendHeader('Content-Language: ' . getLanguage());
139 }
140
141 // Compiles the final output
142 function compileFinalOutput () {
143         // Init counter
144         $cnt = 0;
145
146         // Add page header and footer
147         addPageHeaderFooter();
148
149         // Compile all out
150         while (((strpos($GLOBALS['output'], '{--') !== false) || (strpos($GLOBALS['output'], '{DQUOTE}') !== false) || (strpos($GLOBALS['output'], '{!') !== false) || (strpos($GLOBALS['output'], '{?') !== false) || (strpos($GLOBALS['output'], '{%') !== false)) && ($cnt < 3)) {
151                 // Init common variables
152                 $content = array();
153                 $newContent = '';
154
155                 // Compile it
156                 //* DEBUG: */ print '<pre>'.htmlentities($GLOBALS['output']).'</pre>';
157                 $eval = '$newContent = "' . str_replace('{DQUOTE}', '"', compileCode(escapeQuotes($GLOBALS['output']))) . '";';
158                 //* DEBUG: */ die('<pre>'.htmlentities($eval).'</pre>');
159                 eval($eval);
160                 //* DEBUG: */ die('<pre>'.htmlentities($newContent).'</pre>');
161
162                 // Was that eval okay?
163                 if (empty($newContent)) {
164                         // Something went wrong!
165                         debug_report_bug(__FUNCTION__, __LINE__, 'Evaluation error:<pre>' . linenumberCode($eval) . '</pre>', false);
166                 } // END - if
167
168                 // Use it again
169                 $GLOBALS['output'] = $newContent;
170
171                 // Count round
172                 $cnt++;
173         } // END - while
174
175         // Extension 'rewrite' installed?
176         if ((isExtensionActive('rewrite')) && (getOutputMode() != 1)) {
177                 $GLOBALS['output'] = rewriteLinksInCode($GLOBALS['output']);
178         } // END - if
179
180         // Compress it?
181         if (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('gzip', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
182                 // Compress it for HTTP gzip
183                 $GLOBALS['output'] = gzencode($GLOBALS['output'], 9, true);
184
185                 // Add header
186                 sendHeader('Content-Encoding: gzip');
187         } elseif (!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos('deflate', $_SERVER['HTTP_ACCEPT_ENCODING']) !== null)) {
188                 // Compress it for HTTP deflate
189                 $GLOBALS['output'] = gzcompress($GLOBALS['output'], 9);
190
191                 // Add header
192                 sendHeader('Content-Encoding: deflate');
193         }
194
195         // Add final length
196         sendHeader('Content-Length: ' . strlen($GLOBALS['output']));
197
198         // Flush all headers
199         flushHeaders();
200 }
201
202 // Output the raw HTML code
203 function outputRawCode ($htmlCode) {
204         // Output stripped HTML code to avoid broken JavaScript code, etc.
205         print(str_replace('{BACK}', "\\", $htmlCode));
206
207         // Flush the output if only getPhpCaching() is not 'on'
208         if (getPhpCaching() != 'on') {
209                 // Flush it
210                 flush();
211         } // END - if
212 }
213
214 // Init fatal message array
215 function initFatalMessages () {
216         $GLOBALS['fatal_messages'] = array();
217 }
218
219 // Getter for whole fatal error messages
220 function getFatalArray () {
221         return $GLOBALS['fatal_messages'];
222 }
223
224 // Add a fatal error message to the queue array
225 function addFatalMessage ($F, $L, $message, $extra = '') {
226         if (is_array($extra)) {
227                 // Multiple extras for a message with masks
228                 $message = call_user_func_array('sprintf', $extra);
229         } elseif (!empty($extra)) {
230                 // $message is text with a mask plus extras to insert into the text
231                 $message = sprintf($message, $extra);
232         }
233
234         // Add message to $GLOBALS['fatal_messages']
235         $GLOBALS['fatal_messages'][] = $message;
236
237         // Log fatal messages away
238         logDebugMessage($F, $L, 'Fatal error message: ' . $message);
239 }
240
241 // Getter for total fatal message count
242 function getTotalFatalErrors () {
243         // Init coun
244         $count = '0';
245
246         // Do we have at least the first entry?
247         if (!empty($GLOBALS['fatal_messages'][0])) {
248                 // Get total count
249                 $count = count($GLOBALS['fatal_messages']);
250         } // END - if
251
252         // Return value
253         return $count;
254 }
255
256 // Load a template file and return it's content (only it's name; do not use ' or ")
257 function loadTemplate ($template, $return = false, $content = array()) {
258         // @TODO Remove this sanity-check if all is fine
259         if (!is_bool($return)) debug_report_bug(__FUNCTION__, __LINE__, 'return is not bool (' . gettype($return) . ')');
260
261         // @TODO Try to rewrite all $DATA to $content
262         global $DATA;
263
264         // Do we have cache?
265         if (isTemplateCached($template)) {
266                 // Evaluate the cache
267                 eval(readTemplateCache($template));
268         } elseif (!isset($GLOBALS['template_eval'][$template])) {
269                 // Add more variables which you want to use in your template files
270                 $username = getUsername();
271
272                 // Make all template names lowercase
273                 $template = strtolower($template);
274
275                 // Init some data
276                 $ret = '';
277                 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = '0';
278
279                 // Base directory
280                 $basePath = sprintf("%stemplates/%s/html/", getConfig('PATH'), getLanguage());
281                 $extraPath = detectExtraTemplatePath($template);;
282
283                 ////////////////////////
284                 // Generate file name //
285                 ////////////////////////
286                 $FQFN = $basePath . $extraPath . $template . '.tpl';
287
288                 // Does the special template exists?
289                 if (!isFileReadable($FQFN)) {
290                         // Reset to default template
291                         $FQFN = $basePath . $template . '.tpl';
292                 } // END - if
293
294                 // Now does the final template exists?
295                 if (isFileReadable($FQFN)) {
296                         // Count the template load
297                         incrementConfigEntry('num_templates');
298
299                         // The local file does exists so we load it. :)
300                         $GLOBALS['tpl_content'] = readFromFile($FQFN);
301
302                         // Do we have to compile the code?
303                         $ret = '';
304                         if ((strpos($GLOBALS['tpl_content'], '$') !== false) || (strpos($GLOBALS['tpl_content'], '{--') !== false) || (strpos($GLOBALS['tpl_content'], '{!') !== false) || (strpos($GLOBALS['tpl_content'], '{?') !== false) || (strpos($GLOBALS['tpl_content'], '{%') !== false)) {
305                                 // Normal HTML output?
306                                 if (getOutputMode() == '0') {
307                                         // Add surrounding HTML comments to help finding bugs faster
308                                         $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
309
310                                         // Prepare eval() command
311                                         $eval = '$ret = "' . compileCode(escapeQuotes($ret)) . '";';
312                                 } elseif (substr($template, 0, 3) == 'js_') {
313                                         // JavaScripts don't like entities and timings
314                                         $eval = '$ret = decodeEntities("' . compileRawCode(escapeJavaScriptQuotes($GLOBALS['tpl_content'])) . '");';
315                                 } else {
316                                         // Prepare eval() command, other output doesn't like entities, maybe
317                                         $eval = '$ret = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
318                                 }
319                         } else {
320                                 // Add surrounding HTML comments to help finding bugs faster
321                                 $ret = '<!-- Template ' . $template . " - Start -->\n" . $GLOBALS['tpl_content'] . '<!-- Template ' . $template . " - End -->\n";
322                                 $eval = '$ret = "' . compileRawCode(escapeQuotes($ret)) . '";';
323                         } // END - if
324
325                         // Cache the eval() command here
326                         $GLOBALS['template_eval'][$template] = $eval;
327                 } elseif ((isAdmin()) || ((isInstalling()) && (!isInstalled()))) {
328                         // Only admins shall see this warning or when installation mode is active
329                         $ret = '<br /><span class="guest_failed">{--TEMPLATE_404--}</span><br />
330 (' . $template . ')<br />
331 <br />
332 {--TEMPLATE_CONTENT--}
333 <pre>' . print_r($content, true) . '</pre>
334 {--TEMPLATE_DATA--}
335 <pre>' . print_r($DATA, true) . '</pre>
336 <br /><br />';
337                 } else {
338                         // No file!
339                         $GLOBALS['template_eval'][$template] = '404';
340                 }
341         }
342
343         // Code set?
344         if ((isset($GLOBALS['template_eval'][$template])) && ($GLOBALS['template_eval'][$template] != '404')) {
345                 // Eval the code
346                 eval($GLOBALS['template_eval'][$template]);
347         } // END - if
348
349         // Do we have some content to output or return?
350         if (!empty($ret)) {
351                 // Not empty so let's put it out! ;)
352                 if ($return === true) {
353                         // Return the HTML code
354                         return $ret;
355                 } else {
356                         // Output directly
357                         outputHtml($ret);
358                 }
359         } elseif (isDebugModeEnabled()) {
360                 // Warning, empty output!
361                 return 'E:' . $template . ',content=<pre>' . print_r($content, true) . '</pre>';
362         }
363 }
364
365 // Detects the extra template path from given template name
366 function detectExtraTemplatePath ($template) {
367         // Default is empty
368         $extraPath = '';
369
370         // Do we have cache?
371         if (!isset($GLOBALS['extra_path'][$template])) {
372                 // Check for admin/guest/member/etc. templates
373                 if (substr($template, 0, 6) == 'admin_') {
374                         // Admin template found
375                         $extraPath = 'admin/';
376                 } elseif (substr($template, 0, 6) == 'guest_') {
377                         // Guest template found
378                         $extraPath = 'guest/';
379                 } elseif (substr($template, 0, 7) == 'member_') {
380                         // Member template found
381                         $extraPath = 'member/';
382                 } elseif (substr($template, 0, 7) == 'select_') {
383                         // Selection template found
384                         $extraPath = 'select/';
385                 } elseif (substr($template, 0, 8) == 'install_') {
386                         // Installation template found
387                         $extraPath = 'install/';
388                 } elseif (substr($template, 0, 4) == 'ext_') {
389                         // Extension template found
390                         $extraPath = 'ext/';
391                 } elseif (substr($template, 0, 3) == 'la_') {
392                         // 'Logical-area' template found
393                         $extraPath = 'la/';
394                 } elseif (substr($template, 0, 3) == 'js_') {
395                         // JavaScript template found
396                         $extraPath = 'js/';
397                 } elseif (substr($template, 0, 5) == 'menu_') {
398                         // Menu template found
399                         $extraPath = 'menu/';
400                 } else {
401                         // Test for extension
402                         $test = substr($template, 0, strpos($template, '_'));
403
404                         // Probe for valid extension name
405                         if (isExtensionNameValid($test)) {
406                                 // Set extra path to extension's name
407                                 $extraPath = $test . '/';
408                         } // END - if
409                 }
410
411                 // Store it in cache
412                 $GLOBALS['extra_path'][$template] = $extraPath;
413         } // END - if
414
415         // Return result
416         return $GLOBALS['extra_path'][$template];
417 }
418
419 // Loads an email template and compiles it
420 function loadEmailTemplate ($template, $content = array(), $userid = '0') {
421         global $DATA;
422
423         // Make sure all template names are lowercase!
424         $template = strtolower($template);
425
426         // Default 'nickname' if extension is not installed
427         $nick = '---';
428
429         // Neutral email address is default
430         $email = getConfig('WEBMASTER');
431
432         // Is content an array?
433         if (is_array($content)) {
434                 // Add expiration to array
435                 if ((isConfigEntrySet('auto_purge')) && (getConfig('auto_purge') == '0')) {
436                         // Will never expire!
437                         $content['expiration'] = getMessage('MAIL_WILL_NEVER_EXPIRE');
438                 } elseif (isConfigEntrySet('auto_purge')) {
439                         // Create nice date string
440                         $content['expiration'] = createFancyTime(getConfig('auto_purge'));
441                 } else {
442                         // Missing entry
443                         $content['expiration'] = getMessage('MAIL_NO_CONFIG_AUTO_PURGE');
444                 }
445         } // END - if
446
447         // Load user's data
448         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "UID={$userid},template={$template},content[]=".gettype($content).'<br />');
449         if (($userid > 0) && (is_array($content))) {
450                 // If nickname extension is installed, fetch nickname as well
451                 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
452                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NICKNAME!<br />");
453                         // Load by nickname
454                         fetchUserData($userid, 'nickname');
455                 } else {
456                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "NO-NICK!<br />");
457                         /// Load by userid
458                         fetchUserData($userid);
459                 }
460
461                 // Merge data if valid
462                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - PRE<br />");
463                 if (isUserDataValid()) {
464                         $content = merge_array($content, getUserDataArray());
465                 } // END - if
466                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "content()=".count($content)." - AFTER<br />");
467         } // END - if
468
469         // Translate M to male or F to female if present
470         if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
471
472         // Overwrite email from data if present
473         if (isset($content['email'])) $email = $content['email'];
474
475         // Store email for some functions in global $DATA array
476         // @TODO Do only use $content, not $DATA or raw variables
477         $DATA['email'] = $email;
478
479         // Base directory
480         $basePath = sprintf("%stemplates/%s/emails/", getConfig('PATH'), getLanguage());
481
482         // Detect extra path
483         $extraPath = detectExtraTemplatePath($template);
484
485         // Generate full FQFN
486         $FQFN = $basePath . $extraPath . $template . '.tpl';
487
488         // Does the special template exists?
489         if (!isFileReadable($FQFN)) {
490                 // Reset to default template
491                 $FQFN = $basePath . $template . '.tpl';
492         } // END - if
493
494         // Now does the final template exists?
495         $newContent = '';
496         if (isFileReadable($FQFN)) {
497                 // The local file does exists so we load it. :)
498                 $GLOBALS['tpl_content'] = readFromFile($FQFN);
499
500                 // Run code
501                 $GLOBALS['tpl_content'] = '$newContent = decodeEntities("' . compileRawCode(escapeQuotes($GLOBALS['tpl_content'])) . '");';
502                 eval($GLOBALS['tpl_content']);
503         } elseif (!empty($template)) {
504                 // Template file not found!
505                 $newContent = '{--TEMPLATE_404--}: ' . $template . '<br />
506 {--TEMPLATE_CONTENT--}
507 <pre>' . print_r($content, true) . '</pre>
508 {--TEMPLATE_DATA--}
509 <pre>' . print_r($DATA, true) . '</pre>
510 <br /><br />';
511
512                 // Debug mode not active? Then remove the HTML tags
513                 if (!isDebugModeEnabled()) $newContent = secureString($newContent);
514         } else {
515                 // No template name supplied!
516                 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
517         }
518
519         // Is there some content?
520         if (empty($newContent)) {
521                 // Compiling failed
522                 $newContent = "Compiler error for template " . $template . " !\nUncompiled content:\n" . $GLOBALS['tpl_content'];
523
524                 // Add last error if the required function exists
525                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
526         } // END - if
527
528         // Remove content and data
529         unset($content);
530         unset($DATA);
531
532         // Return content
533         return $newContent;
534 }
535
536 // Send mail out to an email address
537 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
538         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail},SUBJECT={$subject}<br />");
539
540         // Compile subject line (for POINTS constant etc.)
541         eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
542
543         // Set from header
544         if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
545                 // Value detected, is the message extension installed?
546                 // @TODO Extension 'msg' does not exist
547                 if (isExtensionActive('msg')) {
548                         ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
549                         return;
550                 } else {
551                         // Does the user exist?
552                         if (fetchUserData($toEmail)) {
553                                 // Get the email
554                                 $toEmail = getUserData('email');
555                         } else {
556                                 // Set webmaster
557                                 $toEmail = getConfig('WEBMASTER');
558                         }
559                 }
560         } elseif ($toEmail == '0') {
561                 // Is the webmaster!
562                 $toEmail = getConfig('WEBMASTER');
563         }
564         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}<br />");
565
566         // Check for PHPMailer or debug-mode
567         if (!checkPhpMailerUsage()) {
568                 // Not in PHPMailer-Mode
569                 if (empty($mailHeader)) {
570                         // Load email header template
571                         $mailHeader = loadEmailTemplate('header');
572                 } else {
573                         // Append header
574                         $mailHeader .= loadEmailTemplate('header');
575                 }
576         } elseif (isDebugModeEnabled()) {
577                 if (empty($mailHeader)) {
578                         // Load email header template
579                         $mailHeader = loadEmailTemplate('header');
580                 } else {
581                         // Append header
582                         $mailHeader .= loadEmailTemplate('header');
583                 }
584         }
585
586         // Compile "TO"
587         eval('$toEmail = "' . compileRawCode(escapeQuotes($toEmail)) . '";');
588
589         // Compile "MSG"
590         eval('$message = "' . str_replace('$', '&#36;', compileRawCode(escapeQuotes($message))) . '";');
591
592         // Fix HTML parameter (default is no!)
593         if (empty($isHtml)) $isHtml = 'N';
594         if (isDebugModeEnabled()) {
595                 // In debug mode we want to display the mail instead of sending it away so we can debug this part
596                 outputHtml('<pre>
597 Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . '
598 To      : ' . htmlentities(utf8_decode($toEmail)) . '
599 Subject : ' . htmlentities(utf8_decode($subject)) . '
600 Message : ' . htmlentities(utf8_decode($message)) . '
601 </pre>');
602         } elseif (($isHtml == 'Y') && (isExtensionActive('html_mail'))) {
603                 // Send mail as HTML away
604                 return sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
605         } elseif (!empty($toEmail)) {
606                 // Send Mail away
607                 return sendRawEmail($toEmail, $subject, $message, $mailHeader);
608         } elseif ($isHtml != 'Y') {
609                 // Problem found!
610                 return sendRawEmail(getConfig('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
611         }
612 }
613
614 // Check to use wether legacy mail() command or PHPMailer class
615 // @TODO Rewrite this to an extension 'smtp'
616 // @private
617 function checkPhpMailerUsage() {
618         return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
619 }
620
621 // Send out a raw email with PHPMailer class or legacy mail() command
622 function sendRawEmail ($toEmail, $subject, $message, $from) {
623         // Just compile all again, to put out all configs, etc.
624         eval('$toEmail = decodeEntities("' . compileRawCode(escapeQuotes($toEmail)) . '");');
625         eval('$subject = decodeEntities("' . compileRawCode(escapeQuotes($subject)) . '");');
626         eval('$message = decodeEntities("' . compileRawCode(escapeQuotes($message)) . '");');
627         eval('$from    = decodeEntities("' . compileRawCode(escapeQuotes($from))    . '");');
628
629         // Shall we use PHPMailer class or legacy mode?
630         if (checkPhpMailerUsage()) {
631                 // Use PHPMailer class with SMTP enabled
632                 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
633                 loadIncludeOnce('inc/phpmailer/class.smtp.php');
634
635                 // get new instance
636                 $mail = new PHPMailer();
637
638                 // Set charset to UTF-8
639                 $mail->CharSet = 'UTF-8';
640
641                 // Path for PHPMailer
642                 $mail->PluginDir  = sprintf("%sinc/phpmailer/", getConfig('PATH'));
643
644                 $mail->IsSMTP();
645                 $mail->SMTPAuth   = true;
646                 $mail->Host       = getConfig('SMTP_HOSTNAME');
647                 $mail->Port       = 25;
648                 $mail->Username   = getConfig('SMTP_USER');
649                 $mail->Password   = getConfig('SMTP_PASSWORD');
650                 if (empty($from)) {
651                         $mail->From = getConfig('WEBMASTER');
652                 } else {
653                         $mail->From = $from;
654                 }
655                 $mail->FromName   = getConfig('MAIN_TITLE');
656                 $mail->Subject    = $subject;
657                 if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) {
658                         $mail->Body       = $message;
659                         $mail->AltBody    = 'Your mail program required HTML support to read this mail!';
660                         $mail->WordWrap   = 70;
661                         $mail->IsHTML(true);
662                 } else {
663                         $mail->Body       = decodeEntities($message);
664                 }
665                 $mail->AddAddress($toEmail, '');
666                 $mail->AddReplyTo(getConfig('WEBMASTER'), getConfig('MAIN_TITLE'));
667                 $mail->AddCustomHeader('Errors-To:' . getConfig('WEBMASTER'));
668                 $mail->AddCustomHeader('X-Loop:' . getConfig('WEBMASTER'));
669                 $mail->Send();
670
671                 // Has an error occured?
672                 if (!empty($mail->ErrorInfo)) {
673                         // Log message
674                         logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo);
675
676                         // Raise an error
677                         return false;
678                 } else {
679                         // All fine!
680                         return true;
681                 }
682         } else {
683                 // Use legacy mail() command
684                 return mail($toEmail, $subject, decodeEntities($message), $from);
685         }
686 }
687
688 // Generate a password in a specified length or use default password length
689 function generatePassword ($length = '0') {
690         // Auto-fix invalid length of zero
691         if ($length == '0') $length = getConfig('pass_len');
692
693         // Initialize array with all allowed chars
694         $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,-,+,_,/,.');
695
696         // Start creating password
697         $PASS = '';
698         for ($i = '0'; $i < $length; $i++) {
699                 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
700         } // END - for
701
702         // When the size is below 40 we can also add additional security by scrambling
703         // it. Otherwise we may corrupt hashes
704         if (strlen($PASS) <= 40) {
705                 // Also scramble the password
706                 $PASS = scrambleString($PASS);
707         } // END - if
708
709         // Return the password
710         return $PASS;
711 }
712
713 // Generates a human-readable timestamp from the Uni* stamp
714 function generateDateTime ($time, $mode = '0') {
715         // Filter out numbers
716         $time = bigintval($time);
717
718         // If the stamp is zero it mostly didn't "happen"
719         if ($time == '0') {
720                 // Never happend
721                 return getMessage('NEVER_HAPPENED');
722         } // END - if
723
724         switch (getLanguage()) {
725                 case 'de': // German date / time format
726                         switch ($mode) {
727                                 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
728                                 case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break;
729                                 case '2': $ret = date('d.m.Y|H:i', $time); break;
730                                 case '3': $ret = date('d.m.Y', $time); break;
731                                 default:
732                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
733                                         break;
734                         }
735                         break;
736
737                 default: // Default is the US date / time format!
738                         switch ($mode) {
739                                 case '0': $ret = date('r', $time); break;
740                                 case '1': $ret = date('Y-m-d - g:i A', $time); break;
741                                 case '2': $ret = date('y-m-d|H:i', $time); break;
742                                 case '3': $ret = date('y-m-d', $time); break;
743                                 default:
744                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
745                                         break;
746                         } // END - switch
747         } // END - switch
748
749         // Return result
750         return $ret;
751 }
752
753 // Translates Y/N to yes/no
754 function translateYesNo ($yn) {
755         // Default
756         $translated = '??? (' . $yn . ')';
757         switch ($yn) {
758                 case 'Y': $translated = getMessage('YES'); break;
759                 case 'N': $translated = getMessage('NO'); break;
760                 default:
761                         // Log unknown value
762                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
763                         break;
764         }
765
766         // Return it
767         return $translated;
768 }
769
770 // Translates the "pool type" into human-readable
771 function translatePoolType ($type) {
772         // Default?type is unknown
773         $translated = getMaskedMessage('POOL_TYPE_UNKNOWN', $type);
774
775         // Generate constant
776         $constName = sprintf("POOL_TYPE_%s", $type);
777
778         // Does it exist?
779         if (isMessageIdValid($constName)) {
780                 // Then use it
781                 $translated = getMessage($constName);
782         } // END - if
783
784         // Return "translation"
785         return $translated;
786 }
787
788 // Translates the american decimal dot into a german comma
789 function translateComma ($dotted, $cut = true, $max = '0') {
790         // First, cast all to double, due to PHP changes
791         $dotted = (double) $dotted;
792
793         // Default is 3 you can change this in admin area "Misc -> Misc Options"
794         if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3);
795
796         // Use from config is default
797         $maxComma = getConfig('max_comma');
798
799         // Use from parameter?
800         if ($max > 0) $maxComma = $max;
801
802         // Cut zeros off?
803         if (($cut === true) && ($max == '0')) {
804                 // Test for commata if in cut-mode
805                 $com = explode('.', $dotted);
806                 if (count($com) < 2) {
807                         // Don't display commatas even if there are none... ;-)
808                         $maxComma = '0';
809                 }
810         } // END - if
811
812         // Debug log
813         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
814
815         // Translate it now
816         switch (getLanguage()) {
817                 case 'de': // German language
818                         $dotted = number_format($dotted, $maxComma, ',', '.');
819                         break;
820
821                 default: // All others
822                         $dotted = number_format($dotted, $maxComma, '.', ',');
823                         break;
824         }
825
826         // Return translated value
827         return $dotted;
828 }
829
830 // Translate Uni*-like gender to human-readable
831 function translateGender ($gender) {
832         // Default
833         $ret = '!' . $gender . '!';
834
835         // Male/female or company?
836         switch ($gender) {
837                 case 'M': $ret = getMessage('GENDER_M'); break;
838                 case 'F': $ret = getMessage('GENDER_F'); break;
839                 case 'C': $ret = getMessage('GENDER_C'); break;
840                 default:
841                         // Please report bugs on unknown genders
842                         debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
843                         break;
844         } // END - switch
845
846         // Return translated gender
847         return $ret;
848 }
849
850 // "Translates" the user status
851 function translateUserStatus ($status) {
852         // Generate message depending on status
853         switch ($status) {
854                 case 'UNCONFIRMED':
855                 case 'CONFIRMED':
856                 case 'LOCKED':
857                         $ret = getMessage(sprintf("ACCOUNT_%s", $status));
858                         break;
859
860                 case '':
861                 case null:
862                         $ret = getMessage('ACCOUNT_DELETED');
863                         break;
864
865                 default:
866                         // Please report all unknown status
867                         debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
868                         break;
869         } // END - switch
870
871         // Return it
872         return $ret;
873 }
874
875 // Generates an URL for the dereferer
876 function generateDerefererUrl ($URL) {
877         // Don't de-refer our own links!
878         if (substr($URL, 0, strlen(getConfig('URL'))) != getConfig('URL')) {
879                 // De-refer this link
880                 $URL = '{%url=modules.php?module=loader&amp;url=' . encodeString(compileUriCode($URL)) . '%}';
881         } // END - if
882
883         // Return link
884         return $URL;
885 }
886
887 // Generates an URL for the frametester
888 function generateFrametesterUrl ($URL) {
889         // Prepare frametester URL
890         $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&amp;url=%s%%}",
891                 encodeString(compileUriCode($URL))
892         );
893
894         // Return the new URL
895         return $frametesterUrl;
896 }
897
898 // Count entries from e.g. a selection box
899 function countSelection ($array) {
900         // Integrity check
901         if (!is_array($array)) {
902                 // Not an array!
903                 debug_report_bug(__FUNCTION__.': No array provided.');
904         } // END - if
905
906         // Init count
907         $ret = '0';
908
909         // Count all entries
910         foreach ($array as $key => $selected) {
911                 // Is it checked?
912                 if (!empty($selected)) $ret++;
913         } // END - foreach
914
915         // Return counted selections
916         return $ret;
917 }
918
919 // Generate XHTML code for the CAPTCHA
920 function generateCaptchaCode ($code, $type, $DATA, $userid) {
921         return '<img border="0" alt="Code ' . $code . '" src="{%url=mailid_top.php?userid=' . $userid . '&amp;' . $type . '=' . $DATA . '&amp;mode=img&amp;code=' . $code . '%}" />';
922 }
923
924 // Generates a timestamp (some wrapper for mktime())
925 function makeTime ($hours, $minutes, $seconds, $stamp) {
926         // Extract day, month and year from given timestamp
927         $days   = date('d', $stamp);
928         $months = date('m', $stamp);
929         $years  = date('Y', $stamp);
930
931         // Create timestamp for wished time which depends on extracted date
932         return mktime(
933                 $hours,
934                 $minutes,
935                 $seconds,
936                 $months,
937                 $days,
938                 $years
939         );
940 }
941
942 // Redirects to an URL and if neccessarry extends it with own base URL
943 function redirectToUrl ($URL, $allowSpider = true) {
944         // Compile out codes
945         eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
946
947         // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
948         $rel = ' rel="external"';
949
950         // Do we have internal or external URL?
951         if (substr($URL, 0, strlen(getConfig('URL'))) == getConfig('URL')) {
952                 // Own (=internal) URL
953                 $rel = '';
954         } // END - if
955
956         // Three different ways to debug...
957         //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
958         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
959         //* DEBUG: */ die($URL);
960
961         // Simple probe for bots/spiders from search engines
962         if ((isSpider()) && ($allowSpider === true)) {
963                 // Secure the URL against bad things such als HTML insertions and so on...
964                 $URL = secureString($URL);
965
966                 // Set content-type here to fix a missing array element
967                 setContentType('text/html');
968
969                 // Output new location link as anchor
970                 outputHtml('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
971         } elseif (!headers_sent()) {
972                 // Clear own output buffer
973                 $GLOBALS['output'] = '';
974
975                 // Load URL when headers are not sent
976                 sendHeader('Location: '.str_replace('&amp;', '&', $URL));
977         } else {
978                 // Output error message
979                 loadInclude('inc/header.php');
980                 loadTemplate('redirect_url', false, str_replace('&amp;', '&', $URL));
981                 loadInclude('inc/footer.php');
982         }
983
984         // Shut the mailer down here
985         shutdown();
986 }
987
988 // Wrapper for redirectToUrl but URL comes from a configuration entry
989 function redirectToConfiguredUrl ($configEntry) {
990         // Get the URL
991         $URL = getConfig($configEntry);
992
993         // Is this URL set?
994         if (is_null($URL)) {
995                 // Then abort here
996                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Configuration entry %s is not set!", $configEntry));
997         } // END - if
998
999         // Load the URL
1000         redirectToUrl($URL);
1001 }
1002
1003 // Compiles the given HTML/mail code
1004 function compileCode ($code, $simple = false, $constants = true, $full = true) {
1005         // Is the code a string?
1006         if (!is_string($code)) {
1007                 // Silently return it
1008                 return $code;
1009         } // END - if
1010
1011         // Start couting
1012         $startCompile = microtime(true);
1013
1014         // Comile the code
1015         $code = compileRawCode($code, $simple, $constants, $full);
1016
1017         // Get timing
1018         $compiled = microtime(true);
1019
1020         // Add timing
1021         $code .= '<!-- Compilation time: ' . (($compiled - $startCompile) * 1000). 'ms //-->';
1022
1023         // Return compiled code
1024         return $code;
1025 }
1026
1027 // Compiles the code (use compileCode() only for HTML because of the comments)
1028 // @TODO $simple is deprecated
1029 function compileRawCode ($code, $simple = false, $constants = true, $full = true) {
1030         // Is the code a string?
1031         if (!is_string($code)) {
1032                 // Silently return it
1033                 return $code;
1034         } // END - if
1035
1036         // Init replacement-array with smaller set of security characters
1037         $secChars = $GLOBALS['url_chars'];
1038
1039         // Select full set of chars to replace when we e.g. want to compile URLs
1040         if ($full === true) $secChars = $GLOBALS['security_chars'];
1041
1042         // Compile more through a filter
1043         $code = runFilterChain('compile_code', $code);
1044
1045         // Compile constants
1046         if ($constants === true) {
1047                 // BEFORE 0.2.1 : Language and data constants
1048                 // WITH 0.2.1+  : Only language constants
1049                 $code = str_replace('{--', "\" . getMessage('", str_replace('--}', "') . \"", $code));
1050
1051                 // BEFORE 0.2.1 : Not used
1052                 // WITH 0.2.1+  : Data constants
1053                 $code = str_replace('{!', "\" . constant('", str_replace('!}', "') . \"", $code));
1054         } // END - if
1055
1056         // Compile QUOT and other non-HTML codes
1057         foreach ($secChars['to'] as $k => $to) {
1058                 // Do the reversed thing as in inc/libs/security_functions.php
1059                 $code = str_replace($to, $secChars['from'][$k], $code);
1060         } // END - foreach
1061
1062         // Find $content[bla][blub] entries
1063         // @TODO Do only use $content and deprecate $GLOBALS and $DATA in templates
1064         preg_match_all('/\$(content|GLOBALS|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1065
1066         // Are some matches found?
1067         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1068                 // Replace all matches
1069                 $matchesFound = array();
1070                 foreach ($matches[0] as $key => $match) {
1071                         // Fuzzy look has failed by default
1072                         $fuzzyFound = false;
1073
1074                         // Fuzzy look on match if already found
1075                         foreach ($matchesFound as $found => $set) {
1076                                 // Get test part
1077                                 $test = substr($found, 0, strlen($match));
1078
1079                                 // Does this entry exist?
1080                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "found={$found},match={$match},set={$set}<br />");
1081                                 if ($test == $match) {
1082                                         // Match found!
1083                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "fuzzyFound!<br />");
1084                                         $fuzzyFound = true;
1085                                         break;
1086                                 } // END - if
1087                         } // END - foreach
1088
1089                         // Skip this entry?
1090                         if ($fuzzyFound === true) continue;
1091
1092                         // Take all string elements
1093                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_" . $matches[4][$key]]))) {
1094                                 // Replace it in the code
1095                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "key={$key},match={$match}<br />");
1096                                 $newMatch = str_replace('[', "['", str_replace(']', "']", $match));
1097                                 $code = str_replace($match, '".' . $newMatch . '."', $code);
1098                                 $matchesFound[$key . '_' . $matches[4][$key]] = 1;
1099                                 $matchesFound[$match] = 1;
1100                         } elseif (!isset($matchesFound[$match])) {
1101                                 // Not yet replaced!
1102                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "match={$match}<br />");
1103                                 $code = str_replace($match, '".' . $match . '."', $code);
1104                                 $matchesFound[$match] = 1;
1105                         }
1106                 } // END - foreach
1107         } // END - if
1108
1109         // Return it
1110         return $code;
1111 }
1112
1113 /************************************************************************
1114  *                                                                      *
1115  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
1116  * $a_sort sortiert:                                                    *
1117  *                                                                      *
1118  * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1119  * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben    *
1120  * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird   *
1121  * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a             *
1122  * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren   *
1123  *                                                                      *
1124  * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array    *
1125  * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1126  * Sie, dass es doch nicht so schwer ist! :-)                           *
1127  *                                                                      *
1128  ************************************************************************/
1129 function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) {
1130         $dummy = $array;
1131         while ($primary_key < count($a_sort)) {
1132                 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1133                         foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1134                                 $match = false;
1135                                 if ($nums === false) {
1136                                         // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1137                                         if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1138                                 } elseif ($key != $key2) {
1139                                         // Sort numbers (E.g.: 9 < 10)
1140                                         if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1141                                         if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1))  $match = true;
1142                                 }
1143
1144                                 if ($match) {
1145                                         // We have found two different values, so let's sort whole array
1146                                         foreach ($dummy as $sort_key => $sort_val) {
1147                                                 $t                       = $dummy[$sort_key][$key];
1148                                                 $dummy[$sort_key][$key]  = $dummy[$sort_key][$key2];
1149                                                 $dummy[$sort_key][$key2] = $t;
1150                                                 unset($t);
1151                                         } // END - foreach
1152                                 } // END - if
1153                         } // END - foreach
1154                 } // END - foreach
1155
1156                 // Count one up
1157                 $primary_key++;
1158         } // END - while
1159
1160         // Write back sorted array
1161         $array = $dummy;
1162 }
1163
1164 //
1165 function addSelectionBox ($type, $default, $prefix = '', $id = '0', $class = 'register_select') {
1166         $OUT = '';
1167
1168         if ($type == 'yn') {
1169                 // This is a yes/no selection only!
1170                 if ($id > 0) $prefix .= '[' . $id . ']';
1171                 $OUT .= '<select name="' . $prefix . '" class="' . $class . '" size="1">';
1172         } else {
1173                 // Begin with regular selection box here
1174                 if (!empty($prefix)) $prefix .= "_";
1175                 $type2 = $type;
1176                 if ($id > 0) $type2 .= '[' . $id . ']';
1177                 $OUT .= '<select name="' . strtolower($prefix . $type2) . '" class="' . $class . '" size="1">';
1178         }
1179
1180         switch ($type) {
1181                 case 'day': // Day
1182                         for ($idx = 1; $idx < 32; $idx++) {
1183                                 $OUT .= '<option value="' . $idx . '"';
1184                                 if ($default == $idx) $OUT .= ' selected="selected"';
1185                                 $OUT .= '>' . $idx . '</option>';
1186                         } // END - for
1187                         break;
1188
1189                 case 'month': // Month
1190                         foreach ($GLOBALS['month_descr'] as $idx => $descr) {
1191                                 $OUT .= '<option value="' . $idx . '"';
1192                                 if ($default == $idx) $OUT .= ' selected="selected"';
1193                                 $OUT .= '>' . $descr . '</option>';
1194                         } // END - for
1195                         break;
1196
1197                 case 'year': // Year
1198                         // Get current year
1199                         $year = date('Y', time());
1200
1201                         // Use configured min age or fixed?
1202                         if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1203                                 // Configured
1204                                 $startYear = $year - getConfig('min_age');
1205                         } else {
1206                                 // Fixed 16 years
1207                                 $startYear = $year - 16;
1208                         }
1209
1210                         // Calculate earliest year (100 years old people can still enter Internet???)
1211                         $minYear = $year - 100;
1212
1213                         // Check if the default value is larger than minimum and bigger than actual year
1214                         if (($default > $minYear) && ($default >= $year)) {
1215                                 for ($idx = $year; $idx < ($year + 11); $idx++) {
1216                                         $OUT .= '<option value="' . $idx . '"';
1217                                         if ($default == $idx) $OUT .= ' selected="selected"';
1218                                         $OUT .= '>' . $idx . '</option>';
1219                                 } // END - for
1220                         } elseif ($default == -1) {
1221                                 // Current year minus 1
1222                                 for ($idx = $startYear; $idx <= ($year + 1); $idx++) {
1223                                         $OUT .= '<option value="' . $idx . '">' . $idx . '</option>';
1224                                 } // END - for
1225                         } else {
1226                                 // Get current year and subtract the configured minimum age
1227                                 $OUT .= '<option value="' . ($minYear - 1) . '">&lt;' . $minYear . '</option>';
1228                                 // Calculate earliest year depending on extension version
1229                                 if (isExtensionInstalledAndNewer('order', '0.2.1')) {
1230                                         // Use configured minimum age
1231                                         $year = date('Y', time()) - getConfig('min_age');
1232                                 } else {
1233                                         // Use fixed 16 years age
1234                                         $year = date('Y', time()) - 16;
1235                                 }
1236
1237                                 // Construct year selection list
1238                                 for ($idx = $minYear; $idx <= $year; $idx++) {
1239                                         $OUT .= '<option value="' . $idx . '"';
1240                                         if ($default == $idx) $OUT .= ' selected="selected"';
1241                                         $OUT .= '>' . $idx . '</option>';
1242                                 } // END - for
1243                         }
1244                         break;
1245
1246                 case 'sec':
1247                 case 'min':
1248                         for ($idx = 0; $idx < 60; $idx+=5) {
1249                                 if (strlen($idx) == 1) $idx = '0' . $idx;
1250                                 $OUT .= '<option value="' . $idx . '"';
1251                                 if ($default == $idx) $OUT .= ' selected="selected"';
1252                                 $OUT .= '>' . $idx . '</option>';
1253                         } // END - for
1254                         break;
1255
1256                 case 'hour':
1257                         for ($idx = 0; $idx < 24; $idx++) {
1258                                 if (strlen($idx) == 1) $idx = '0' . $idx;
1259                                 $OUT .= '<option value="' . $idx . '"';
1260                                 if ($default == $idx) $OUT .= ' selected="selected"';
1261                                 $OUT .= '>' . $idx . '</option>';
1262                         } // END - for
1263                         break;
1264
1265                 case 'yn':
1266                         $OUT .= '<option value="Y"';
1267                         if ($default == 'Y') $OUT .= ' selected="selected"';
1268                         $OUT .= '>{--YES--}</option><option value="N"';
1269                         if ($default != 'Y') $OUT .= ' selected="selected"';
1270                         $OUT .= '>{--NO--}</option>';
1271                         break;
1272         }
1273         $OUT .= '</select>';
1274         return $OUT;
1275 }
1276
1277 //
1278 // Deprecated : $length
1279 // Optional   : $DATA
1280 //
1281 function generateRandomCode ($length, $code, $userid, $DATA = '') {
1282         // Build server string
1283         $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
1284
1285         // Build key string
1286         $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY');
1287         if (isConfigEntrySet('secret_key'))  $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1288         if (isConfigEntrySet('file_hash'))   $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1289         $keys .= getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime'));
1290         if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1291
1292         // Build string from misc data
1293         $data   = $code . getConfig('ENCRYPT_SEPERATOR') . $userid . getConfig('ENCRYPT_SEPERATOR') . $DATA;
1294
1295         // Add more additional data
1296         if (isSessionVariableSet('u_hash'))         $data .= getConfig('ENCRYPT_SEPERATOR') . getSession('u_hash');
1297
1298         // Add referal id, language, theme and userid
1299         $data .= getConfig('ENCRYPT_SEPERATOR') . determineReferalId();
1300         $data .= getConfig('ENCRYPT_SEPERATOR') . getLanguage();
1301         $data .= getConfig('ENCRYPT_SEPERATOR') . getCurrentTheme();
1302         $data .= getConfig('ENCRYPT_SEPERATOR') . getMemberId();
1303
1304         // Calculate number for generating the code
1305         $a = $code + getConfig('_ADD') - 1;
1306
1307         if (isConfigEntrySet('master_salt')) {
1308                 // Generate hash with master salt from modula of number with the prime number and other data
1309                 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, getConfig('master_salt'));
1310
1311                 // Create number from hash
1312                 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1313         } else {
1314                 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1315                 $saltedHash = generateHash(($a % getConfig('_PRIME')) . getConfig('ENCRYPT_SEPERATOR') . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a, substr(sha1(getConfig('SITE_KEY')), 0, getConfig('salt_length')));
1316
1317                 // Create number from hash
1318                 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getConfig('rand_no') - $a + sqrt(getConfig('_ADD'))) / pi();
1319         }
1320
1321         // At least 10 numbers shall be secure enought!
1322         $len = getConfig('code_length');
1323         if ($len == '0') $len = $length;
1324         if ($len == '0') $len = 10;
1325
1326         // Cut off requested counts of number
1327         $return = substr(str_replace('.', '', $rcode), 0, $len);
1328
1329         // Done building code
1330         return $return;
1331 }
1332
1333 // Does only allow numbers
1334 function bigintval ($num, $castValue = true, $abortOnMismatch = true) {
1335         // Filter all numbers out
1336         $ret = preg_replace('/[^0123456789]/', '', $num);
1337
1338         // Shall we cast?
1339         if ($castValue === true) $ret = (double)$ret;
1340
1341         // Has the whole value changed?
1342         if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true)) {
1343                 // Log the values
1344                 debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret=' . $ret . ', num='. $num);
1345         } // END - if
1346
1347         // Return result
1348         return $ret;
1349 }
1350
1351 // Insert the code in $img_code into jpeg or PNG image
1352 function generateImageOrCode ($img_code, $headerSent = true) {
1353         // Is the code size oversized or shouldn't we display it?
1354         if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == '0')) {
1355                 // Stop execution of function here because of over-sized code length
1356                 debug_report_bug(__FUNCTION__, __LINE__, 'img_code ' . $img_code .' has invalid length. img_code()=' . strlen($img_code) . ' code_length=' . getConfig('code_length'));
1357         } elseif ($headerSent === false) {
1358                 // Return an HTML code here
1359                 return '<img src="{%url=img.php?code=' . $img_code . '%}" alt="Image" />';
1360         }
1361
1362         // Load image
1363         $img = sprintf("%s/theme/%s/images/code_bg.%s",
1364                 getConfig('PATH'),
1365                 getCurrentTheme(),
1366                 getConfig('img_type')
1367         );
1368
1369         // Is it readable?
1370         if (isFileReadable($img)) {
1371                 // Switch image type
1372                 switch (getConfig('img_type')) {
1373                         case 'jpg':
1374                                 // Okay, load image and hide all errors
1375                                 $image = imagecreatefromjpeg($img);
1376                                 break;
1377
1378                         case 'png':
1379                                 // Okay, load image and hide all errors
1380                                 $image = imagecreatefrompng($img);
1381                                 break;
1382                 } // END - switch
1383         } else {
1384                 // Exit function here
1385                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1386                 return;
1387         }
1388
1389         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1390         $text_color = imagecolorallocate($image, 0, 0, 0);
1391
1392         // Insert code into image
1393         imagestring($image, 5, 14, 2, $img_code, $text_color);
1394
1395         // Return to browser
1396         sendHeader('Content-Type: image/' . getConfig('img_type'));
1397
1398         // Output image with matching image factory
1399         switch (getConfig('img_type')) {
1400                 case 'jpg': imagejpeg($image); break;
1401                 case 'png': imagepng($image);  break;
1402         } // END - switch
1403
1404         // Remove image from memory
1405         imagedestroy($image);
1406 }
1407 // Create selection box or array of splitted timestamp
1408 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1409         // Do not continue if ONE_DAY is absend
1410         if (!isConfigEntrySet('ONE_DAY')) {
1411                 // And return the timestamp itself or empty array
1412                 if ($return_array === true) {
1413                         return array();
1414                 } else {
1415                         return $timestamp;
1416                 }
1417         } // END - if
1418
1419         // Calculate 2-seconds timestamp
1420         $stamp = round($timestamp);
1421         //* DEBUG: */ print("*" . $stamp.'/' . $timestamp."*<br />");
1422
1423         // Do we have a leap year?
1424         $SWITCH = '0';
1425         $TEST = date('Y', time()) / 4;
1426         $M1 = date('m', time());
1427         $M2 = date('m', (time() + $timestamp));
1428
1429         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1430         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02"))  $SWITCH = getConfig('ONE_DAY');
1431
1432         // First of all years...
1433         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1434         //* DEBUG: */ print("Y={$Y}<br />");
1435         // Next months...
1436         $M = abs(floor($timestamp / 2628000 - $Y * 12));
1437         //* DEBUG: */ print("M={$M}<br />");
1438         // Next weeks
1439         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('ONE_DAY')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) / 7)));
1440         //* DEBUG: */ print("W={$W}<br />");
1441         // Next days...
1442         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY'))) - $W * 7));
1443         //* DEBUG: */ print("D={$D}<br />");
1444         // Next hours...
1445         $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24) - $W * 7 * 24 - $D * 24));
1446         //* DEBUG: */ print("h={$h}<br />");
1447         // Next minutes..
1448         $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1449         //* DEBUG: */ print("m={$m}<br />");
1450         // And at last seconds...
1451         $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('ONE_DAY')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1452         //* DEBUG: */ print("s={$s}<br />");
1453
1454         // Is seconds zero and time is < 60 seconds?
1455         if (($s == '0') && ($timestamp < 60)) {
1456                 // Fix seconds
1457                 $s = round($timestamp);
1458         } // END - if
1459
1460         //
1461         // Now we convert them in seconds...
1462         //
1463         if ($return_array) {
1464                 // Just put all data in an array for later use
1465                 $OUT = array(
1466                         'YEARS'   => $Y,
1467                         'MONTHS'  => $M,
1468                         'WEEKS'   => $W,
1469                         'DAYS'    => $D,
1470                         'HOURS'   => $h,
1471                         'MINUTES' => $m,
1472                         'SECONDS' => $s
1473                 );
1474         } else {
1475                 // Generate table
1476                 $OUT  = '<div align="' . $align . '">';
1477                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" class="timebox_table dashed">';
1478                 $OUT .= '<tr>';
1479
1480                 if (isInString('Y', $display) || (empty($display))) {
1481                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_YEARS--}</strong></td>';
1482                 } // END - if
1483
1484                 if (isInString('M', $display) || (empty($display))) {
1485                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MONTHS--}</strong></td>';
1486                 } // END - if
1487
1488                 if (isInString('W', $display) || (empty($display))) {
1489                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_WEEKS--}</strong></td>';
1490                 } // END - if
1491
1492                 if (isInString('D', $display) || (empty($display))) {
1493                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_DAYS--}</strong></td>';
1494                 } // END - if
1495
1496                 if (isInString('h', $display) || (empty($display))) {
1497                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_HOURS--}</strong></td>';
1498                 } // END - if
1499
1500                 if (isInString('m', $display) || (empty($display))) {
1501                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_MINUTES--}</strong></td>';
1502                 } // END - if
1503
1504                 if (isInString('s', $display) || (empty($display))) {
1505                         $OUT .= '<td align="center" class="timebox_column bottom"><div class="tiny">{--_SECONDS--}</strong></td>';
1506                 } // END - if
1507
1508                 $OUT .= '</tr>';
1509                 $OUT .= '<tr>';
1510
1511                 if (isInString('Y', $display) || (empty($display))) {
1512                         // Generate year selection
1513                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ye" size="1">';
1514                         for ($idx = 0; $idx <= 10; $idx++) {
1515                                 $OUT .= '<option class="mini_select" value="' . $idx . '"';
1516                                 if ($idx == $Y) $OUT .= ' selected="selected"';
1517                                 $OUT .= '>' . $idx . '</option>';
1518                         } // END - for
1519                         $OUT .= '</select></td>';
1520                 } else {
1521                         $OUT .= '<input type="hidden" name="' . $prefix . '_ye" value="0" />';
1522                 }
1523
1524                 if (isInString('M', $display) || (empty($display))) {
1525                         // Generate month selection
1526                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mo" size="1">';
1527                         for ($idx = 0; $idx <= 11; $idx++) {
1528                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1529                                 if ($idx == $M) $OUT .= ' selected="selected"';
1530                                 $OUT .= '>' . $idx . '</option>';
1531                         } // END - for
1532                         $OUT .= '</select></td>';
1533                 } else {
1534                         $OUT .= '<input type="hidden" name="' . $prefix . '_mo" value="0" />';
1535                 }
1536
1537                 if (isInString('W', $display) || (empty($display))) {
1538                         // Generate week selection
1539                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_we" size="1">';
1540                         for ($idx = 0; $idx <= 4; $idx++) {
1541                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1542                                 if ($idx == $W) $OUT .= ' selected="selected"';
1543                                 $OUT .= '>' . $idx . '</option>';
1544                         } // END - for
1545                         $OUT .= '</select></td>';
1546                 } else {
1547                         $OUT .= '<input type="hidden" name="' . $prefix . '_we" value="0" />';
1548                 }
1549
1550                 if (isInString('D', $display) || (empty($display))) {
1551                         // Generate day selection
1552                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_da" size="1">';
1553                         for ($idx = 0; $idx <= 31; $idx++) {
1554                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1555                                 if ($idx == $D) $OUT .= ' selected="selected"';
1556                                 $OUT .= '>' . $idx . '</option>';
1557                         } // END - for
1558                         $OUT .= '</select></td>';
1559                 } else {
1560                         $OUT .= '<input type="hidden" name="' . $prefix . '_da" value="0" />';
1561                 }
1562
1563                 if (isInString('h', $display) || (empty($display))) {
1564                         // Generate hour selection
1565                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_ho" size="1">';
1566                         for ($idx = 0; $idx <= 23; $idx++) {
1567                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1568                                 if ($idx == $h) $OUT .= ' selected="selected"';
1569                                 $OUT .= '>' . $idx . '</option>';
1570                         } // END - for
1571                         $OUT .= '</select></td>';
1572                 } else {
1573                         $OUT .= '<input type="hidden" name="' . $prefix . '_ho" value="0" />';
1574                 }
1575
1576                 if (isInString('m', $display) || (empty($display))) {
1577                         // Generate minute selection
1578                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_mi" size="1">';
1579                         for ($idx = 0; $idx <= 59; $idx++) {
1580                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1581                                 if ($idx == $m) $OUT .= ' selected="selected"';
1582                                 $OUT .= '>' . $idx . '</option>';
1583                         } // END - for
1584                         $OUT .= '</select></td>';
1585                 } else {
1586                         $OUT .= '<input type="hidden" name="' . $prefix . '_mi" value="0" />';
1587                 }
1588
1589                 if (isInString('s', $display) || (empty($display))) {
1590                         // Generate second selection
1591                         $OUT .= '<td align="center"><select class="mini_select" name="' . $prefix . '_se" size="1">';
1592                         for ($idx = 0; $idx <= 59; $idx++) {
1593                                 $OUT .= '  <option class="mini_select" value="' . $idx . '"';
1594                                 if ($idx == $s) $OUT .= ' selected="selected"';
1595                                 $OUT .= '>' . $idx . '</option>';
1596                         } // END - for
1597                         $OUT .= '</select></td>';
1598                 } else {
1599                         $OUT .= '<input type="hidden" name="' . $prefix . '_se" value="0" />';
1600                 }
1601                 $OUT .= '</tr>';
1602                 $OUT .= '</table>';
1603                 $OUT .= '</div>';
1604         }
1605
1606         // Return generated HTML code
1607         return $OUT;
1608 }
1609
1610 //
1611 function createTimestampFromSelections ($prefix, $postData) {
1612         // Initial return value
1613         $ret = '0';
1614
1615         // Do we have a leap year?
1616         $SWITCH = '0';
1617         $TEST = date('Y', time()) / 4;
1618         $M1   = date('m', time());
1619
1620         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1621         if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02'))  $SWITCH = getConfig('ONE_DAY');
1622
1623         // First add years...
1624         $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
1625
1626         // Next months...
1627         $ret += $postData[$prefix . '_mo'] * 2628000;
1628
1629         // Next weeks
1630         $ret += $postData[$prefix . '_we'] * 604800;
1631
1632         // Next days...
1633         $ret += $postData[$prefix . '_da'] * 86400;
1634
1635         // Next hours...
1636         $ret += $postData[$prefix . '_ho'] * 3600;
1637
1638         // Next minutes..
1639         $ret += $postData[$prefix . '_mi'] * 60;
1640
1641         // And at last seconds...
1642         $ret += $postData[$prefix . '_se'];
1643
1644         // Return calculated value
1645         return $ret;
1646 }
1647
1648 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1649 function createFancyTime ($stamp) {
1650         // Get data array with years/months/weeks/days/...
1651         $data = createTimeSelections($stamp, '', '', '', true);
1652         $ret = '';
1653         foreach($data as $k => $v) {
1654                 if ($v > 0) {
1655                         // Value is greater than 0 "eval" data to return string
1656                         eval('$ret .= ", ".$v." {--_' . strtoupper($k) . '--}";');
1657                         break;
1658                 } // END - if
1659         } // END - foreach
1660
1661         // Do we have something there?
1662         if (strlen($ret) > 0) {
1663                 // Remove leading commata and space
1664                 $ret = substr($ret, 2);
1665         } else {
1666                 // Zero seconds
1667                 $ret = '0 {--_SECONDS--}';
1668         }
1669
1670         // Return fancy time string
1671         return $ret;
1672 }
1673
1674 // Generates a navigation row for listing emails
1675 function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
1676         $TOP = '';
1677         if ($show_form === false) {
1678                 $TOP = ' top';
1679         } // END - if
1680
1681         $NAV = '';
1682         for ($page = 1; $page <= $PAGES; $page++) {
1683                 // Is the page currently selected or shall we generate a link to it?
1684                 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1685                         // Is currently selected, so only highlight it
1686                         $NAV .= '<strong>-';
1687                 } else {
1688                         // Open anchor tag and add base URL
1689                         $NAV .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat() . '&amp;page=' . $page . '&amp;offset=' . $offset;
1690
1691                         // Add userid when we shall show all mails from a single member
1692                         if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&amp;userid=' . bigintval(getRequestParameter('userid'));
1693
1694                         // Close open anchor tag
1695                         $NAV .= '%}">';
1696                 }
1697                 $NAV .= $page;
1698                 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1699                         // Is currently selected, so only highlight it
1700                         $NAV .= '-</strong>';
1701                 } else {
1702                         // Close anchor tag
1703                         $NAV .= '</a>';
1704                 }
1705
1706                 // Add seperator if we have not yet reached total pages
1707                 if ($page < $PAGES) {
1708                         // Add it
1709                         $NAV .= '|';
1710                 } // END - if
1711         } // END - for
1712
1713         // Define constants only once
1714         $content['nav']  = $NAV;
1715         $content['span'] = $colspan;
1716         $content['top']  = $TOP;
1717
1718         // Load navigation template
1719         $OUT = loadTemplate('admin_email_nav_row', true, $content);
1720
1721         if ($return === true) {
1722                 // Return generated HTML-Code
1723                 return $OUT;
1724         } else {
1725                 // Output HTML-Code
1726                 outputHtml($OUT);
1727         }
1728 }
1729
1730 // Extract host from script name
1731 function extractHostnameFromUrl (&$script) {
1732         // Use default SERVER_URL by default... ;) So?
1733         $url = getConfig('SERVER_URL');
1734
1735         // Is this URL valid?
1736         if (substr($script, 0, 7) == 'http://') {
1737                 // Use the hostname from script URL as new hostname
1738                 $url = substr($script, 7);
1739                 $extract = explode('/', $url);
1740                 $url = $extract[0];
1741                 // Done extracting the URL :)
1742         } // END - if
1743
1744         // Extract host name
1745         $host = str_replace('http://', '', $url);
1746         if (isInString('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1747
1748         // Generate relative URL
1749         //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1750         if (substr(strtolower($script), 0, 7) == 'http://') {
1751                 // But only if http:// is in front!
1752                 $script = substr($script, (strlen($url) + 7));
1753         } elseif (substr(strtolower($script), 0, 8) == 'https://') {
1754                 // Does this work?!
1755                 $script = substr($script, (strlen($url) + 8));
1756         }
1757
1758         //* DEBUG: */ print('SCRIPT=' . $script.'<br />');
1759         if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1760
1761         // Return host name
1762         return $host;
1763 }
1764
1765 // Send a GET request
1766 function sendGetRequest ($script, $data = array()) {
1767         // Extract host name from script
1768         $host = extractHostnameFromUrl($script);
1769
1770         // Add data
1771         $body = http_build_query($data, '', '&');
1772
1773         // Do we have a question-mark in the script?
1774         if (strpos($script, '?') === false) {
1775                 // No, so first char must be question mark
1776                 $body = '?' . $body;
1777         } else {
1778                 // Ok, add &
1779                 $body = '&' . $body;
1780         }
1781
1782         // Add script data
1783         $script .= $body;
1784
1785         // Remove trailed & to make it more conform
1786         if (substr($script, -1, 1) == '&') $script = substr($script, 0, -1);
1787
1788         // Generate GET request header
1789         $request  = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1790         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1791         $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1792         if (isConfigEntrySet('FULL_VERSION')) {
1793                 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1794         } else {
1795                 $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
1796         }
1797         $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
1798         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1799         $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
1800         $request .= 'Connection: close' . getConfig('HTTP_EOL');
1801         $request .= getConfig('HTTP_EOL');
1802
1803         // Send the raw request
1804         $response = sendRawRequest($host, $request);
1805
1806         // Return the result to the caller function
1807         return $response;
1808 }
1809
1810 // Send a POST request
1811 function sendPostRequest ($script, $postData) {
1812         // Is postData an array?
1813         if (!is_array($postData)) {
1814                 // Abort here
1815                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1816                 return array('', '', '');
1817         } // END - if
1818
1819         // Extract host name from script
1820         $host = extractHostnameFromUrl($script);
1821
1822         // Construct request body
1823         $body = http_build_query($postData, '', '&');
1824
1825         // Generate POST request header
1826         $request  = 'POST /' . trim($script) . ' HTTP/1.0' . getConfig('HTTP_EOL');
1827         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1828         $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1829         $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1830         $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
1831         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
1832         $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1833         $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1834         $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
1835         $request .= 'Connection: close' . getConfig('HTTP_EOL');
1836         $request .= getConfig('HTTP_EOL');
1837
1838         // Add body
1839         $request .= $body;
1840
1841         // Send the raw request
1842         $response = sendRawRequest($host, $request);
1843
1844         // Return the result to the caller function
1845         return $response;
1846 }
1847
1848 // Sends a raw request to another host
1849 function sendRawRequest ($host, $request) {
1850         // Init errno and errdesc with 'all fine' values
1851         $errno = '0'; $errdesc = '';
1852
1853         // Initialize array
1854         $response = array('', '', '');
1855
1856         // Default is not to use proxy
1857         $useProxy = false;
1858
1859         // Are proxy settins set?
1860         if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1861                 // Then use it
1862                 $useProxy = true;
1863         } // END - if
1864
1865         // Load include
1866         loadIncludeOnce('inc/classes/resolver.class.php');
1867
1868         // Get resolver instance
1869         $resolver = new HostnameResolver();
1870
1871         // Open connection
1872         //* DEBUG: */ die('SCRIPT=' . $script.'<br />');
1873         if ($useProxy === true) {
1874                 // Resolve hostname into IP address
1875                 $ip = $resolver->resolveHostname(compileRawCode(getConfig('proxy_host')));
1876
1877                 // Connect to host through proxy connection
1878                 $fp = fsockopen($ip, bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1879         } else {
1880                 // Resolve hostname into IP address
1881                 $ip = $resolver->resolveHostname($host);
1882
1883                 // Connect to host directly
1884                 $fp = fsockopen($ip, 80, $errno, $errdesc, 30);
1885         }
1886
1887         // Is there a link?
1888         if (!is_resource($fp)) {
1889                 // Failed!
1890                 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
1891                 return $response;
1892         } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
1893                 // Cannot set non-blocking mode or timeout
1894                 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
1895                 return $response;
1896         }
1897
1898         // Do we use proxy?
1899         if ($useProxy === true) {
1900                 // Setup proxy tunnel
1901                 $response = setupProxyTunnel($host, $fp);
1902
1903                 // If the response is invalid, abort
1904                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
1905                         // Invalid response!
1906                         logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
1907                         return $response;
1908                 } // END - if
1909         } // END - if
1910
1911         // Write request
1912         fwrite($fp, $request);
1913
1914         // Start counting
1915         $start = microtime(true);
1916
1917         // Read response
1918         while (!feof($fp)) {
1919                 // Get info from stream
1920                 $info = stream_get_meta_data($fp);
1921
1922                 // Is it timed out? 15 seconds is a really patient...
1923                 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
1924                         // Timeout
1925                         logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
1926
1927                         // Abort here
1928                         break;
1929                 } // END - if
1930
1931                 // Get line from stream
1932                 $line = fgets($fp, 128);
1933
1934                 // Ignore empty lines because of non-blocking mode
1935                 if (empty($line)) {
1936                         // uslepp a little to avoid 100% CPU load
1937                         usleep(10);
1938
1939                         // Skip this
1940                         continue;
1941                 } // END - if
1942
1943                 // Add it to response
1944                 $response[] = trim($line);
1945         } // END - while
1946
1947         // Close socket
1948         fclose($fp);
1949
1950         // Time request if debug-mode is enabled
1951         if (isDebugModeEnabled()) {
1952                 // Add debug message...
1953                 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
1954         } // END - if
1955
1956         // Skip first empty lines
1957         $resp = $response;
1958         foreach ($resp as $idx => $line) {
1959                 // Trim space away
1960                 $line = trim($line);
1961
1962                 // Is this line empty?
1963                 if (empty($line)) {
1964                         // Then remove it
1965                         array_shift($response);
1966                 } else {
1967                         // Abort on first non-empty line
1968                         break;
1969                 }
1970         } // END - foreach
1971
1972         //* DEBUG: */ print('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
1973         //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1974
1975         // Proxy agent found or something went wrong?
1976         if (!isset($response[0])) {
1977                 // No response, maybe timeout
1978                 $response = array('', '', '');
1979                 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
1980         } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1981                 // Proxy header detected, so remove two lines
1982                 array_shift($response);
1983                 array_shift($response);
1984         } // END - if
1985
1986         // Was the request successfull?
1987         if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
1988                 // Not found / access forbidden
1989                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
1990                 $response = array('', '', '');
1991         } // END - if
1992
1993         // Return response
1994         return $response;
1995 }
1996
1997 // Sets up a proxy tunnel for given hostname and through resource
1998 function setupProxyTunnel ($host, $resource) {
1999         // Initialize array
2000         $response = array('', '', '');
2001
2002         // Generate CONNECT request header
2003         $proxyTunnel  = 'CONNECT ' . $host . ':80 HTTP/1.0' . getConfig('HTTP_EOL');
2004         $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
2005
2006         // Use login data to proxy? (username at least!)
2007         if (getConfig('proxy_username') != '') {
2008                 // Add it as well
2009                 $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . ':' . compileRawCode(getConfig('proxy_password')));
2010                 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
2011         } // END - if
2012
2013         // Add last new-line
2014         $proxyTunnel .= getConfig('HTTP_EOL');
2015         //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
2016
2017         // Write request
2018         fwrite($fp, $proxyTunnel);
2019
2020         // Got response?
2021         if (feof($fp)) {
2022                 // No response received
2023                 return $response;
2024         } // END - if
2025
2026         // Read the first line
2027         $resp = trim(fgets($fp, 10240));
2028         $respArray = explode(' ', $resp);
2029         if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
2030                 // Invalid response!
2031                 return $response;
2032         } // END - if
2033
2034         // All fine!
2035         return $respArray;
2036 }
2037
2038 // Taken from www.php.net isInStringIgnoreCase() user comments
2039 function isEmailValid ($email) {
2040         // Check first part of email address
2041         $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
2042
2043         //  Check domain
2044         $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
2045
2046         // Generate pattern
2047         $regex = '@^' . $first . '\@' . $domain . '$@iU';
2048
2049         // Return check result
2050         return preg_match($regex, $email);
2051 }
2052
2053 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2054 function isUrlValid ($URL, $compile=true) {
2055         // Trim URL a little
2056         $URL = trim(urldecode($URL));
2057         //* DEBUG: */ outputHtml($URL.'<br />');
2058
2059         // Compile some chars out...
2060         if ($compile === true) $URL = compileUriCode($URL, false, false, false);
2061         //* DEBUG: */ outputHtml($URL.'<br />');
2062
2063         // Check for the extension filter
2064         if (isExtensionActive('filter')) {
2065                 // Use the extension's filter set
2066                 return FILTER_VALIDATE_URL($URL, false);
2067         } // END - if
2068
2069         // If not installed, perform a simple test. Just make it sure there is always a http:// or
2070         // https:// in front of the URLs
2071         return isUrlValidSimple($URL);
2072 }
2073
2074 // Generate a list of administrative links to a given userid
2075 function generateMemberAdminActionLinks ($userid, $status = '') {
2076         // Make sure userid is a number
2077         if ($userid != bigintval($userid)) debug_report_bug(__FUNCTION__, __LINE__, 'userid is not a number!');
2078
2079         // Define all main targets
2080         $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2081
2082         // Begin of navigation links
2083         $OUT = '[';
2084
2085         foreach ($targetArray as $tar) {
2086                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;userid=' . $userid . '%}" title="{--ADMIN_LINK_';
2087                 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
2088                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2089                         // Locked accounts shall be unlocked
2090                         $OUT .= 'UNLOCK_USER';
2091                 } else {
2092                         // All other status is fine
2093                         $OUT .= strtoupper($tar);
2094                 }
2095                 $OUT .= '_TITLE--}">{--ADMIN_';
2096                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
2097                         // Locked accounts shall be unlocked
2098                         $OUT .= 'UNLOCK_USER';
2099                 } else {
2100                         // All other status is fine
2101                         $OUT .= strtoupper($tar);
2102                 }
2103                 $OUT .= '--}</a></span>|';
2104         }
2105
2106         // Finish navigation link
2107         $OUT = substr($OUT, 0, -7) . ']';
2108
2109         // Return string
2110         return $OUT;
2111 }
2112
2113 // Generate an email link
2114 function generateEmailLink ($email, $table = 'admins') {
2115         // Default email link (INSECURE! Spammer can read this by harvester programs)
2116         $EMAIL = 'mailto:' . $email;
2117
2118         // Check for several extensions
2119         if ((isExtensionActive('admins')) && ($table == 'admins')) {
2120                 // Create email link for contacting admin in guest area
2121                 $EMAIL = generateAdminEmailLink($email);
2122         } elseif ((isExtensionInstalledAndNewer('user', '0.3.3')) && ($table == 'user_data')) {
2123                 // Create email link for contacting a member within admin area (or later in other areas, too?)
2124                 $EMAIL = generateUserEmailLink($email, 'admin');
2125         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
2126                 // Create email link to contact sponsor within admin area (or like the link above?)
2127                 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
2128         }
2129
2130         // Shall I close the link when there is no admin?
2131         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2132
2133         // Return email link
2134         return $EMAIL;
2135 }
2136
2137 // Generate a hash for extra-security for all passwords
2138 function generateHash ($plainText, $salt = '', $hash = true) {
2139         // Debug output
2140         //* DEBUG: */ outputHtml('plainText=' . $plainText . ',salt=' . $salt . ',hash='.intval($hash).'<br />');
2141
2142         // Is the required extension 'sql_patches' there and a salt is not given?
2143         // 0123                            4                      43    3     4     432    2                  3             32    2                             3                3210
2144         if ((((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')))) {
2145                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2146                 if ($hash === true) {
2147                         // Is plain password
2148                         return md5($plainText);
2149                 } else {
2150                         // Is already a hash
2151                         return $plainText;
2152                 }
2153         } // END - if
2154
2155         // Do we miss an arry element here?
2156         if (!isConfigEntrySet('file_hash')) {
2157                 // Stop here
2158                 debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
2159         } // END - if
2160
2161         // When the salt is empty build a new one, else use the first x configured characters as the salt
2162         if (empty($salt)) {
2163                 // Build server string for more entropy
2164                 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2165
2166                 // Build key string
2167                 $keys   = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('secret_key') . getConfig('ENCRYPT_SEPERATOR') . getConfig('file_hash') . getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime')) . getConfig('ENCRYPT_SEPERATOR') . getConfig('master_salt');
2168
2169                 // Additional data
2170                 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2171
2172                 // Calculate number for generating the code
2173                 $a = time() + getConfig('_ADD') - 1;
2174
2175                 // Generate SHA1 sum from modula of number and the prime number
2176                 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2177                 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2178                 $sha1 = scrambleString($sha1);
2179                 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2180                 //* DEBUG: */ $sha1b = descrambleString($sha1);
2181                 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2182
2183                 // Generate the password salt string
2184                 $salt = substr($sha1, 0, getConfig('salt_length'));
2185                 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2186         } else {
2187                 // Use given salt
2188                 //* DEBUG: */ outputHtml('salt=' . $salt . '<br />');
2189                 $salt = substr($salt, 0, getConfig('salt_length'));
2190                 //* DEBUG: */ outputHtml('salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />');
2191
2192                 // Sanity check on salt
2193                 if (strlen($salt) != getConfig('salt_length')) {
2194                         // Not the same!
2195                         debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2196                 } // END - if
2197         }
2198
2199         // Generate final hash (for debug output)
2200         $finalHash = $salt . sha1($salt . $plainText);
2201
2202         // Debug output
2203         //* DEBUG: */ outputHtml('finalHash=' . $finalHash);
2204
2205         // Return hash
2206         return $finalHash;
2207 }
2208
2209 // Scramble a string
2210 function scrambleString($str) {
2211         // Init
2212         $scrambled = '';
2213
2214         // Final check, in case of failture it will return unscrambled string
2215         if (strlen($str) > 40) {
2216                 // The string is to long
2217                 return $str;
2218         } elseif (strlen($str) == 40) {
2219                 // From database
2220                 $scrambleNums = explode(':', getConfig('pass_scramble'));
2221         } else {
2222                 // Generate new numbers
2223                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2224         }
2225
2226         // Compare both lengths and abort if different
2227         if (strlen($str) != count($scrambleNums)) return $str;
2228
2229         // Scramble string here
2230         //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2231         for ($idx = 0; $idx < strlen($str); $idx++) {
2232                 // Get char on scrambled position
2233                 $char = substr($str, $scrambleNums[$idx], 1);
2234
2235                 // Add it to final output string
2236                 $scrambled .= $char;
2237         } // END - for
2238
2239         // Return scrambled string
2240         //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2241         return $scrambled;
2242 }
2243
2244 // De-scramble a string scrambled by scrambleString()
2245 function descrambleString($str) {
2246         // Scramble only 40 chars long strings
2247         if (strlen($str) != 40) return $str;
2248
2249         // Load numbers from config
2250         $scrambleNums = explode(':', getConfig('pass_scramble'));
2251
2252         // Validate numbers
2253         if (count($scrambleNums) != 40) return $str;
2254
2255         // Begin descrambling
2256         $orig = str_repeat(' ', 40);
2257         //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2258         for ($idx = 0; $idx < 40; $idx++) {
2259                 $char = substr($str, $idx, 1);
2260                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2261         } // END - for
2262
2263         // Return scrambled string
2264         //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2265         return $orig;
2266 }
2267
2268 // Generated a "string" for scrambling
2269 function genScrambleString ($len) {
2270         // Prepare array for the numbers
2271         $scrambleNumbers = array();
2272
2273         // First we need to setup randomized numbers from 0 to 31
2274         for ($idx = 0; $idx < $len; $idx++) {
2275                 // Generate number
2276                 $rand = mt_rand(0, ($len -1));
2277
2278                 // Check for it by creating more numbers
2279                 while (array_key_exists($rand, $scrambleNumbers)) {
2280                         $rand = mt_rand(0, ($len -1));
2281                 } // END - while
2282
2283                 // Add number
2284                 $scrambleNumbers[$rand] = $rand;
2285         } // END - for
2286
2287         // So let's create the string for storing it in database
2288         $scrambleString = implode(':', $scrambleNumbers);
2289         return $scrambleString;
2290 }
2291
2292 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2293 function encodeHashForCookie ($passHash) {
2294         // Return vanilla password hash
2295         $ret = $passHash;
2296
2297         // Is a secret key and master salt already initialized?
2298         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, intval(isExtensionInstalled('sql_patches')) . '/' . intval(isConfigEntrySet('_PRIME')) . '/' . intval(isConfigEntrySet('secret_key')) . '/' . intval(isConfigEntrySet('master_salt')));
2299         if ((isExtensionInstalled('sql_patches')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2300                 // Only calculate when the secret key is generated
2301                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '/' . strlen(getConfig('secret_key')));
2302                 if ((strlen($passHash) != 49) || (strlen(getConfig('secret_key')) != 40)) {
2303                         // Both keys must have same length so return unencrypted
2304                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, strlen($passHash) . '!=49/' . strlen(getConfig('secret_key')) . '!=40');
2305                         return $ret;
2306                 } // END - if
2307
2308                 $newHash = ''; $start = 9;
2309                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'passHash=' . $passHash . '(' . strlen($passHash) . ')');
2310                 for ($idx = 0; $idx < 20; $idx++) {
2311                         $part1 = hexdec(substr($passHash, ($idx * 2) + (strlen($passHash) - strlen(getConfig('secret_key'))), 2));
2312                         $part2 = hexdec(substr(getConfig('secret_key'), $start, 2));
2313                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2);
2314                         $mod = dechex($idx);
2315                         if ($part1 > $part2) {
2316                                 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2317                         } elseif ($part2 > $part1) {
2318                                 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2319                         }
2320                         $mod = substr($mod, 0, 2);
2321                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
2322                         $mod = str_repeat(0, (2 - strlen($mod))) . $mod;
2323                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
2324                         $start += 2;
2325                         $newHash .= $mod;
2326                 } // END - for
2327
2328                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $passHash . ',' . $newHash . ' (' . strlen($newHash) . ')');
2329                 $ret = generateHash($newHash, getConfig('master_salt'));
2330         } // END - if
2331
2332         // Return result
2333         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . $ret . '');
2334         return $ret;
2335 }
2336
2337 // Fix "deleted" cookies
2338 function fixDeletedCookies ($cookies) {
2339         // Is this an array with entries?
2340         if ((is_array($cookies)) && (count($cookies) > 0)) {
2341                 // Then check all cookies if they are marked as deleted!
2342                 foreach ($cookies as $cookieName) {
2343                         // Is the cookie set to "deleted"?
2344                         if (getSession($cookieName) == 'deleted') {
2345                                 setSession($cookieName, '');
2346                         } // END - if
2347                 } // END - foreach
2348         } // END - if
2349 }
2350
2351 // Output error messages in a fasioned way and die...
2352 function app_die ($F, $L, $message) {
2353         // Check if Script is already dieing and not let it kill itself another 1000 times
2354         if (!isset($GLOBALS['app_died'])) {
2355                 // Make sure, that the script realy realy diese here and now
2356                 $GLOBALS['app_died'] = true;
2357
2358                 // Set content type as text/html
2359                 setContentType('text/html');
2360
2361                 // Load header
2362                 loadIncludeOnce('inc/header.php');
2363
2364                 // Rewrite message for output
2365                 $message = sprintf(getMessage('MAILER_HAS_DIED'), basename($F), $L, $message);
2366
2367                 // Load the message template
2368                 loadTemplate('app_die_message', false, $message);
2369
2370                 // Load footer
2371                 loadIncludeOnce('inc/footer.php');
2372         } else {
2373                 // Script tried to kill itself twice
2374                 die('['.__FUNCTION__.':'.__LINE__.']: Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2375         }
2376 }
2377
2378 // Display parsing time and number of SQL queries in footer
2379 function displayParsingTime () {
2380         // Is the timer started?
2381         if (!isset($GLOBALS['startTime'])) {
2382                 // Abort here
2383                 return false;
2384         } // END - if
2385
2386         // Get end time
2387         $endTime = microtime(true);
2388
2389         // "Explode" both times
2390         $start = explode(' ', $GLOBALS['startTime']);
2391         $end = explode(' ', $endTime);
2392         $runTime = $end[0] - $start[0];
2393         if ($runTime < 0) $runTime = '0';
2394
2395         // Prepare output
2396         // @TODO This can be easily moved out after the merge from EL branch to this is complete
2397         $content = array(
2398                 'run_time' => translateComma($runTime),
2399                 'sql_time' => translateComma(getConfig('sql_time') * 1000),
2400         );
2401
2402         // Load the template
2403         $GLOBALS['page_footer'] .= loadTemplate('show_timings', true, $content);
2404 }
2405
2406 // Check wether a boolean constant is set
2407 // Taken from user comments in PHP documentation for function constant()
2408 function isBooleanConstantAndTrue ($constName) { // : Boolean
2409         // Failed by default
2410         $res = false;
2411
2412         // In cache?
2413         if (isset($GLOBALS['cache_array']['const'][$constName])) {
2414                 // Use cache
2415                 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-CACHE!<br />");
2416                 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2417         } else {
2418                 // Check constant
2419                 //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-RESOLVE!<br />");
2420                 if (defined($constName)) {
2421                         // Found!
2422                         //* DEBUG: */ outputHtml(__FUNCTION__ . '(<font color="#0000aa">' . __LINE__ . '</font>): ' . $constName."-FOUND!<br />");
2423                         $res = (constant($constName) === true);
2424                 } // END - if
2425
2426                 // Set cache
2427                 $GLOBALS['cache_array']['const'][$constName] = $res;
2428         }
2429         //* DEBUG: */ var_dump($res);
2430
2431         // Return value
2432         return $res;
2433 }
2434
2435 // Checks if a given apache module is loaded
2436 function isApacheModuleLoaded ($apacheModule) {
2437         // Check it and return result
2438         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2439 }
2440
2441 // Get current theme name
2442 function getCurrentTheme () {
2443         // The default theme is 'default'... ;-)
2444         $ret = 'default';
2445
2446         // Do we have ext-theme installed and active?
2447         if (isExtensionActive('theme')) {
2448                 // Call inner method
2449                 $ret = getActualTheme();
2450         } // END - if
2451
2452         // Return theme value
2453         return $ret;
2454 }
2455
2456 // Generates an error code from given account status
2457 function generateErrorCodeFromUserStatus ($status='') {
2458         // If no status is provided, use the default, cached
2459         if ((empty($status)) && (isMember())) {
2460                 // Get user status
2461                 $status = getUserData('status');
2462         } // END - if
2463
2464         // Default error code if unknown account status
2465         $errorCode = getCode('UNKNOWN_STATUS');
2466
2467         // Generate constant name
2468         $codeName = sprintf("ACCOUNT_%s", strtoupper($status));
2469
2470         // Is the constant there?
2471         if (isCodeSet($codeName)) {
2472                 // Then get it!
2473                 $errorCode = getCode($codeName);
2474         } else {
2475                 // Unknown status
2476                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2477         }
2478
2479         // Return error code
2480         return $errorCode;
2481 }
2482
2483 // Back-ported from the new ship-simu engine. :-)
2484 function debug_get_printable_backtrace () {
2485         // Init variable
2486         $backtrace = "<ol>\n";
2487
2488         // Get and prepare backtrace for output
2489         $backtraceArray = debug_backtrace();
2490         foreach ($backtraceArray as $key => $trace) {
2491                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2492                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2493                 if (!isset($trace['args'])) $trace['args'] = array();
2494                 $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>\n";
2495         } // END - foreach
2496
2497         // Close it
2498         $backtrace .= "</ol>\n";
2499
2500         // Return the backtrace
2501         return $backtrace;
2502 }
2503
2504 // A mail-able backtrace
2505 function debug_get_mailable_backtrace () {
2506         // Init variable
2507         $backtrace = '';
2508
2509         // Get and prepare backtrace for output
2510         $backtraceArray = debug_backtrace();
2511         foreach ($backtraceArray as $key => $trace) {
2512                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2513                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2514                 if (!isset($trace['args'])) $trace['args'] = array();
2515                 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2516         } // END - foreach
2517
2518         // Return the backtrace
2519         return $backtrace;
2520 }
2521
2522 // Output a debug backtrace to the user
2523 function debug_report_bug ($F, $L, $message = '', $sendEmail = true) {
2524         // Is this already called?
2525         if (isset($GLOBALS[__FUNCTION__])) {
2526                 // Other backtrace
2527                 print 'Message:'.$message.'<br />Backtrace:<pre>';
2528                 debug_print_backtrace();
2529                 die('</pre>');
2530         } // END - if
2531
2532         // Set this function as called
2533         $GLOBALS[__FUNCTION__] = true;
2534
2535         // Init message
2536         $debug = '';
2537
2538         // Is the optional message set?
2539         if (!empty($message)) {
2540                 // Use and log it
2541                 $debug = sprintf("Note: %s<br />\n",
2542                         $message
2543                 );
2544
2545                 // @TODO Add a little more infos here
2546                 logDebugMessage($F, $L, strip_tags($message));
2547         } // END - if
2548
2549         // Add output
2550         $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">http://bugs.mxchange.org</a> and include the logfile from <strong>" . str_replace(getConfig('PATH'), '', getConfig('CACHE_PATH')) . "debug.log</strong> in your report (you can now attach files):<pre>";
2551         $debug .= debug_get_printable_backtrace();
2552         $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2553         $debug .= "Thank you for finding bugs.";
2554
2555         // Send an email? (e.g. not wanted for evaluation errors)
2556         if (($sendEmail === true) && (!isInstallationPhase())) {
2557                 // Prepare content
2558                 $content = array(
2559                         'message'     => trim($message),
2560                         'backtrace'   => trim(debug_get_mailable_backtrace())
2561                 );
2562
2563                 // Send email to webmaster
2564                 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2565         } // END - if
2566
2567         // And abort here
2568         app_die($F, $L, $debug);
2569 }
2570
2571 // Generates a ***weak*** seed
2572 function generateSeed () {
2573         return microtime(true) * 100000;
2574 }
2575
2576 // Converts a message code to a human-readable message
2577 function getMessageFromErrorCode ($code) {
2578         $message = '';
2579         switch ($code) {
2580                 case '': break;
2581                 case getCode('LOGOUT_DONE')        : $message = getMessage('LOGOUT_DONE'); break;
2582                 case getCode('LOGOUT_FAILED')      : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2583                 case getCode('DATA_INVALID')       : $message = getMessage('MAIL_DATA_INVALID'); break;
2584                 case getCode('POSSIBLE_INVALID')   : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2585                 case getCode('USER_404')           : $message = getMessage('USER_404'); break;
2586                 case getCode('STATS_404')          : $message = getMessage('MAIL_STATS_404'); break;
2587                 case getCode('ALREADY_CONFIRMED')  : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2588                 case getCode('WRONG_PASS')         : $message = getMessage('LOGIN_WRONG_PASS'); break;
2589                 case getCode('WRONG_ID')           : $message = getMessage('LOGIN_WRONG_ID'); break;
2590                 case getCode('ACCOUNT_LOCKED')     : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2591                 case getCode('ACCOUNT_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2592                 case getCode('COOKIES_DISABLED')   : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2593                 case getCode('BEG_SAME_AS_OWN')    : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2594                 case getCode('LOGIN_FAILED')       : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2595                 case getCode('MODULE_MEM_ONLY')    : $message = getMaskedMessage('MODULE_MEM_ONLY', getRequestParameter('mod')); break;
2596                 case getCode('OVERLENGTH')         : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2597                 case getCode('URL_FOUND')          : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2598                 case getCode('SUBJ_URL')           : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2599                 case getCode('BLIST_URL')          : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestParameter('blist'), 0); break;
2600                 case getCode('NO_RECS_LEFT')       : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2601                 case getCode('INVALID_TAGS')       : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2602                 case getCode('MORE_POINTS')        : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2603                 case getCode('MORE_RECEIVERS1')    : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2604                 case getCode('MORE_RECEIVERS2')    : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2605                 case getCode('MORE_RECEIVERS3')    : $message = getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'); break;
2606                 case getCode('INVALID_URL')        : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2607                 case getCode('NO_MAIL_TYPE')       : $message = getMessage('MEMBER_NO_MAIL_TYPE_SELECTED'); break;
2608                 case getCode('UNKNOWN_ERROR')      : $message = getMessage('LOGIN_UNKNOWN_ERROR'); break;
2609                 case getCode('UNKNOWN_STATUS')     : $message = getMessage('LOGIN_UNKNOWN_STATUS'); break;
2610
2611                 case getCode('ERROR_MAILID'):
2612                         if (isExtensionActive('mailid', true)) {
2613                                 $message = getMessage('ERROR_CONFIRMING_MAIL');
2614                         } else {
2615                                 $message = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'mailid');
2616                         }
2617                         break;
2618
2619                 case getCode('EXTENSION_PROBLEM'):
2620                         if (isGetRequestParameterSet('ext')) {
2621                                 $message = generateExtensionInactiveNotInstalledMessage(getRequestParameter('ext'));
2622                         } else {
2623                                 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2624                         }
2625                         break;
2626
2627                 case getCode('URL_TLOCK'):
2628                         // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
2629                         $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2630                                 array(bigintval(getRequestParameter('id'))), __FUNCTION__, __LINE__);
2631
2632                         // Load timestamp from last order
2633                         list($timestamp) = SQL_FETCHROW($result);
2634
2635                         // Free memory
2636                         SQL_FREERESULT($result);
2637
2638                         // Translate it for templates
2639                         $timestamp = generateDateTime($timestamp, 1);
2640
2641                         // Calculate hours...
2642                         $STD = round(getConfig('url_tlock') / 60 / 60);
2643
2644                         // Minutes...
2645                         $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2646
2647                         // And seconds
2648                         $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2649
2650                         // Finally contruct the message
2651                         // @TODO Rewrite this old lost code to a template
2652                         $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2653                         {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2654                         {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2655                         break;
2656
2657                 default:
2658                         // Missing/invalid code
2659                         $message = getMaskedMessage('UNKNOWN_MAILID_CODE', $code);
2660
2661                         // Log it
2662                         logDebugMessage(__FUNCTION__, __LINE__, $message);
2663                         break;
2664         } // END - switch
2665
2666         // Return the message
2667         return $message;
2668 }
2669
2670 // Compile characters which are allowed in URLs
2671 function compileUriCode ($code, $simple = true) {
2672         // Compile constants
2673         if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2674
2675         // Compile QUOT and other non-HTML codes
2676         $code = str_replace('{DOT}', '.',
2677                 str_replace('{SLASH}', '/',
2678                 str_replace('{QUOT}', "'",
2679                 str_replace('{DOLLAR}', '$',
2680                 str_replace('{OPEN_ANCHOR}', '(',
2681                 str_replace('{CLOSE_ANCHOR}', ')',
2682                 str_replace('{OPEN_SQR}', '[',
2683                 str_replace('{CLOSE_SQR}', ']',
2684                 str_replace('{PER}', '%',
2685                 $code
2686         )))))))));
2687
2688         // Return compiled code
2689         return $code;
2690 }
2691
2692 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
2693 function isUrlValidSimple ($url) {
2694         // Prepare URL
2695         $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2696
2697         // Allows http and https
2698         $http      = "(http|https)+(:\/\/)";
2699         // Test domain
2700         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2701         // Test double-domains (e.g. .de.vu)
2702         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2703         // Test IP number
2704         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2705         // ... directory
2706         $dir       = "((/)+([-_\.[:alnum:]])+)*";
2707         // ... page
2708         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2709         // ... and the string after and including question character
2710         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2711         // Pattern for URLs like http://url/dir/doc.html?var=value
2712         $pattern['d1dpg1']  = $http . $domain1 . $dir . $page . $getstring1;
2713         $pattern['d2dpg1']  = $http . $domain2 . $dir . $page . $getstring1;
2714         $pattern['ipdpg1']  = $http . $ip . $dir . $page . $getstring1;
2715         // Pattern for URLs like http://url/dir/?var=value
2716         $pattern['d1dg1']  = $http . $domain1 . $dir.'/' . $getstring1;
2717         $pattern['d2dg1']  = $http . $domain2 . $dir.'/' . $getstring1;
2718         $pattern['ipdg1']  = $http . $ip . $dir.'/' . $getstring1;
2719         // Pattern for URLs like http://url/dir/page.ext
2720         $pattern['d1dp']  = $http . $domain1 . $dir . $page;
2721         $pattern['d1dp']  = $http . $domain2 . $dir . $page;
2722         $pattern['ipdp']  = $http . $ip . $dir . $page;
2723         // Pattern for URLs like http://url/dir
2724         $pattern['d1d']  = $http . $domain1 . $dir;
2725         $pattern['d2d']  = $http . $domain2 . $dir;
2726         $pattern['ipd']  = $http . $ip . $dir;
2727         // Pattern for URLs like http://url/?var=value
2728         $pattern['d1g1']  = $http . $domain1 . '/' . $getstring1;
2729         $pattern['d2g1']  = $http . $domain2 . '/' . $getstring1;
2730         $pattern['ipg1']  = $http . $ip . '/' . $getstring1;
2731         // Pattern for URLs like http://url?var=value
2732         $pattern['d1g12']  = $http . $domain1 . $getstring1;
2733         $pattern['d2g12']  = $http . $domain2 . $getstring1;
2734         $pattern['ipg12']  = $http . $ip . $getstring1;
2735
2736         // Test all patterns
2737         $reg = false;
2738         foreach ($pattern as $key => $pat) {
2739                 // Debug regex?
2740                 if (isDebugRegularExpressionEnabled()) {
2741                         // @TODO Are these convertions still required?
2742                         $pat = str_replace('.', "&#92;&#46;", $pat);
2743                         $pat = str_replace('@', "&#92;&#64;", $pat);
2744                         //* DEBUG: */ outputHtml($key."=&nbsp;" . $pat . '<br />');
2745                 } // END - if
2746
2747                 // Check if expression matches
2748                 $reg = ($reg || preg_match(('^' . $pat . '^'), $url));
2749
2750                 // Does it match?
2751                 if ($reg === true) break;
2752         }
2753
2754         // Return true/false
2755         return $reg;
2756 }
2757
2758 // Wtites data to a config.php-style file
2759 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2760 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2761         // Initialize some variables
2762         $done = false;
2763         $seek++;
2764         $next  = -1;
2765         $found = false;
2766
2767         // Is the file there and read-/write-able?
2768         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2769                 $search = 'CFG: ' . $comment;
2770                 $tmp = $FQFN . '.tmp';
2771
2772                 // Open the source file
2773                 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2774
2775                 // Is the resource valid?
2776                 if (is_resource($fp)) {
2777                         // Open temporary file
2778                         $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2779
2780                         // Is the resource again valid?
2781                         if (is_resource($fp_tmp)) {
2782                                 // Mark temporary file as readable
2783                                 $GLOBALS['file_readable'][$tmp] = true;
2784
2785                                 // Start reading
2786                                 while (!feof($fp)) {
2787                                         // Read from source file
2788                                         $line = fgets ($fp, 1024);
2789
2790                                         if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2791
2792                                         if ($next > -1) {
2793                                                 if ($next === $seek) {
2794                                                         $next = -1;
2795                                                         $line = $prefix . $DATA . $suffix . "\n";
2796                                                 } else {
2797                                                         $next++;
2798                                                 }
2799                                         } // END - if
2800
2801                                         // Write to temp file
2802                                         fwrite($fp_tmp, $line);
2803                                 } // END - while
2804
2805                                 // Close temp file
2806                                 fclose($fp_tmp);
2807
2808                                 // Finished writing tmp file
2809                                 $done = true;
2810                         } // END - if
2811
2812                         // Close source file
2813                         fclose($fp);
2814
2815                         if (($done === true) && ($found === true)) {
2816                                 // Copy back tmp file and delete tmp :-)
2817                                 copyFileVerified($tmp, $FQFN, 0644);
2818                                 return removeFile($tmp);
2819                         } elseif ($found === false) {
2820                                 outputHtml('<strong>CHANGE:</strong> 404!');
2821                         } else {
2822                                 outputHtml('<strong>TMP:</strong> UNDONE!');
2823                         }
2824                 }
2825         } else {
2826                 // File not found, not readable or writeable
2827                 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2828         }
2829
2830         // An error was detected!
2831         return false;
2832 }
2833 // Send notification to admin
2834 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2835         if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2836                 // Send new way
2837                 sendAdminsEmails($subject, $templateName, $content, $userid);
2838         } else {
2839                 // Send out out-dated way
2840                 $message = loadEmailTemplate($templateName, $content, $userid);
2841                 sendAdminEmails($subject, $message);
2842         }
2843 }
2844
2845 // Debug message logger
2846 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2847         // Is debug mode enabled?
2848         if ((isDebugModeEnabled()) || ($force === true)) {
2849                 // Remove CRLF
2850                 $message = str_replace("\r", '', str_replace("\n", '', $message));
2851
2852                 // Log this message away
2853                 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot write logfile debug.log!');
2854                 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2855                 fclose($fp);
2856         } // END - if
2857 }
2858
2859 // Handle extra values
2860 function handleExtraValues ($filterFunction, $value, $extraValue) {
2861         // Default is the value itself
2862         $ret = $value;
2863
2864         // Do we have a special filter function?
2865         if (!empty($filterFunction)) {
2866                 // Does the filter function exist?
2867                 if (function_exists($filterFunction)) {
2868                         // Do we have extra parameters here?
2869                         if (!empty($extraValue)) {
2870                                 // Put both parameters in one new array by default
2871                                 $args = array($value, $extraValue);
2872
2873                                 // If we have an array simply use it and pre-extend it with our value
2874                                 if (is_array($extraValue)) {
2875                                         // Make the new args array
2876                                         $args = merge_array(array($value), $extraValue);
2877                                 } // END - if
2878
2879                                 // Call the multi-parameter call-back
2880                                 $ret = call_user_func_array($filterFunction, $args);
2881                         } else {
2882                                 // One parameter call
2883                                 $ret = call_user_func($filterFunction, $value);
2884                         }
2885                 } // END - if
2886         } // END - if
2887
2888         // Return the value
2889         return $ret;
2890 }
2891
2892 // Converts timestamp selections into a timestamp
2893 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2894         // Init test variable
2895         $skip  = false;
2896         $test2 = '';
2897
2898         // Get last three chars
2899         $test = substr($id, -3);
2900
2901         // Improved way of checking! :-)
2902         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2903                 // Found a multi-selection for timings?
2904                 $test = substr($id, 0, -3);
2905                 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)) {
2906                         // Generate timestamp
2907                         $postData[$test] = createTimestampFromSelections($test, $postData);
2908                         $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2909                         $GLOBALS['skip_config'][$test] = true;
2910
2911                         // Remove data from array
2912                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2913                                 unset($postData[$test . '_' . $rem]);
2914                         } // END - foreach
2915
2916                         // Skip adding
2917                         unset($id);
2918                         $skip = true;
2919                         $test2 = $test;
2920                 } // END - if
2921         } // END - if
2922 }
2923
2924 // Reverts the german decimal comma into Computer decimal dot
2925 function convertCommaToDot ($str) {
2926         // Default float is not a float... ;-)
2927         $float = false;
2928
2929         // Which language is selected?
2930         switch (getLanguage()) {
2931                 case 'de': // German language
2932                         // Remove german thousand dots first
2933                         $str = str_replace('.', '', $str);
2934
2935                         // Replace german commata with decimal dot and cast it
2936                         $float = (float)str_replace(',', '.', $str);
2937                         break;
2938
2939                 default: // US and so on
2940                         // Remove thousand dots first and cast
2941                         $float = (float)str_replace(',', '', $str);
2942                         break;
2943         }
2944
2945         // Return float
2946         return $float;
2947 }
2948
2949 // Handle menu-depending failed logins and return the rendered content
2950 function handleLoginFailures ($accessLevel) {
2951         // Default output is empty ;-)
2952         $OUT = '';
2953
2954         // Is the session data set?
2955         if ((isSessionVariableSet('mailer_' . $accessLevel . '_failures')) && (isSessionVariableSet('mailer_' . $accessLevel . '_last_failure'))) {
2956                 // Ignore zero values
2957                 if (getSession('mailer_' . $accessLevel . '_failures') > 0) {
2958                         // Non-guest has login failures found, get both data and prepare it for template
2959                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "accessLevel={$accessLevel}<br />");
2960                         $content = array(
2961                                 'login_failures' => getSession('mailer_' . $accessLevel . '_failures'),
2962                                 'last_failure'   => generateDateTime(getSession('mailer_' . $accessLevel . '_last_failure'), 2)
2963                         );
2964
2965                         // Load template
2966                         $OUT = loadTemplate('login_failures', true, $content);
2967                 } // END - if
2968
2969                 // Reset session data
2970                 setSession('mailer_' . $accessLevel . '_failures', '');
2971                 setSession('mailer_' . $accessLevel . '_last_failure', '');
2972         } // END - if
2973
2974         // Return rendered content
2975         return $OUT;
2976 }
2977
2978 // Rebuild cache
2979 function rebuildCache ($cache, $inc = '', $force = false) {
2980         // Debug message
2981         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2982
2983         // Shall I remove the cache file?
2984         if (isCacheInstanceValid()) {
2985                 // Rebuild cache
2986                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2987                         // Destroy it
2988                         $GLOBALS['cache_instance']->removeCacheFile($force);
2989                 } // END - if
2990
2991                 // Include file given?
2992                 if (!empty($inc)) {
2993                         // Construct FQFN
2994                         $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
2995
2996                         // Is the include there?
2997                         if (isIncludeReadable($inc)) {
2998                                 // And rebuild it from scratch
2999                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "inc={$inc} - LOADED!<br />");
3000                                 loadInclude($inc);
3001                         } else {
3002                                 // Include not found!
3003                                 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3004                         }
3005                 } // END - if
3006         } // END - if
3007 }
3008
3009 // Determines the real remote address
3010 function determineRealRemoteAddress () {
3011         // Is a proxy in use?
3012         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3013                 // Proxy was used
3014                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3015         } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3016                 // Yet, another proxy
3017                 $address = $_SERVER['HTTP_CLIENT_IP'];
3018         } else {
3019                 // The regular address when no proxy was used
3020                 $address = $_SERVER['REMOTE_ADDR'];
3021         }
3022
3023         // This strips out the real address from proxy output
3024         if (strstr($address, ',')) {
3025                 $addressArray = explode(',', $address);
3026                 $address = $addressArray[0];
3027         } // END - if
3028
3029         // Return the result
3030         return $address;
3031 }
3032
3033 // Adds a bonus mail to the queue
3034 // This is a high-level function!
3035 function addNewBonusMail ($data, $mode = '', $output=true) {
3036         // Use mode from data if not set and availble ;-)
3037         if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3038
3039         // Generate receiver list
3040         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3041
3042         // Receivers added?
3043         if (!empty($receiver)) {
3044                 // Add bonus mail to queue
3045                 addBonusMailToQueue(
3046                 $data['subject'],
3047                 $data['text'],
3048                 $receiver,
3049                 $data['points'],
3050                 $data['seconds'],
3051                 $data['url'],
3052                 $data['cat'],
3053                 $mode,
3054                 $data['receiver']
3055                 );
3056
3057                 // Mail inserted into bonus pool
3058                 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3059         } elseif ($output) {
3060                 // More entered than can be reached!
3061                 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3062         } else {
3063                 // Debug log
3064                 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3065         }
3066 }
3067
3068 // Determines referal id and sets it
3069 function determineReferalId () {
3070         // Skip this in non-html-mode and outside ref.php
3071         if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3072
3073         // Check if refid is set
3074         if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3075                 // This is fine...
3076         } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3077                 // The variable user comes from the click-counter script click.php and we only accept this here
3078                 $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
3079         } elseif (isPostRequestParameterSet('refid')) {
3080                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3081                 $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
3082         } elseif (isGetRequestParameterSet('refid')) {
3083                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3084                 $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
3085         } elseif (isGetRequestParameterSet('ref')) {
3086                 // Set refid=ref (the referal link uses such variable)
3087                 $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
3088         } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3089                 // Set session refid als global
3090                 $GLOBALS['refid'] = bigintval(getSession('refid'));
3091         } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3092                 // Select a random user which has confirmed enougth mails
3093                 $GLOBALS['refid'] = determineRandomReferalId();
3094         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (getConfig('def_refid') > 0)) {
3095                 // Set default refid as refid in URL
3096                 $GLOBALS['refid'] = getConfig('def_refid');
3097         } else {
3098                 // No default id when sql_patches is not installed or none set
3099                 $GLOBALS['refid'] = '0';
3100         }
3101
3102         // Set cookie when default refid > 0
3103         if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3104                 // Default is not found
3105                 $found = false;
3106
3107                 // Do we have nickname or userid set?
3108                 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3109                         // Nickname in URL, so load the id
3110                         $found = fetchUserData($GLOBALS['refid'], 'nickname');
3111                 } elseif ($GLOBALS['refid'] > 0) {
3112                         // Direct userid entered
3113                         $found = fetchUserData($GLOBALS['refid']);
3114                 }
3115
3116                 // Is the record valid?
3117                 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3118                         // No, then reset referal id
3119                         $GLOBALS['refid'] = getConfig('def_refid');
3120                 } // END - if
3121
3122                 // Set cookie
3123                 setSession('refid', $GLOBALS['refid']);
3124         } // END - if
3125
3126         // Return determined refid
3127         return $GLOBALS['refid'];
3128 }
3129
3130 // Enables the reset mode and runs it
3131 function doReset () {
3132         // Enable the reset mode
3133         $GLOBALS['reset_enabled'] = true;
3134
3135         // Run filters
3136         runFilterChain('reset');
3137 }
3138
3139 // Our shutdown-function
3140 function shutdown () {
3141         // Call the filter chain 'shutdown'
3142         runFilterChain('shutdown', null);
3143
3144         // Check if not in installation phase and the link is up
3145         if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) {
3146                 // Close link
3147                 SQL_CLOSE(__FUNCTION__, __LINE__);
3148         } elseif (!isInstallationPhase()) {
3149                 // No database link
3150                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3151         }
3152
3153         // Stop executing here
3154         exit;
3155 }
3156
3157 // Init member id
3158 function initMemberId () {
3159         $GLOBALS['member_id'] = '0';
3160 }
3161
3162 // Setter for member id
3163 function setMemberId ($memberid) {
3164         // We should not set member id to zero
3165         if ($memberid == '0') debug_report_bug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
3166
3167         // Set it secured
3168         $GLOBALS['member_id'] = bigintval($memberid);
3169 }
3170
3171 // Getter for member id or returns zero
3172 function getMemberId () {
3173         // Default member id
3174         $memberid = '0';
3175
3176         // Is the member id set?
3177         if (isMemberIdSet()) {
3178                 // Then use it
3179                 $memberid = $GLOBALS['member_id'];
3180         } // END - if
3181
3182         // Return it
3183         return $memberid;
3184 }
3185
3186 // Checks ether the member id is set
3187 function isMemberIdSet () {
3188         return (isset($GLOBALS['member_id']));
3189 }
3190
3191 // Handle message codes from URL
3192 function handleCodeMessage () {
3193         if (isGetRequestParameterSet('code')) {
3194                 // Default extension is 'unknown'
3195                 $ext = 'unknown';
3196
3197                 // Is extension given?
3198                 if (isGetRequestParameterSet('ext')) $ext = getRequestParameter('ext');
3199
3200                 // Convert the 'code' parameter from URL to a human-readable message
3201                 $message = getMessageFromErrorCode(getRequestParameter('code'));
3202
3203                 // Load message template
3204                 loadTemplate('message', false, $message);
3205         } // END - if
3206 }
3207
3208 // Setter for extra title
3209 function setExtraTitle ($extraTitle) {
3210         $GLOBALS['extra_title'] = $extraTitle;
3211 }
3212
3213 // Getter for extra title
3214 function getExtraTitle () {
3215         // Is the extra title set?
3216         if (!isExtraTitleSet()) {
3217                 // No, then abort here
3218                 debug_report_bug(__FUNCTION__, __LINE__, 'extra_title is not set!');
3219         } // END - if
3220
3221         // Return it
3222         return $GLOBALS['extra_title'];
3223 }
3224
3225 // Checks if the extra title is set
3226 function isExtraTitleSet () {
3227         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3228 }
3229
3230 // Generates a 'extension foo inactive' message
3231 function generateExtensionInactiveMessage ($ext_name) {
3232         // Is the extension empty?
3233         if (empty($ext_name)) {
3234                 // This should not happen
3235                 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3236         } // END - if
3237
3238         // Default message
3239         $message = getMaskedMessage('EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3240
3241         // Is an admin logged in?
3242         if (isAdmin()) {
3243                 // Then output admin message
3244                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE', $ext_name);
3245         } // END - if
3246
3247         // Return prepared message
3248         return $message;
3249 }
3250
3251 // Generates a 'extension foo not installed' message
3252 function generateExtensionNotInstalledMessage ($ext_name) {
3253         // Is the extension empty?
3254         if (empty($ext_name)) {
3255                 // This should not happen
3256                 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3257         } // END - if
3258
3259         // Default message
3260         $message = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3261
3262         // Is an admin logged in?
3263         if (isAdmin()) {
3264                 // Then output admin message
3265                 $message = getMaskedMessage('ADMIN_EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', $ext_name);
3266         } // END - if
3267
3268         // Return prepared message
3269         return $message;
3270 }
3271
3272 // Generates a message depending on if the extension is not installed or not
3273 // just activated
3274 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3275         // Init message
3276         $message = '';
3277
3278         // Is the extension not installed or just deactivated?
3279         switch (isExtensionInstalled($ext_name)) {
3280                 case true; // Deactivated!
3281                         $message = generateExtensionInactiveMessage($ext_name);
3282                         break;
3283
3284                 case false; // Not installed!
3285                         $message = generateExtensionNotInstalledMessage($ext_name);
3286                         break;
3287
3288                 default: // Should not happen!
3289                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3290                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3291                         break;
3292         } // END - switch
3293
3294         // Return the message
3295         return $message;
3296 }
3297
3298 // Reads a directory recursively by default and searches for files not matching
3299 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3300 // a whole directory.
3301 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3302         // Add default entries we should exclude
3303         $excludeArray[] = '.';
3304         $excludeArray[] = '..';
3305         $excludeArray[] = '.svn';
3306         $excludeArray[] = '.htaccess';
3307
3308         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3309         // Init includes
3310         $files = array();
3311
3312         // Open directory
3313         $dirPointer = opendir(getConfig('PATH') . $baseDir) or debug_report_bug(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3314
3315         // Read all entries
3316         while ($baseFile = readdir($dirPointer)) {
3317                 // Exclude '.', '..' and entries in $excludeArray automatically
3318                 if (in_array($baseFile, $excludeArray, true))  {
3319                         // Exclude them
3320                         //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3321                         continue;
3322                 } // END - if
3323
3324                 // Construct include filename and FQFN
3325                 $fileName = $baseDir . $baseFile;
3326                 $FQFN = getConfig('PATH') . $fileName;
3327
3328                 // Remove double slashes
3329                 $FQFN = str_replace('//', '/', $FQFN);
3330
3331                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3332                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3333                         // These Lines are only for debugging!!
3334                         //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3335                         //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3336                         //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3337
3338                         // Exclude this one
3339                         continue;
3340                 } // END - if
3341
3342                 // Skip also files with non-matching prefix genericly
3343                 if (($recursive === true) && (isDirectory($FQFN))) {
3344                         // Is a redirectory so read it as well
3345                         $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3346
3347                         // And skip further processing
3348                         continue;
3349                 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3350                         // Skip this file
3351                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3352                         continue;
3353                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3354                         // Skip wrong suffix as well
3355                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3356                         continue;
3357                 } elseif (!isFileReadable($FQFN)) {
3358                         // Not readable so skip it
3359                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3360                         continue;
3361                 }
3362
3363                 // Is the file a PHP script or other?
3364                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3365                 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3366                         // Is this a valid include file?
3367                         if ($extension == '.php') {
3368                                 // Remove both for extension name
3369                                 $extName = substr($baseFile, strlen($prefix), -4);
3370
3371                                 // Is the extension valid and active?
3372                                 if (isExtensionNameValid($extName)) {
3373                                         // Then add this file
3374                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3375                                         $files[] = $fileName;
3376                                 } else {
3377                                         // Add non-extension files as well
3378                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3379                                         if ($addBaseDir === true) {
3380                                                 $files[] = $fileName;
3381                                         } else {
3382                                                 $files[] = $baseFile;
3383                                         }
3384                                 }
3385                         } else {
3386                                 // We found .php file but should not search for them, why?
3387                                 debug_report_bug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script.');
3388                         }
3389                 } elseif (substr($baseFile, -4, 4) == $extension) {
3390                         // Other, generic file found
3391                         $files[] = $fileName;
3392                 }
3393         } // END - while
3394
3395         // Close directory
3396         closedir($dirPointer);
3397
3398         // Sort array
3399         sort($files);
3400
3401         // Return array with include files
3402         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3403         return $files;
3404 }
3405
3406 // Maps a module name into a database table name
3407 function mapModuleToTable ($moduleName) {
3408         // Map only these, still lame code...
3409         switch ($moduleName) {
3410                 // 'index' is the guest's menu
3411                 case 'index': $moduleName = 'guest';  break;
3412                 // ... and 'login' the member's menu
3413                 case 'login': $moduleName = 'member'; break;
3414                 // Anything else will not be mapped, silently.
3415         } // END - switch
3416
3417         // Return result
3418         return $moduleName;
3419 }
3420
3421 // Add SQL debug data to array for later output
3422 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3423         // Already executed?
3424         if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3425                 // Then abort here, we don't need to profile a query twice
3426                 return;
3427         } // END - if
3428
3429         // Remeber this as profiled (or not, but we don't care here)
3430         $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3431
3432         // Do we have cache?
3433         if (!isset($GLOBALS['debug_sql_available'])) {
3434                 // Check it and cache it in $GLOBALS
3435                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3436         } // END - if
3437         
3438         // Don't execute anything here if we don't need or ext-other is missing
3439         if ($GLOBALS['debug_sql_available'] === false) {
3440                 return;
3441         } // END - if
3442
3443         // Generate record
3444         $record = array(
3445                 'num_rows' => SQL_NUMROWS($result),
3446                 'affected' => SQL_AFFECTEDROWS(),
3447                 'sql_str'  => $sqlString,
3448                 'timing'   => $timing,
3449                 'file'     => basename($F),
3450                 'line'     => $L
3451         );
3452
3453         // Add it
3454         $GLOBALS['debug_sqls'][] = $record;
3455 }
3456
3457 // Initializes the cache instance
3458 function initCacheInstance () {
3459         // Load include for CacheSystem class
3460         loadIncludeOnce('inc/classes/cachesystem.class.php');
3461
3462         // Initialize cache system only when it's needed
3463         $GLOBALS['cache_instance'] = new CacheSystem();
3464         if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3465                 // Failed to initialize cache sustem
3466                 addFatalMessage(__FUNCTION__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3467         } // END - if
3468 }
3469
3470 // Getter for message from array or raw message
3471 function getMessageFromIndexedArray ($message, $pos, $array) {
3472         // Check if the requested message was found in array
3473         if (isset($array[$pos])) {
3474                 // ... if yes then use it!
3475                 $ret = $array[$pos];
3476         } else {
3477                 // ... else use default message
3478                 $ret = $message;
3479         }
3480
3481         // Return result
3482         return $ret;
3483 }
3484
3485 // Print code with line numbers
3486 function linenumberCode ($code)    {
3487         if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3488         $count_lines = count($codeE);
3489
3490         $r = 'Line | Code:<br />';
3491         foreach($codeE as $line => $c) {
3492                 $r .= '<div class="line"><span class="linenum">';
3493                 if ($count_lines == 1) {
3494                         $r .= 1;
3495                 } else {
3496                         $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
3497                 }
3498                 $r .= '</span>|';
3499
3500                 // Add code
3501                 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3502         }
3503
3504         return '<div class="code">' . $r . '</div>';
3505 }
3506
3507 // Convert ';' to ', ' for e.g. receiver list
3508 function convertReceivers ($old) {
3509         return str_replace(';', ', ', $old);
3510 }
3511
3512 // Determines the right page title
3513 function determinePageTitle () {
3514         // Config and database connection valid?
3515         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3516                 // Init title
3517                 $TITLE = '';
3518
3519                 // Title decoration enabled?
3520                 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left')) . ' ';
3521
3522                 // Do we have some extra title?
3523                 if (isExtraTitleSet()) {
3524                         // Then prepent it
3525                         $TITLE .= getExtraTitle() . ' by ';
3526                 } // END - if
3527
3528                 // Add main title
3529                 $TITLE .= getConfig('MAIN_TITLE');
3530
3531                 // Add title of module? (middle decoration will also be added!)
3532                 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3533                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3534                 } // END - if
3535
3536                 // Add title from what file
3537                 $mode = '';
3538                 if (getModule() == 'login') $mode = 'member';
3539                 elseif (getModule() == 'index') $mode = 'guest';
3540                 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3541
3542                 // Add title decorations? (right)
3543                 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3544
3545                 // Remember title in constant for the template
3546                 $pageTitle = $TITLE;
3547         } elseif ((isInstalled()) && (isAdminRegistered())) {
3548                 // Installed, admin registered but no ext-sql_patches
3549                 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3550         } elseif ((isInstalled()) && (!isAdminRegistered())) {
3551                 // Installed but no admin registered
3552                 $pageTitle = getMessage('SETUP_OF_MXCHANGE');
3553         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3554                 // Installation mode
3555                 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3556         } else {
3557                 // Configuration not found!
3558                 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3559
3560                 // Do not add the fatal message in installation mode
3561                 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FUNCTION__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3562         }
3563
3564         // Return title
3565         return decodeEntities($pageTitle);
3566 }
3567
3568 // Checks wethere there is a cache file there. This function is cached.
3569 function isTemplateCached ($template) {
3570         // Do we have cached this result?
3571         if (!isset($GLOBALS['template_cache'][$template])) {
3572                 // Generate FQFN
3573                 $FQFN = generateCacheFqfn($template);
3574
3575                 // Is it there?
3576                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3577         } // END - if
3578
3579         // Return it
3580         return $GLOBALS['template_cache'][$template];
3581 }
3582
3583 // Flushes non-flushed template cache to disk
3584 function flushTemplateCache ($template, $eval) {
3585         // Is this cache flushed?
3586         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3587                 // Generate FQFN
3588                 $FQFN = generateCacheFqfn($template);
3589
3590                 // Replace username with a call
3591                 $eval = str_replace('$username', '".getUsername()."', $eval);
3592
3593                 // And flush it
3594                 writeToFile($FQFN, $eval, true);
3595         } // END - if
3596 }
3597
3598 // Reads a template cache
3599 function readTemplateCache ($template) {
3600         // Check it again
3601         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3602                 // Generate FQFN
3603                 $FQFN = generateCacheFqfn($template);
3604
3605                 // And read from it
3606                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3607         } // END - if
3608
3609         // And return it
3610         return $GLOBALS['template_eval'][$template];
3611 }
3612
3613 // Escapes quotes (default is only double-quotes)
3614 function escapeQuotes ($str, $single = false) {
3615         // Should we escape all?
3616         if ($single === true) {
3617                 // Escape all (including null)
3618                 $str = addslashes($str);
3619         } else {
3620                 // Escape only double-quotes but prevent double-quoting
3621                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3622         }
3623
3624         // Return the escaped string
3625         return $str;
3626 }
3627
3628 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3629 function escapeJavaScriptQuotes ($str) {
3630         // Replace all double-quotes and secure back-ticks
3631         $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3632
3633         // Return it
3634         return $str;
3635 }
3636
3637 // Send out mails depending on the 'mod/modes' combination
3638 // @TODO Lame description for this function
3639 function sendModeMails ($mod, $modes) {
3640         // Load hash
3641         if (fetchUserData(getMemberId())) {
3642                 // Extract salt from cookie
3643                 $salt = substr(getSession('u_hash'), 0, -40);
3644
3645                 // Now let's compare passwords
3646                 $hash = encodeHashForCookie(getUserData('password'));
3647
3648                 // Does the hash match or should we change it?
3649                 if (($hash == getSession('u_hash')) || (postRequestParameter('pass1') == postRequestParameter('pass2'))) {
3650                         // Load the data
3651                         $content = getUserDataArray();
3652
3653                         // Translate gender
3654                         $content['gender'] = translateGender($content['gender']);
3655
3656                         // Clear/init the content variable
3657                         $content['message'] = '';
3658
3659                         // Which mail?
3660                         // @TODO Move this in a filter
3661                         switch ($mod) {
3662                                 case 'mydata':
3663                                         foreach ($modes as $mode) {
3664                                                 switch ($mode) {
3665                                                         case 'normal': break; // Do not add any special lines
3666                                                         case 'email': // Email was changed!
3667                                                                 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestParameter('old_email')."\n";
3668                                                                 break;
3669
3670                                                         case 'pass': // Password was changed
3671                                                                 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3672                                                                 break;
3673
3674                                                         default:
3675                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3676                                                                 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3677                                                                 break;
3678                                                 } // END - switch
3679                                         } // END - foreach
3680
3681                                         if (isExtensionActive('country')) {
3682                                                 // Replace code with description
3683                                                 $content['country'] = generateCountryInfo(postRequestParameter('country_code'));
3684                                         } // END - if
3685
3686                                         // Merge content with data from POST
3687                                         $content = merge_array($content, postRequestArray());
3688
3689                                         // Load template
3690                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3691
3692                                         if (getConfig('admin_notify') == 'Y') {
3693                                                 // The admin needs to be notified about a profile change
3694                                                 $message_admin = 'admin_mydata_notify';
3695                                                 $sub_adm   = getMessage('ADMIN_CHANGED_DATA');
3696                                         } else {
3697                                                 // No mail to admin
3698                                                 $message_admin = '';
3699                                                 $sub_adm   = '';
3700                                         }
3701
3702                                         // Set subject lines
3703                                         $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3704
3705                                         // Output success message
3706                                         $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3707                                         break;
3708
3709                                 default: // Unsupported module!
3710                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3711                                         $content = '<span class="member_failed">{--UNKNOWN_MODULE--}</span>';
3712                                         break;
3713                         } // END - switch
3714                 } else {
3715                         // Passwords mismatch
3716                         $content = '<span class="member_failed">{--MEMBER_PASSWORD_ERROR--}</span>';
3717                 }
3718         } else {
3719                 // Could not load profile
3720                 $content = '<span class="member_failed">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>';
3721         }
3722
3723         // Send email to user if required
3724         if ((!empty($sub_mem)) && (!empty($message))) {
3725                 // Send member mail
3726                 sendEmail($content['email'], $sub_mem, $message);
3727         } // END - if
3728
3729         // Send only if no other error has occured
3730         if (empty($content)) {
3731                 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3732                         // Send admin mail
3733                         sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3734                 } elseif (getConfig('admin_notify') == 'Y') {
3735                         // Cannot send mails to admin!
3736                         $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3737                 } else {
3738                         // No mail to admin
3739                         $content = '<span class="member_done">{--MYDATA_MAIL_SENT--}</span>';
3740                 }
3741         } // END - if
3742
3743         // Load template
3744         loadTemplate('admin_settings_saved', false, $content);
3745 }
3746
3747 // Generates a 'selection box' from given array
3748 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent = '', $extraName = '') {
3749         // Start the output
3750         $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3751 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3752
3753         // Walk through all options
3754         foreach ($options as $option) {
3755                 // Add the <option> entry
3756                 if (empty($optionContent)) {
3757                         // ... from template
3758                         $OUT .= loadTemplate('select_' . $name . $extraName . '_option', true, $option);
3759                 } else {
3760                         // Direct HTML code
3761                         $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3762                 }
3763         } // END - foreach
3764
3765         // Finish selection box
3766         $OUT .= '</select>';
3767
3768         // Prepare output
3769         $content = array(
3770                 'selection_box' => $OUT,
3771                 'module'        => getModule(),
3772                 'what'          => getWhat()
3773         );
3774
3775         // Load template and return it
3776         return loadTemplate('select_' . $name . $extraName . '_box', true, $content);
3777 }
3778
3779 // Get a module from filename and access level
3780 function getModuleFromFileName ($file, $accessLevel) {
3781         // Default is 'invalid';
3782         $modCheck = 'invalid';
3783
3784         // @TODO This is still very static, rewrite it somehow
3785         switch ($accessLevel) {
3786                 case 'admin':
3787                         $modCheck = 'admin';
3788                         break;
3789
3790                 case 'sponsor':
3791                 case 'guest':
3792                 case 'member':
3793                         $modCheck = getModule();
3794                         break;
3795
3796                 default: // Unsupported file name / access level
3797                         debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3798                         break;
3799         }
3800
3801         // Return result
3802         return $modCheck;
3803 }
3804
3805 // Encodes an URL for adding session id, etc.
3806 function encodeUrl ($url, $outputMode = '0') {
3807         // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
3808         if ((strpos($url, session_name()) !== false) || (getOutputMode() == -3)) return $url;
3809
3810         // Do we have a valid session?
3811         if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3812                 // Invalid session
3813                 // Determine right seperator
3814                 $seperator = '&amp;';
3815                 if (strpos($url, '?') === false) {
3816                         // No question mark
3817                         $seperator = '?';
3818                 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3819                         // Non-HTML mode
3820                         $seperator = '&';
3821                 }
3822
3823                 // Add it to URL
3824                 if (session_id() != '') {
3825                         $url .= $seperator . session_name() . '=' . session_id();
3826                 } // END - if
3827         } // END - if
3828
3829         // Add {?URL?} ?
3830         if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3831                 // Add it
3832                 $url = '{?URL?}/' . $url;
3833         } // END - if
3834
3835         // Return the URL
3836         return $url;
3837 }
3838
3839 // Simple check for spider
3840 function isSpider () {
3841         // Get the UA
3842         $userAgent = strtolower(detectUserAgent(true));
3843
3844         // It should not be empty, if so it is better a spider/bot
3845         if (empty($userAgent)) return true;
3846
3847         // Is it a spider?
3848         return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false) || (strpos($userAgent, 'archiver') !== false));
3849 }
3850
3851 // Prepares the header for HTML output
3852 function loadHtmlHeader () {
3853         // Run two filters:
3854         // 1.) pre_page_header (mainly loads the page_header template and includes
3855         //     meta description)
3856         runFilterChain('pre_page_header');
3857
3858         // Here can be something be added, but normally one of the two filters
3859         // around this line should do the job for you.
3860
3861         // 2.) post_page_header (mainly to load stylesheet, extra JavaScripts and
3862         //     to close the head-tag)
3863         // Include more header data here
3864         runFilterChain('post_page_header');
3865 }
3866
3867 // Adds page header and footer to output array element
3868 function addPageHeaderFooter () {
3869         // Init output
3870         $OUT = '';
3871
3872         // Add them all together. This is maybe to simple
3873         foreach (array('page_header', 'output', 'page_footer') as $pagePart) {
3874                 // Add page part if set
3875                 if (isset($GLOBALS[$pagePart])) $OUT .= $GLOBALS[$pagePart];
3876         } // END - foreach
3877
3878         // Transfer $OUT to 'output'
3879         $GLOBALS['output'] = $OUT;
3880 }
3881
3882 // Generates meta description for current module and 'what' value
3883 function generateMetaDescriptionCode () {
3884         // Only include from guest area and if sql_patches has correct version
3885         if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3886                 // Construct dynamic description
3887                 $DESCR = '{?MAIN_TITLE?} ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu('guest', getWhat());
3888
3889                 // Output it directly
3890                 $GLOBALS['page_header'] .= '<meta name="description" content="' . $DESCR . '" />';
3891         } // END - if
3892
3893         // Remove depth
3894         unset($GLOBALS['ref_level']);
3895 }
3896
3897 // Generates an FQFN for template cache from the given template name
3898 function generateCacheFqfn ($template) {
3899         // Is this cached?
3900         if (!isset($GLOBALS['template_cache_fqfn'][$template])) {
3901                 // Generate the FQFN
3902                 $GLOBALS['template_cache_fqfn'][$template] = sprintf("%s_compiled/html/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3903         } // END - if
3904
3905         // Return it
3906         return $GLOBALS['template_cache_fqfn'][$template];
3907 }
3908
3909 // Function to search for the last modified file
3910 function searchDirsRecursive ($dir, &$last_changed, $lookFor = 'Date') {
3911         // Get dir as array
3912         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir);
3913         // Does it match what we are looking for? (We skip a lot files already!)
3914         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
3915         $excludePattern = '@(\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
3916
3917         $ds = getArrayFromDirectory($dir, '', false, true, array(), '.php', $excludePattern);
3918         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count(ds)='.count($ds));
3919
3920         // Walk through all entries
3921         foreach ($ds as $d) {
3922                 // Generate proper FQFN
3923                 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir . '/' . $d);
3924
3925                 // Is it a file and readable?
3926                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'dir=' . $dir . ',d=' . $d);
3927                 if (isFileReadable($FQFN)) {
3928                         // $FQFN is a readable file so extract the requested data from it
3929                         $check = extractRevisionInfoFromFile($FQFN, $lookFor);
3930                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' found. check=' . $check);
3931
3932                         // Is the file more recent?
3933                         if ((!isset($last_changed[$lookFor])) || ($last_changed[$lookFor] < $check)) {
3934                                 // This file is newer as the file before
3935                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'NEWER!');
3936                                 $last_changed['path_name'] = $FQFN;
3937                                 $last_changed[$lookFor] = $check;
3938                         } // END - if
3939                 } else {
3940                         // Not readable
3941                         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'File: ' . $d . ' not readable or directory.');
3942                 }
3943         } // END - foreach
3944 }
3945
3946 // "Fixes" null or empty string to count of dashes
3947 function fixNullEmptyToDashes ($str, $num) {
3948         // Use str as default
3949         $return = $str;
3950
3951         // Is it empty?
3952         if ((is_null($str)) || (trim($str) == '')) {
3953                 // Set it
3954                 $return = str_repeat('-', $num);
3955         } // END - if
3956
3957         // Return final string
3958         return $return;
3959 }
3960
3961 // Handles the braces [] of a field (e.g. value of 'name' attribute)
3962 function handleFieldWithBraces ($field) {
3963         // Are there braces [] at the end?
3964         if (substr($field, -2, 2) == '[]') {
3965                 // Try to find one and replace it. I do it this way to allow easy
3966                 // extending of this code.
3967                 foreach (array('admin_list_builder_id_value') as $key) {
3968                         // Is the cache entry set?
3969                         if (isset($GLOBALS[$key])) {
3970                                 // Insert it
3971                                 $field = str_replace('[]', '[' . $GLOBALS[$key] . ']', $field);
3972
3973                                 // And abort
3974                                 break;
3975                         } // END - if
3976                 } // END - foreach
3977         } // END - if
3978
3979         // Return it
3980         return $field;
3981 }
3982
3983 //////////////////////////////////////////////////
3984 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3985 //////////////////////////////////////////////////
3986 //
3987 if (!function_exists('html_entity_decode')) {
3988         // Taken from documentation on www.php.net
3989         function html_entity_decode ($string) {
3990                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3991                 $trans_tbl = array_flip($trans_tbl);
3992                 return strtr($string, $trans_tbl);
3993         }
3994 } // END - if
3995
3996 if (!function_exists('http_build_query')) {
3997         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
3998         function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3999                 $ret = array();
4000                 foreach ((array)$data as $k => $v) {
4001                         if (is_int($k) && $prefix != null) {
4002                                 $k = urlencode($prefix . $k);
4003                         } // END - if
4004
4005                         if ((!empty($key)) || ($key === 0))  $k = $key . '[' . urlencode($k) . ']';
4006
4007                         if (is_array($v) || is_object($v)) {
4008                                 array_push($ret, http_build_query($v, '', $sep, $k));
4009                         } else {
4010                                 array_push($ret, $k.'='.urlencode($v));
4011                         }
4012                 } // END - foreach
4013
4014                 if (empty($sep)) $sep = ini_get('arg_separator.output');
4015
4016                 return implode($sep, $ret);
4017         }
4018 } // END - if
4019
4020 // [EOF]
4021 ?>