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