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