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