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