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