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