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