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