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