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