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