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