debug_report_bug() does call app_die() again (internal TODO), nicer template for...
[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 : ' . str_replace('<', '&lt', str_replace('>', '&gt;', secureString(trim($mailHeader)))) . '
590 To      : ' . $toEmail . '
591 Subject : ' . $subject . '
592 Message : ' . $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 = sprintf(getMessage('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 = sprintf(getMessage('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\" />\n";
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\" />\n";
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\" />\n";
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\" />\n";
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\" />\n";
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\" />\n";
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\" />\n";
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         $scriptData = 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                 $scriptData = '?' . $scriptData;
1733         } else {
1734                 // Ok, add &
1735                 $scriptData = '&' . $scriptData;
1736         }
1737
1738         // Add script data
1739         $script .= $scriptData;
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 .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
1751         $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1752         $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1753
1754         // Send the raw request
1755         $response = sendRawRequest($host, $request);
1756
1757         // Return the result to the caller function
1758         return $response;
1759 }
1760
1761 // Send a POST request
1762 function sendPostRequest ($script, $postData) {
1763         // Is postData an array?
1764         if (!is_array($postData)) {
1765                 // Abort here
1766                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1767                 return array('', '', '');
1768         } // END - if
1769
1770         // Extract host name from script
1771         $host = extractHostnameFromUrl($script);
1772
1773         // Construct request
1774         $data = http_build_query($postData, '', '&');
1775
1776         // Generate POST request header
1777         $request  = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
1778         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
1779         $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
1780         $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
1781         $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
1782         $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
1783         $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
1784         $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1785         $request .= $data;
1786
1787         // Send the raw request
1788         $response = sendRawRequest($host, $request);
1789
1790         // Return the result to the caller function
1791         return $response;
1792 }
1793
1794 // Sends a raw request to another host
1795 function sendRawRequest ($host, $request) {
1796         // Init errno and errdesc with 'all fine' values
1797         $errno = '0'; $errdesc = '';
1798
1799         // Initialize array
1800         $response = array('', '', '');
1801
1802         // Default is not to use proxy
1803         $useProxy = false;
1804
1805         // Are proxy settins set?
1806         if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
1807                 // Then use it
1808                 $useProxy = true;
1809         } // END - if
1810
1811         // Open connection
1812         //* DEBUG: */ die("SCRIPT=" . $script.'<br />');
1813         if ($useProxy === true) {
1814                 // Connect to host through proxy connection
1815                 $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1816         } else {
1817                 // Connect to host directly
1818                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1819         }
1820
1821         // Is there a link?
1822         if (!is_resource($fp)) {
1823                 // Failed!
1824                 return $response;
1825         } // END - if
1826
1827         // Do we use proxy?
1828         if ($useProxy === true) {
1829                 // Generate CONNECT request header
1830                 $proxyTunnel  = 'CONNECT ' . $host . ':80 HTTP/1.1' . getConfig('HTTP_EOL');
1831                 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
1832
1833                 // Use login data to proxy? (username at least!)
1834                 if (getConfig('proxy_username') != '') {
1835                         // Add it as well
1836                         $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
1837                         $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
1838                 } // END - if
1839
1840                 // Add last new-line
1841                 $proxyTunnel .= getConfig('HTTP_EOL');
1842                 //* DEBUG: */ print('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
1843
1844                 // Write request
1845                 fputs($fp, $proxyTunnel);
1846
1847                 // Got response?
1848                 if (feof($fp)) {
1849                         // No response received
1850                         return $response;
1851                 } // END - if
1852
1853                 // Read the first line
1854                 $resp = trim(fgets($fp, 10240));
1855                 $respArray = explode(' ', $resp);
1856                 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1857                         // Invalid response!
1858                         return $response;
1859                 } // END - if
1860         } // END - if
1861
1862         // Write request
1863         fputs($fp, $request);
1864
1865         // Read response
1866         while (!feof($fp)) {
1867                 $response[] = trim(fgets($fp, 1024));
1868         } // END - while
1869
1870         // Close socket
1871         fclose($fp);
1872
1873         // Skip first empty lines
1874         $resp = $response;
1875         foreach ($resp as $idx => $line) {
1876                 // Trim space away
1877                 $line = trim($line);
1878
1879                 // Is this line empty?
1880                 if (empty($line)) {
1881                         // Then remove it
1882                         array_shift($response);
1883                 } else {
1884                         // Abort on first non-empty line
1885                         break;
1886                 }
1887         } // END - foreach
1888
1889         //* DEBUG: */ print('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
1890
1891         // Proxy agent found?
1892         if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1893                 // Proxy header detected, so remove two lines
1894                 array_shift($response);
1895                 array_shift($response);
1896         } // END - if
1897
1898         // Was the request successfull?
1899         if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1900                 // Not found / access forbidden
1901                 $response = array('', '', '');
1902         } // END - if
1903
1904         // Return response
1905         return $response;
1906 }
1907
1908 // Taken from www.php.net eregi() user comments
1909 function isEmailValid ($email) {
1910         // Check first part of email address
1911         $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1912
1913         //  Check domain
1914         $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1915
1916         // Generate pattern
1917         $regex = '@^' . $first . '\@' . $domain . '$@iU';
1918
1919         // Return check result
1920         return preg_match($regex, $email);
1921 }
1922
1923 // Function taken from user comments on www.php.net / function eregi()
1924 function isUrlValid ($URL, $compile=true) {
1925         // Trim URL a little
1926         $URL = trim(urldecode($URL));
1927         //* DEBUG: */ outputHtml($URL.'<br />');
1928
1929         // Compile some chars out...
1930         if ($compile === true) $URL = compileUriCode($URL, false, false, false);
1931         //* DEBUG: */ outputHtml($URL.'<br />');
1932
1933         // Check for the extension filter
1934         if (isExtensionActive('filter')) {
1935                 // Use the extension's filter set
1936                 return FILTER_VALIDATE_URL($URL, false);
1937         } // END - if
1938
1939         // If not installed, perform a simple test. Just make it sure there is always a http:// or
1940         // https:// in front of the URLs
1941         return isUrlValidSimple($URL);
1942 }
1943
1944 // Generate a list of administrative links to a given userid
1945 function generateMemberAdminActionLinks ($userid, $status = '') {
1946         // Make sure userid is a number
1947         if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
1948
1949         // Define all main targets
1950         $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1951
1952         // Begin of navigation links
1953         $OUT = '[&nbsp;';
1954
1955         foreach ($targetArray as $tar) {
1956                 $OUT .= '<span class="admin_user_link"><a href="{%url=modules.php?module=admin&amp;what=' . $tar . '&amp;userid=' . $userid . '%}" title="{--ADMIN_LINK_';
1957                 //* DEBUG: */ outputHtml('*' . $tar.'/' . $status.'*<br />');
1958                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1959                         // Locked accounts shall be unlocked
1960                         $OUT .= 'UNLOCK_USER';
1961                 } else {
1962                         // All other status is fine
1963                         $OUT .= strtoupper($tar);
1964                 }
1965                 $OUT .= '_TITLE--}">{--ADMIN_';
1966                 if (($tar == 'lock_user') && ($status == 'LOCKED')) {
1967                         // Locked accounts shall be unlocked
1968                         $OUT .= 'UNLOCK_USER';
1969                 } else {
1970                         // All other status is fine
1971                         $OUT .= strtoupper($tar);
1972                 }
1973                 $OUT .= '--}</a></span>&nbsp;|&nbsp;';
1974         }
1975
1976         // Finish navigation link
1977         $OUT = substr($OUT, 0, -7) . ']';
1978
1979         // Return string
1980         return $OUT;
1981 }
1982
1983 // Generate an email link
1984 function generateEmailLink ($email, $table = 'admins') {
1985         // Default email link (INSECURE! Spammer can read this by harvester programs)
1986         $EMAIL = 'mailto:' . $email;
1987
1988         // Check for several extensions
1989         if ((isExtensionActive('admins')) && ($table == 'admins')) {
1990                 // Create email link for contacting admin in guest area
1991                 $EMAIL = generateAdminEmailLink($email);
1992         } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
1993                 // Create email link for contacting a member within admin area (or later in other areas, too?)
1994                 $EMAIL = generateUserEmailLink($email, 'admin');
1995         } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
1996                 // Create email link to contact sponsor within admin area (or like the link above?)
1997                 $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
1998         }
1999
2000         // Shall I close the link when there is no admin?
2001         if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2002
2003         // Return email link
2004         return $EMAIL;
2005 }
2006
2007 // Generate a hash for extra-security for all passwords
2008 function generateHash ($plainText, $salt = '') {
2009         // Is the required extension 'sql_patches' there and a salt is not given?
2010         if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
2011                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2012                 return md5($plainText);
2013         } // END - if
2014
2015         // Do we miss an arry element here?
2016         if (!isConfigEntrySet('file_hash')) {
2017                 // Stop here
2018                 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2019         } // END - if
2020
2021         // When the salt is empty build a new one, else use the first x configured characters as the salt
2022         if (empty($salt)) {
2023                 // Build server string (inc/databases.php is no longer updated with every commit)
2024                 $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
2025
2026                 // Build key string
2027                 $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');
2028
2029                 // Additional data
2030                 $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
2031
2032                 // Calculate number for generating the code
2033                 $a = time() + getConfig('_ADD') - 1;
2034
2035                 // Generate SHA1 sum from modula of number and the prime number
2036                 $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
2037                 //* DEBUG: */ outputHtml('SHA1=' . $sha1.' ('.strlen($sha1).')<br />');
2038                 $sha1 = scrambleString($sha1);
2039                 //* DEBUG: */ outputHtml('Scrambled=' . $sha1.' ('.strlen($sha1).')<br />');
2040                 //* DEBUG: */ $sha1b = descrambleString($sha1);
2041                 //* DEBUG: */ outputHtml('Descrambled=' . $sha1b.' ('.strlen($sha1b).')<br />');
2042
2043                 // Generate the password salt string
2044                 $salt = substr($sha1, 0, getConfig('salt_length'));
2045                 //* DEBUG: */ outputHtml($salt.' ('.strlen($salt).')<br />');
2046         } else {
2047                 // Use given salt
2048                 //* DEBUG: */ print 'salt=' . $salt . '<br />';
2049                 $salt = substr($salt, 0, getConfig('salt_length'));
2050                 //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')<br />';
2051
2052                 // Sanity check on salt
2053                 if (strlen($salt) != getConfig('salt_length')) {
2054                         // Not the same!
2055                         debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
2056                 } // END - if
2057         }
2058
2059         // Return hash
2060         return $salt.sha1($salt . $plainText);
2061 }
2062
2063 // Scramble a string
2064 function scrambleString($str) {
2065         // Init
2066         $scrambled = '';
2067
2068         // Final check, in case of failture it will return unscrambled string
2069         if (strlen($str) > 40) {
2070                 // The string is to long
2071                 return $str;
2072         } elseif (strlen($str) == 40) {
2073                 // From database
2074                 $scrambleNums = explode(':', getConfig('pass_scramble'));
2075         } else {
2076                 // Generate new numbers
2077                 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2078         }
2079
2080         // Scramble string here
2081         //* DEBUG: */ outputHtml('***Original=' . $str.'***<br />');
2082         for ($idx = '0'; $idx < strlen($str); $idx++) {
2083                 // Get char on scrambled position
2084                 $char = substr($str, $scrambleNums[$idx], 1);
2085
2086                 // Add it to final output string
2087                 $scrambled .= $char;
2088         } // END - for
2089
2090         // Return scrambled string
2091         //* DEBUG: */ outputHtml('***Scrambled=' . $scrambled.'***<br />');
2092         return $scrambled;
2093 }
2094
2095 // De-scramble a string scrambled by scrambleString()
2096 function descrambleString($str) {
2097         // Scramble only 40 chars long strings
2098         if (strlen($str) != 40) return $str;
2099
2100         // Load numbers from config
2101         $scrambleNums = explode(':', getConfig('pass_scramble'));
2102
2103         // Validate numbers
2104         if (count($scrambleNums) != 40) return $str;
2105
2106         // Begin descrambling
2107         $orig = str_repeat(' ', 40);
2108         //* DEBUG: */ outputHtml('+++Scrambled=' . $str.'+++<br />');
2109         for ($idx = '0'; $idx < 40; $idx++) {
2110                 $char = substr($str, $idx, 1);
2111                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2112         } // END - for
2113
2114         // Return scrambled string
2115         //* DEBUG: */ outputHtml('+++Original=' . $orig.'+++<br />');
2116         return $orig;
2117 }
2118
2119 // Generated a "string" for scrambling
2120 function genScrambleString ($len) {
2121         // Prepare array for the numbers
2122         $scrambleNumbers = array();
2123
2124         // First we need to setup randomized numbers from 0 to 31
2125         for ($idx = '0'; $idx < $len; $idx++) {
2126                 // Generate number
2127                 $rand = mt_rand(0, ($len -1));
2128
2129                 // Check for it by creating more numbers
2130                 while (array_key_exists($rand, $scrambleNumbers)) {
2131                         $rand = mt_rand(0, ($len -1));
2132                 } // END - while
2133
2134                 // Add number
2135                 $scrambleNumbers[$rand] = $rand;
2136         } // END - for
2137
2138         // So let's create the string for storing it in database
2139         $scrambleString = implode(':', $scrambleNumbers);
2140         return $scrambleString;
2141 }
2142
2143 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2144 function generatePassString ($passHash) {
2145         // Return vanilla password hash
2146         $ret = $passHash;
2147
2148         // Is a secret key and master salt already initialized?
2149         if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
2150                 // Only calculate when the secret key is generated
2151                 $newHash = ''; $start = 9;
2152                 for ($idx = '0'; $idx < 10; $idx++) {
2153                         $part1 = hexdec(substr($passHash, $start, 4));
2154                         $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2155                         $mod = dechex($idx);
2156                         if ($part1 > $part2) {
2157                                 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2158                         } elseif ($part2 > $part1) {
2159                                 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2160                         }
2161                         $mod = substr($mod, 0, 4);
2162                         //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')<br />');
2163                         $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
2164                         //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*<br />');
2165                         $start += 4;
2166                         $newHash .= $mod;
2167                 } // END - for
2168
2169                 //* DEBUG: */ print($passHash.'<br />' . $newHash." (".strlen($newHash).')<br />');
2170                 $ret = generateHash($newHash, getConfig('master_salt'));
2171                 //* DEBUG: */ print('ret='.$ret.'<br />');
2172         } else {
2173                 // Hash it simple
2174                 //* DEBUG: */ outputHtml("--" . $passHash."--<br />");
2175                 $ret = md5($passHash);
2176                 //* DEBUG: */ outputHtml("++" . $ret."++<br />");
2177         }
2178
2179         // Return result
2180         return $ret;
2181 }
2182
2183 // Fix "deleted" cookies
2184 function fixDeletedCookies ($cookies) {
2185         // Is this an array with entries?
2186         if ((is_array($cookies)) && (count($cookies) > 0)) {
2187                 // Then check all cookies if they are marked as deleted!
2188                 foreach ($cookies as $cookieName) {
2189                         // Is the cookie set to "deleted"?
2190                         if (getSession($cookieName) == 'deleted') {
2191                                 setSession($cookieName, '');
2192                         } // END - if
2193                 } // END - foreach
2194         } // END - if
2195 }
2196
2197 // Output error messages in a fasioned way and die...
2198 function app_die ($F, $L, $message) {
2199         // Check if Script is already dieing and not let it kill itself another 1000 times
2200         if (!isset($GLOBALS['app_died'])) {
2201                 // Make sure, that the script realy realy diese here and now
2202                 $GLOBALS['app_died'] = true;
2203
2204                 // Load header
2205                 loadIncludeOnce('inc/header.php');
2206
2207                 // Rewrite message for output
2208                 $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
2209
2210                 // Better log this message away
2211                 if ($F != 'debug_report_bug') logDebugMessage($F, $L, $message);
2212
2213                 // Load the message template
2214                 loadTemplate('app_die_message', false, $message);
2215
2216                 // Load footer
2217                 loadIncludeOnce('inc/footer.php');
2218         } else {
2219                 // Script tried to kill itself twice
2220                 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
2221         }
2222 }
2223
2224 // Display parsing time and number of SQL queries in footer
2225 function displayParsingTime() {
2226         // Is the timer started?
2227         if (!isset($GLOBALS['startTime'])) {
2228                 // Abort here
2229                 return false;
2230         } // END - if
2231
2232         // Get end time
2233         $endTime = microtime(true);
2234
2235         // "Explode" both times
2236         $start = explode(' ', $GLOBALS['startTime']);
2237         $end = explode(' ', $endTime);
2238         $runTime = $end[0] - $start[0];
2239         if ($runTime < 0) $runTime = '0';
2240
2241         // Prepare output
2242         $content = array(
2243                 'runtime'  => translateComma($runTime),
2244                 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
2245         );
2246
2247         // Load the template
2248         loadTemplate('show_timings', false, $content);
2249 }
2250
2251 // Check wether a boolean constant is set
2252 // Taken from user comments in PHP documentation for function constant()
2253 function isBooleanConstantAndTrue ($constName) { // : Boolean
2254         // Failed by default
2255         $res = false;
2256
2257         // In cache?
2258         if (isset($GLOBALS['cache_array']['const'][$constName])) {
2259                 // Use cache
2260                 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-CACHE!<br />");
2261                 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2262         } else {
2263                 // Check constant
2264                 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-RESOLVE!<br />");
2265                 if (defined($constName)) {
2266                         // Found!
2267                         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): " . $constName."-FOUND!<br />");
2268                         $res = (constant($constName) === true);
2269                 } // END - if
2270
2271                 // Set cache
2272                 $GLOBALS['cache_array']['const'][$constName] = $res;
2273         }
2274         //* DEBUG: */ var_dump($res);
2275
2276         // Return value
2277         return $res;
2278 }
2279
2280 // Checks if a given apache module is loaded
2281 function isApacheModuleLoaded ($apacheModule) {
2282         // Check it and return result
2283         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2284 }
2285
2286 // Get current theme name
2287 function getCurrentTheme () {
2288         // The default theme is 'default'... ;-)
2289         $ret = 'default';
2290
2291         // Do we have ext-theme installed and active?
2292         if (isExtensionActive('theme')) {
2293                 // Call inner method
2294                 $ret = getActualTheme();
2295         } // END - if
2296
2297         // Return theme value
2298         return $ret;
2299 }
2300
2301 // Generates an error code from given account status
2302 function generateErrorCodeFromUserStatus ($status='') {
2303         // If no status is provided, use the default, cached
2304         if ((empty($status)) && (isMember())) {
2305                 // Get user status
2306                 $status = getUserData('status');
2307         } // END - if
2308
2309         // Default error code if unknown account status
2310         $errorCode = getCode('UNKNOWN_STATUS');
2311
2312         // Generate constant name
2313         $codeName = sprintf("ID_%s", $status);
2314
2315         // Is the constant there?
2316         if (isCodeSet($codeName)) {
2317                 // Then get it!
2318                 $errorCode = getCode($codeName);
2319         } else {
2320                 // Unknown status
2321                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2322         }
2323
2324         // Return error code
2325         return $errorCode;
2326 }
2327
2328 // Function to search for the last modifified file
2329 function searchDirsRecursive ($dir, &$last_changed) {
2330         // Get dir as array
2331         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=" . $dir.'<br />');
2332         // Does it match what we are looking for? (We skip a lot files already!)
2333         // RegexPattern to exclude  ., .., .revision,  .svn, debug.log or .cache in the filenames
2334         $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
2335         $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
2336         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds).'<br />');
2337
2338         // Walk through all entries
2339         foreach ($ds as $d) {
2340                 // Generate proper FQFN
2341                 $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
2342
2343                 // Is it a file and readable?
2344                 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />");
2345                 if (isDirectory($FQFN)) {
2346                         // $FQFN is a directory so also crawl into this directory
2347                         $newDir = $d;
2348                         if (!empty($dir)) $newDir = $dir . '/'. $d;
2349                         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: " . $newDir.'<br />');
2350                         searchDirsRecursive($newDir, $last_changed);
2351                 } elseif (isFileReadable($FQFN)) {
2352                         // $FQFN is a filename and no directory
2353                         $time = filemtime($FQFN);
2354                         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: " . $d." found. (".($last_changed['time'] - $time).")<br />");
2355                         if ($last_changed['time'] < $time) {
2356                                 // This file is newer as the file before
2357                                 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />");
2358                                 $last_changed['path_name'] = $FQFN;
2359                                 $last_changed['time'] = $time;
2360                         } // END - if
2361                 }
2362         } // END - foreach
2363 }
2364
2365 // "Getter" for revision/version data
2366 function getActualVersion ($type = 'Revision') {
2367         // By default nothing is new... ;-)
2368         $new = false;
2369
2370         // Is the cache entry there?
2371         if (isset($GLOBALS['cache_array']['revision'][$type])) {
2372                 // Found so increase cache hit
2373                 incrementStatsEntry('cache_hits');
2374
2375                 // Return it
2376                 return $GLOBALS['cache_array']['revision'][$type][0];
2377         } else {
2378                 // FQFN of revision file
2379                 $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
2380
2381                 // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
2382                 if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
2383                         // Forced rebuild of .revision file
2384                         $new = true;
2385                 } else {
2386                         // Check for revision file
2387                         if (!isFileReadable($FQFN)) {
2388                                 // Not found, so we need to create it
2389                                 $new = true;
2390                         } else {
2391                                 // Revision file found
2392                                 $ins_vers = explode("\n", readFromFile($FQFN));
2393
2394                                 // Get array for mapping information
2395                                 $mapper = array_flip(getSearchFor());
2396                                 //* DEBUG: */ print('<pre>mapper='.print_r($mapper, true).'</pre>ins_vers=<pre>'.print_r($ins_vers, true).'</pre>');
2397
2398                                 // Is the content valid?
2399                                 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
2400                                         // File needs update!
2401                                         $new = true;
2402                                 } else {
2403                                         // Generate fake cache entry
2404                                         foreach ($mapper as $map => $idx) {
2405                                                 $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
2406                                         } // END - foreach
2407
2408                                         // Return found value
2409                                         return trim($ins_vers[$mapper[$type]]);
2410                                 }
2411                         }
2412                 }
2413
2414                 // Has it been updated?
2415                 if ($new === true)  {
2416                         // Write it
2417                         writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2418
2419                         // ... and call recursive
2420                         return getActualVersion($type);
2421                 } // END - if
2422         }
2423 }
2424
2425 // Repares an array we are looking for
2426 // 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
2427 function getSearchFor () {
2428         // Add Revision, Date, Tag and Author
2429         $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
2430
2431         // Return the created array
2432         return $searchFor;
2433 }
2434
2435 // @TODO Please describe this function
2436 function getArrayFromActualVersion () {
2437         // Init variables
2438         $next_dir = '';
2439
2440         // Directory to start with search
2441         $last_changed = array(
2442                 'path_name' => '',
2443                 'time'      => 0
2444         );
2445
2446         // Init return array
2447         $akt_vers = array();
2448
2449         // Init value for counting the founded keywords
2450         $res = '0';
2451
2452         // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2453         searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2454
2455         // Get file
2456         $last_file = readFromFile($last_changed['path_name']);
2457
2458         // Get all the keywords to search for
2459         $searchFor = getSearchFor();
2460
2461         // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2462         foreach ($searchFor as $search) {
2463                 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2464                 $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
2465                 // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
2466                 if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
2467         } // END - foreach
2468
2469         // Save the last-changed filename for debugging
2470         $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
2471
2472         // at least 3 keyword-Tags are needed for propper values
2473         if ($res && $res >= 3
2474         && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
2475         && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
2476         && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
2477                 // Prepare content witch need special treadment
2478
2479                 // Prepare timestamp for date
2480                 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
2481                 $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2482
2483                 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2484                 if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
2485                         $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
2486                 } // END - if
2487
2488         } else {
2489                 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2490                 $version = sendGetRequest('check-updates3.php');
2491
2492                 // Prepare content
2493                 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2494                 if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
2495                 if (!isset($GLOBALS['cache_array']['revision']['Date'])     || $GLOBALS['cache_array']['revision']['Date']     == '') $GLOBALS['cache_array']['revision']['Date']     = trim($version[9]);
2496                 if (!isset($GLOBALS['cache_array']['revision']['Tag'])      || $GLOBALS['cache_array']['revision']['Tag']      == '') $GLOBALS['cache_array']['revision']['Tag']      = trim($version[8]);
2497                 if (!isset($GLOBALS['cache_array']['revision']['Author'])   || $GLOBALS['cache_array']['revision']['Author']   == '') $GLOBALS['cache_array']['revision']['Author']   = 'quix0r';
2498                 if (!isset($GLOBALS['cache_array']['revision']['File'])     || $GLOBALS['cache_array']['revision']['File']     == '') $GLOBALS['cache_array']['revision']['File']     = trim($version[11]);
2499         }
2500
2501         // Return prepared array
2502         return $GLOBALS['cache_array']['revision'];
2503 }
2504
2505 // Back-ported from the new ship-simu engine. :-)
2506 function debug_get_printable_backtrace () {
2507         // Init variable
2508         $backtrace = "<ol>\n";
2509
2510         // Get and prepare backtrace for output
2511         $backtraceArray = debug_backtrace();
2512         foreach ($backtraceArray as $key => $trace) {
2513                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2514                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2515                 if (!isset($trace['args'])) $trace['args'] = array();
2516                 $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";
2517         } // END - foreach
2518
2519         // Close it
2520         $backtrace .= "</ol>\n";
2521
2522         // Return the backtrace
2523         return $backtrace;
2524 }
2525
2526 // A mail-able backtrace
2527 function debug_get_mailable_backtrace () {
2528         // Init variable
2529         $backtrace = '';
2530
2531         // Get and prepare backtrace for output
2532         $backtraceArray = debug_backtrace();
2533         foreach ($backtraceArray as $key => $trace) {
2534                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2535                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2536                 if (!isset($trace['args'])) $trace['args'] = array();
2537                 $backtrace .= ($key+1) . '.:' . basename($trace['file']) . ':' . $trace['line'] . ', ' . $trace['function'] . '(' . count($trace['args']) . ")\n";
2538         } // END - foreach
2539
2540         // Return the backtrace
2541         return $backtrace;
2542 }
2543
2544 // Output a debug backtrace to the user
2545 function debug_report_bug ($message = '', $sendEmail = true) {
2546         // Is this already called?
2547         if (isset($GLOBALS[__FUNCTION__])) {
2548                 // Other backtrace
2549                 print 'Message:'.$message.'<br />Backtrace:<pre>';
2550                 debug_print_backtrace();
2551                 die('</pre>');
2552         } // END - if
2553
2554         // Set this function as called
2555         $GLOBALS[__FUNCTION__] = true;
2556
2557         // Init message
2558         $debug = '';
2559
2560         // Is the optional message set?
2561         if (!empty($message)) {
2562                 // Use and log it
2563                 $debug = sprintf("Note: %s<br />\n",
2564                         $message
2565                 );
2566
2567                 // @TODO Add a little more infos here
2568                 logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
2569         } // END - if
2570
2571         // Add output
2572         $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>";
2573         $debug .= debug_get_printable_backtrace();
2574         $debug .= "</pre>\nRequest-URI: " . getRequestUri()."<br />\n";
2575         $debug .= "Thank you for finding bugs.";
2576
2577         // Send an email? (e.g. not wanted for evaluation errors)
2578         if ($sendEmail === true) {
2579                 // Prepare content
2580                 $content = array(
2581                         'message'     => trim($message),
2582                         'backtrace'   => trim(debug_get_mailable_backtrace())
2583                 );
2584
2585                 // Send email to webmaster
2586                 sendAdminNotification(getMessage('DEBUG_REPORT_BUG_SUBJECT'), 'admin_report_bug', $content);
2587         } // END - if
2588
2589         // And abort here
2590         app_die(__FUNCTION__, __LINE__, $debug);
2591 }
2592
2593 // Generates a ***weak*** seed
2594 function generateSeed () {
2595         return microtime(true) * 100000;
2596 }
2597
2598 // Converts a message code to a human-readable message
2599 function getMessageFromErrorCode ($code) {
2600         $message = '';
2601         switch ($code) {
2602                 case '': break;
2603                 case getCode('LOGOUT_DONE')       : $message = getMessage('LOGOUT_DONE'); break;
2604                 case getCode('LOGOUT_FAILED')     : $message = '<span class="guest_failed">{--LOGOUT_FAILED--}</span>'; break;
2605                 case getCode('DATA_INVALID')      : $message = getMessage('MAIL_DATA_INVALID'); break;
2606                 case getCode('POSSIBLE_INVALID')  : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
2607                 case getCode('ACCOUNT_LOCKED')    : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2608                 case getCode('USER_404')          : $message = getMessage('USER_404'); break;
2609                 case getCode('STATS_404')         : $message = getMessage('MAIL_STATS_404'); break;
2610                 case getCode('ALREADY_CONFIRMED') : $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2611                 case getCode('WRONG_PASS')        : $message = getMessage('LOGIN_WRONG_PASS'); break;
2612                 case getCode('WRONG_ID')          : $message = getMessage('LOGIN_WRONG_ID'); break;
2613                 case getCode('STATUS_LOCKED')     : $message = getMessage('LOGIN_STATUS_LOCKED'); break;
2614                 case getCode('STATUS_UNCONFIRMED'): $message = getMessage('LOGIN_STATUS_UNCONFIRMED'); break;
2615                 case getCode('COOKIES_DISABLED')  : $message = getMessage('LOGIN_COOKIES_DISABLED'); break;
2616                 case getCode('BEG_SAME_AS_OWN')   : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
2617                 case getCode('LOGIN_FAILED')      : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
2618                 case getCode('MODULE_MEM_ONLY')   : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
2619                 case getCode('OVERLENGTH')        : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
2620                 case getCode('URL_FOUND')         : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
2621                 case getCode('SUBJ_URL')          : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
2622                 case getCode('BLIST_URL')         : $message = "{--MEMBER_URL_BLACK_LISTED--}<br />\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
2623                 case getCode('NO_RECS_LEFT')      : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
2624                 case getCode('INVALID_TAGS')      : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
2625                 case getCode('MORE_POINTS')       : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
2626                 case getCode('MORE_RECEIVERS1')   : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
2627                 case getCode('MORE_RECEIVERS2')   : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
2628                 case getCode('MORE_RECEIVERS3')   : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
2629                 case getCode('INVALID_URL')       : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
2630
2631                 case getCode('ERROR_MAILID'):
2632                         if (isExtensionActive('mailid', true)) {
2633                                 $message = getMessage('ERROR_CONFIRMING_MAIL');
2634                         } else {
2635                                 $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2636                         }
2637                         break;
2638
2639                 case getCode('EXTENSION_PROBLEM'):
2640                         if (isGetRequestElementSet('ext')) {
2641                                 $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
2642                         } else {
2643                                 $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2644                         }
2645                         break;
2646
2647                 case getCode('URL_TLOCK'):
2648                         $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
2649                                 array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
2650
2651                         // Load timestamp from last order
2652                         list($timestamp) = SQL_FETCHROW($result);
2653                         $timestamp = generateDateTime($timestamp, 1);
2654
2655                         // Free memory
2656                         SQL_FREERESULT($result);
2657
2658                         // Calculate hours...
2659                         $STD = round(getConfig('url_tlock') / 60 / 60);
2660
2661                         // Minutes...
2662                         $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
2663
2664                         // And seconds
2665                         $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
2666
2667                         // Finally contruct the message
2668                         // @TODO Rewrite this old lost code to a template
2669                         $message = "{--MEMBER_URL_TIME_LOCK--}<br />{--CONFIG_URL_TLOCK--} ".$STD."
2670                         {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}<br />
2671                         {--MEMBER_LAST_TLOCK--}: ".$timestamp;
2672                         break;
2673
2674                 default:
2675                         // Missing/invalid code
2676                         $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2677
2678                         // Log it
2679                         logDebugMessage(__FUNCTION__, __LINE__, $message);
2680                         break;
2681         } // END - switch
2682
2683         // Return the message
2684         return $message;
2685 }
2686
2687 // Compile characters which are allowed in URLs
2688 function compileUriCode ($code, $simple = true) {
2689         // Compile constants
2690         if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
2691
2692         // Compile QUOT and other non-HTML codes
2693         $code = str_replace('{DOT}', '.',
2694                 str_replace('{SLASH}', '/',
2695                 str_replace('{QUOT}', "'",
2696                 str_replace('{DOLLAR}', '$',
2697                 str_replace('{OPEN_ANCHOR}', '(',
2698                 str_replace('{CLOSE_ANCHOR}', ')',
2699                 str_replace('{OPEN_SQR}', '[',
2700                 str_replace('{CLOSE_SQR}', ']',
2701                 str_replace('{PER}', '%',
2702                 $code
2703         )))))))));
2704
2705         // Return compiled code
2706         return $code;
2707 }
2708
2709 // Function taken from user comments on www.php.net / function eregi()
2710 function isUrlValidSimple ($url) {
2711         // Prepare URL
2712         $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
2713
2714         // Allows http and https
2715         $http      = "(http|https)+(:\/\/)";
2716         // Test domain
2717         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2718         // Test double-domains (e.g. .de.vu)
2719         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2720         // Test IP number
2721         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2722         // ... directory
2723         $dir       = "((/)+([-_\.[:alnum:]])+)*";
2724         // ... page
2725         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2726         // ... and the string after and including question character
2727         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2728         // Pattern for URLs like http://url/dir/doc.html?var=value
2729         $pattern['d1dpg1']  = $http . $domain1 . $dir . $page . $getstring1;
2730         $pattern['d2dpg1']  = $http . $domain2 . $dir . $page . $getstring1;
2731         $pattern['ipdpg1']  = $http . $ip . $dir . $page . $getstring1;
2732         // Pattern for URLs like http://url/dir/?var=value
2733         $pattern['d1dg1']  = $http . $domain1 . $dir.'/' . $getstring1;
2734         $pattern['d2dg1']  = $http . $domain2 . $dir.'/' . $getstring1;
2735         $pattern['ipdg1']  = $http . $ip . $dir.'/' . $getstring1;
2736         // Pattern for URLs like http://url/dir/page.ext
2737         $pattern['d1dp']  = $http . $domain1 . $dir . $page;
2738         $pattern['d1dp']  = $http . $domain2 . $dir . $page;
2739         $pattern['ipdp']  = $http . $ip . $dir . $page;
2740         // Pattern for URLs like http://url/dir
2741         $pattern['d1d']  = $http . $domain1 . $dir;
2742         $pattern['d2d']  = $http . $domain2 . $dir;
2743         $pattern['ipd']  = $http . $ip . $dir;
2744         // Pattern for URLs like http://url/?var=value
2745         $pattern['d1g1']  = $http . $domain1 . '/' . $getstring1;
2746         $pattern['d2g1']  = $http . $domain2 . '/' . $getstring1;
2747         $pattern['ipg1']  = $http . $ip . '/' . $getstring1;
2748         // Pattern for URLs like http://url?var=value
2749         $pattern['d1g12']  = $http . $domain1 . $getstring1;
2750         $pattern['d2g12']  = $http . $domain2 . $getstring1;
2751         $pattern['ipg12']  = $http . $ip . $getstring1;
2752         // Test all patterns
2753         $reg = false;
2754         foreach ($pattern as $key => $pat) {
2755                 // Debug regex?
2756                 if (isDebugRegExpressionEnabled()) {
2757                         // @TODO Are these convertions still required?
2758                         $pat = str_replace('.', "&#92;&#46;", $pat);
2759                         $pat = str_replace('@', "&#92;&#64;", $pat);
2760                         //* DEBUG: */ outputHtml($key."=&nbsp;" . $pat . '<br />');
2761                 } // END - if
2762
2763                 // Check if expression matches
2764                 $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
2765
2766                 // Does it match?
2767                 if ($reg === true) break;
2768         }
2769
2770         // Return true/false
2771         return $reg;
2772 }
2773
2774 // Wtites data to a config.php-style file
2775 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2776 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2777         // Initialize some variables
2778         $done = false;
2779         $seek++;
2780         $next  = -1;
2781         $found = false;
2782
2783         // Is the file there and read-/write-able?
2784         if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2785                 $search = 'CFG: ' . $comment;
2786                 $tmp = $FQFN . '.tmp';
2787
2788                 // Open the source file
2789                 $fp = fopen($FQFN, 'r') or outputHtml('<strong>READ:</strong> ' . $FQFN . '<br />');
2790
2791                 // Is the resource valid?
2792                 if (is_resource($fp)) {
2793                         // Open temporary file
2794                         $fp_tmp = fopen($tmp, 'w') or outputHtml('<strong>WRITE:</strong> ' . $tmp . '<br />');
2795
2796                         // Is the resource again valid?
2797                         if (is_resource($fp_tmp)) {
2798                                 // Mark temporary file as readable
2799                                 $GLOBALS['file_readable'][$tmp] = true;
2800
2801                                 // Start reading
2802                                 while (!feof($fp)) {
2803                                         // Read from source file
2804                                         $line = fgets ($fp, 1024);
2805
2806                                         if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
2807
2808                                         if ($next > -1) {
2809                                                 if ($next === $seek) {
2810                                                         $next = -1;
2811                                                         $line = $prefix . $DATA . $suffix . "\n";
2812                                                 } else {
2813                                                         $next++;
2814                                                 }
2815                                         } // END - if
2816
2817                                         // Write to temp file
2818                                         fputs($fp_tmp, $line);
2819                                 } // END - while
2820
2821                                 // Close temp file
2822                                 fclose($fp_tmp);
2823
2824                                 // Finished writing tmp file
2825                                 $done = true;
2826                         } // END - if
2827
2828                         // Close source file
2829                         fclose($fp);
2830
2831                         if (($done === true) && ($found === true)) {
2832                                 // Copy back tmp file and delete tmp :-)
2833                                 copyFileVerified($tmp, $FQFN, 0644);
2834                                 return removeFile($tmp);
2835                         } elseif ($found === false) {
2836                                 outputHtml('<strong>CHANGE:</strong> 404!');
2837                         } else {
2838                                 outputHtml('<strong>TMP:</strong> UNDONE!');
2839                         }
2840                 }
2841         } else {
2842                 // File not found, not readable or writeable
2843                 outputHtml('<strong>404:</strong> ' . $FQFN . '<br />');
2844         }
2845
2846         // An error was detected!
2847         return false;
2848 }
2849 // Send notification to admin
2850 function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
2851         if ((isExtensionInstalledAndNewer('admins', '0.4.1')) && (function_exists('sendAdminsEmails'))) {
2852                 // Send new way
2853                 sendAdminsEmails($subject, $templateName, $content, $userid);
2854         } else {
2855                 // Send out out-dated way
2856                 $message = loadEmailTemplate($templateName, $content, $userid);
2857                 sendAdminEmails($subject, $message);
2858         }
2859 }
2860
2861 // Debug message logger
2862 function logDebugMessage ($funcFile, $line, $message, $force=true) {
2863         // Is debug mode enabled?
2864         if ((isDebugModeEnabled()) || ($force === true)) {
2865                 // Remove CRLF
2866                 $message = str_replace("\r", '', str_replace("\n", '', $message));
2867
2868                 // Log this message away, we better don't call app_die() here to prevent an endless loop
2869                 $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
2870                 fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
2871                 fclose($fp);
2872         } // END - if
2873 }
2874
2875 // Handle extra values
2876 function handleExtraValues ($filterFunction, $value, $extraValue) {
2877         // Default is the value itself
2878         $ret = $value;
2879
2880         // Do we have a special filter function?
2881         if (!empty($filterFunction)) {
2882                 // Does the filter function exist?
2883                 if (function_exists($filterFunction)) {
2884                         // Do we have extra parameters here?
2885                         if (!empty($extraValue)) {
2886                                 // Put both parameters in one new array by default
2887                                 $args = array($value, $extraValue);
2888
2889                                 // If we have an array simply use it and pre-extend it with our value
2890                                 if (is_array($extraValue)) {
2891                                         // Make the new args array
2892                                         $args = merge_array(array($value), $extraValue);
2893                                 } // END - if
2894
2895                                 // Call the multi-parameter call-back
2896                                 $ret = call_user_func_array($filterFunction, $args);
2897                         } else {
2898                                 // One parameter call
2899                                 $ret = call_user_func($filterFunction, $value);
2900                         }
2901                 } // END - if
2902         } // END - if
2903
2904         // Return the value
2905         return $ret;
2906 }
2907
2908 // Converts timestamp selections into a timestamp
2909 function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
2910         // Init test variable
2911         $skip  = false;
2912         $test2 = '';
2913
2914         // Get last three chars
2915         $test = substr($id, -3);
2916
2917         // Improved way of checking! :-)
2918         if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2919                 // Found a multi-selection for timings?
2920                 $test = substr($id, 0, -3);
2921                 if ((isset($postData[$test.'_ye'])) && (isset($postData[$test.'_mo'])) && (isset($postData[$test.'_we'])) && (isset($postData[$test.'_da'])) && (isset($postData[$test.'_ho'])) && (isset($postData[$test.'_mi'])) && (isset($postData[$test.'_se'])) && ($test != $test2)) {
2922                         // Generate timestamp
2923                         $postData[$test] = createTimestampFromSelections($test, $postData);
2924                         $DATA[] = sprintf("`%s`='%s'", $test, $postData[$test]);
2925                         $GLOBALS['skip_config'][$test] = true;
2926
2927                         // Remove data from array
2928                         foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2929                                 unset($postData[$test . '_' . $rem]);
2930                         } // END - foreach
2931
2932                         // Skip adding
2933                         unset($id);
2934                         $skip = true;
2935                         $test2 = $test;
2936                 } // END - if
2937         } // END - if
2938 }
2939
2940 // Reverts the german decimal comma into Computer decimal dot
2941 function convertCommaToDot ($str) {
2942         // Default float is not a float... ;-)
2943         $float = false;
2944
2945         // Which language is selected?
2946         switch (getLanguage()) {
2947                 case 'de': // German language
2948                         // Remove german thousand dots first
2949                         $str = str_replace('.', '', $str);
2950
2951                         // Replace german commata with decimal dot and cast it
2952                         $float = (float)str_replace(',', '.', $str);
2953                         break;
2954
2955                 default: // US and so on
2956                         // Remove thousand dots first and cast
2957                         $float = (float)str_replace(',', '', $str);
2958                         break;
2959         }
2960
2961         // Return float
2962         return $float;
2963 }
2964
2965 // Handle menu-depending failed logins and return the rendered content
2966 function handleLoginFailtures ($accessLevel) {
2967         // Default output is empty ;-)
2968         $OUT = '';
2969
2970         // Is the session data set?
2971         if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
2972                 // Ignore zero values
2973                 if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
2974                         // Non-guest has login failures found, get both data and prepare it for template
2975                         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />");
2976                         $content = array(
2977                                 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
2978                                 'last_failure'   => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
2979                         );
2980
2981                         // Load template
2982                         $OUT = loadTemplate('login_failures', true, $content);
2983                 } // END - if
2984
2985                 // Reset session data
2986                 setSession('mxchange_' . $accessLevel.'_failures', '');
2987                 setSession('mxchange_' . $accessLevel.'_last_fail', '');
2988         } // END - if
2989
2990         // Return rendered content
2991         return $OUT;
2992 }
2993
2994 // Rebuild cache
2995 function rebuildCacheFile ($cache, $inc = '', $force = false) {
2996         // Debug message
2997         /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
2998
2999         // Shall I remove the cache file?
3000         if (isCacheInstanceValid()) {
3001                 // Rebuild cache
3002                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3003                         // Destroy it
3004                         $GLOBALS['cache_instance']->removeCacheFile($force);
3005                 } // END - if
3006
3007                 // Include file given?
3008                 if (!empty($inc)) {
3009                         // Construct FQFN
3010                         $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
3011
3012                         // Is the include there?
3013                         if (isIncludeReadable($inc)) {
3014                                 // And rebuild it from scratch
3015                                 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />");
3016                                 loadInclude($inc);
3017                         } else {
3018                                 // Include not found!
3019                                 logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3020                         }
3021                 } // END - if
3022         } // END - if
3023 }
3024
3025 // Determines the real remote address
3026 function determineRealRemoteAddress () {
3027         // Is a proxy in use?
3028         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
3029                 // Proxy was used
3030                 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3031         } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
3032                 // Yet, another proxy
3033                 $address = $_SERVER['HTTP_CLIENT_IP'];
3034         } else {
3035                 // The regular address when no proxy was used
3036                 $address = $_SERVER['REMOTE_ADDR'];
3037         }
3038
3039         // This strips out the real address from proxy output
3040         if (strstr($address, ',')) {
3041                 $addressArray = explode(',', $address);
3042                 $address = $addressArray[0];
3043         } // END - if
3044
3045         // Return the result
3046         return $address;
3047 }
3048
3049 // Adds a bonus mail to the queue
3050 // This is a high-level function!
3051 function addNewBonusMail ($data, $mode = '', $output=true) {
3052         // Use mode from data if not set and availble ;-)
3053         if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3054
3055         // Generate receiver list
3056         $receiver = generateReceiverList($data['cat'], $data['receiver'], $mode);
3057
3058         // Receivers added?
3059         if (!empty($receiver)) {
3060                 // Add bonus mail to queue
3061                 addBonusMailToQueue(
3062                 $data['subject'],
3063                 $data['text'],
3064                 $receiver,
3065                 $data['points'],
3066                 $data['seconds'],
3067                 $data['url'],
3068                 $data['cat'],
3069                 $mode,
3070                 $data['receiver']
3071                 );
3072
3073                 // Mail inserted into bonus pool
3074                 if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3075         } elseif ($output) {
3076                 // More entered than can be reached!
3077                 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3078         } else {
3079                 // Debug log
3080                 logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3081         }
3082 }
3083
3084 // Determines referal id and sets it
3085 function determineReferalId () {
3086         // Skip this in non-html-mode and outside ref.php
3087         if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
3088
3089         // Check if refid is set
3090         if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
3091                 // This is fine...
3092         } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
3093                 // The variable user comes from the click-counter script click.php and we only accept this here
3094                 $GLOBALS['refid'] = bigintval(getRequestElement('user'));
3095         } elseif (isPostRequestElementSet('refid')) {
3096                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3097                 $GLOBALS['refid'] = secureString(postRequestElement('refid'));
3098         } elseif (isGetRequestElementSet('refid')) {
3099                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3100                 $GLOBALS['refid'] = secureString(getRequestElement('refid'));
3101         } elseif (isGetRequestElementSet('ref')) {
3102                 // Set refid=ref (the referal link uses such variable)
3103                 $GLOBALS['refid'] = secureString(getRequestElement('ref'));
3104         } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3105                 // Set session refid als global
3106                 $GLOBALS['refid'] = bigintval(getSession('refid'));
3107         } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid') == 'Y')) {
3108                 // Select a random user which has confirmed enougth mails
3109                 $GLOBALS['refid'] = determineRandomReferalId();
3110         } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
3111                 // Set default refid as refid in URL
3112                 $GLOBALS['refid'] = getConfig('def_refid');
3113         } else {
3114                 // No default id when sql_patches is not installed or none set
3115                 $GLOBALS['refid'] = '0';
3116         }
3117
3118         // Set cookie when default refid > 0
3119         if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
3120                 // Default is not found
3121                 $found = false;
3122
3123                 // Do we have nickname or userid set?
3124                 if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
3125                         // Nickname in URL, so load the id
3126                         $found = fetchUserData($GLOBALS['refid'], 'nickname');
3127                 } elseif ($GLOBALS['refid'] > 0) {
3128                         // Direct userid entered
3129                         $found = fetchUserData($GLOBALS['refid']);
3130                 }
3131
3132                 // Is the record valid?
3133                 if ((($found === false) || (!isUserDataValid())) && (isConfigEntrySet('def_refid'))) {
3134                         // No, then reset referal id
3135                         $GLOBALS['refid'] = getConfig('def_refid');
3136                 } // END - if
3137
3138                 // Set cookie
3139                 setSession('refid', $GLOBALS['refid']);
3140         } // END - if
3141
3142         // Return determined refid
3143         return $GLOBALS['refid'];
3144 }
3145
3146 // Enables the reset mode and runs it
3147 function doReset () {
3148         // Enable the reset mode
3149         $GLOBALS['reset_enabled'] = true;
3150
3151         // Run filters
3152         runFilterChain('reset');
3153 }
3154
3155 // Our shutdown-function
3156 function shutdown () {
3157         // Call the filter chain 'shutdown'
3158         runFilterChain('shutdown', null);
3159
3160         if (SQL_IS_LINK_UP()) {
3161                 // Close link
3162                 SQL_CLOSE(__FILE__, __LINE__);
3163         } elseif (!isInstallationPhase()) {
3164                 // No database link
3165                 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3166         }
3167
3168         // Stop executing here
3169         exit;
3170 }
3171
3172 // Init member id
3173 function initMemberId () {
3174         $GLOBALS['member_id'] = '0';
3175 }
3176
3177 // Setter for member id
3178 function setMemberId ($memberid) {
3179         // We should not set member id to zero
3180         if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
3181
3182         // Set it secured
3183         $GLOBALS['member_id'] = bigintval($memberid);
3184 }
3185
3186 // Getter for member id or returns zero
3187 function getMemberId () {
3188         // Default member id
3189         $memberid = '0';
3190
3191         // Is the member id set?
3192         if (isMemberIdSet()) {
3193                 // Then use it
3194                 $memberid = $GLOBALS['member_id'];
3195         } // END - if
3196
3197         // Return it
3198         return $memberid;
3199 }
3200
3201 // Checks ether the member id is set
3202 function isMemberIdSet () {
3203         return (isset($GLOBALS['member_id']));
3204 }
3205
3206 // Handle message codes from URL
3207 function handleCodeMessage () {
3208         if (isGetRequestElementSet('code')) {
3209                 // Default extension is 'unknown'
3210                 $ext = 'unknown';
3211
3212                 // Is extension given?
3213                 if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
3214
3215                 // Convert the 'code' parameter from URL to a human-readable message
3216                 $message = getMessageFromErrorCode(getRequestElement('code'));
3217
3218                 // Load message template
3219                 loadTemplate('message', false, $message);
3220         } // END - if
3221 }
3222
3223 // Setter for extra title
3224 function setExtraTitle ($extraTitle) {
3225         $GLOBALS['extra_title'] = $extraTitle;
3226 }
3227
3228 // Getter for extra title
3229 function getExtraTitle () {
3230         // Is the extra title set?
3231         if (!isExtraTitleSet()) {
3232                 // No, then abort here
3233                 debug_report_bug('extra_title is not set!');
3234         } // END - if
3235
3236         // Return it
3237         return $GLOBALS['extra_title'];
3238 }
3239
3240 // Checks if the extra title is set
3241 function isExtraTitleSet () {
3242         return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3243 }
3244
3245 // Generates a 'extension foo inactive' message
3246 function generateExtensionInactiveMessage ($ext_name) {
3247         // Is the extension empty?
3248         if (empty($ext_name)) {
3249                 // This should not happen
3250                 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3251         } // END - if
3252
3253         // Default message
3254         $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3255
3256         // Is an admin logged in?
3257         if (isAdmin()) {
3258                 // Then output admin message
3259                 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
3260         } // END - if
3261
3262         // Return prepared message
3263         return $message;
3264 }
3265
3266 // Generates a 'extension foo not installed' message
3267 function generateExtensionNotInstalledMessage ($ext_name) {
3268         // Is the extension empty?
3269         if (empty($ext_name)) {
3270                 // This should not happen
3271                 debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
3272         } // END - if
3273
3274         // Default message
3275         $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3276
3277         // Is an admin logged in?
3278         if (isAdmin()) {
3279                 // Then output admin message
3280                 $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
3281         } // END - if
3282
3283         // Return prepared message
3284         return $message;
3285 }
3286
3287 // Generates a message depending on if the extension is not installed or not
3288 // just activated
3289 function generateExtensionInactiveNotInstalledMessage ($ext_name) {
3290         // Init message
3291         $message = '';
3292
3293         // Is the extension not installed or just deactivated?
3294         switch (isExtensionInstalled($ext_name)) {
3295                 case true; // Deactivated!
3296                         $message = generateExtensionInactiveMessage($ext_name);
3297                         break;
3298
3299                 case false; // Not installed!
3300                         $message = generateExtensionNotInstalledMessage($ext_name);
3301                         break;
3302
3303                 default: // Should not happen!
3304                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
3305                         $message = sprintf("Invalid state of extension %s detected.", $ext_name);
3306                         break;
3307         } // END - switch
3308
3309         // Return the message
3310         return $message;
3311 }
3312
3313 // Reads a directory recursively by default and searches for files not matching
3314 // an exclusion pattern. You can now keep the exclusion pattern empty for reading
3315 // a whole directory.
3316 function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true, $suffix = '') {
3317         // Add default entries we should exclude
3318         $excludeArray[] = '.';
3319         $excludeArray[] = '..';
3320         $excludeArray[] = '.svn';
3321         $excludeArray[] = '.htaccess';
3322
3323         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
3324         // Init includes
3325         $files = array();
3326
3327         // Open directory
3328         $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
3329
3330         // Read all entries
3331         while ($baseFile = readdir($dirPointer)) {
3332                 // Exclude '.', '..' and entries in $excludeArray automatically
3333                 if (in_array($baseFile, $excludeArray, true))  {
3334                         // Exclude them
3335                         //* DEBUG: */ outputHtml('excluded=' . $baseFile . '<br />');
3336                         continue;
3337                 } // END - if
3338
3339                 // Construct include filename and FQFN
3340                 $fileName = $baseDir . $baseFile;
3341                 $FQFN = getConfig('PATH') . $fileName;
3342
3343                 // Remove double slashes
3344                 $FQFN = str_replace('//', '/', $FQFN);
3345
3346                 // Check if the base filenname matches an exclusion pattern and if the pattern is not empty
3347                 if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
3348                         // These Lines are only for debugging!!
3349                         //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '<br />');
3350                         //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '<br />');
3351                         //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '<br />');
3352
3353                         // Exclude this one
3354                         continue;
3355                 } // END - if
3356
3357                 // Skip also files with non-matching prefix genericly
3358                 if (($recursive === true) && (isDirectory($FQFN))) {
3359                         // Is a redirectory so read it as well
3360                         $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
3361
3362                         // And skip further processing
3363                         continue;
3364                 } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
3365                         // Skip this file
3366                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
3367                         continue;
3368                 } elseif ((!empty($suffix)) && (substr($baseFile, -(strlen($suffix . $extension)), (strlen($suffix . $extension))) != $suffix . $extension)) {
3369                         // Skip wrong suffix as well
3370                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid suffix in file " . $baseFile . ", suffix=" . $suffix);
3371                         continue;
3372                 } elseif (!isFileReadable($FQFN)) {
3373                         // Not readable so skip it
3374                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
3375                         continue;
3376                 }
3377
3378                 // Is the file a PHP script or other?
3379                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
3380                 if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
3381                         // Is this a valid include file?
3382                         if ($extension == '.php') {
3383                                 // Remove both for extension name
3384                                 $extName = substr($baseFile, strlen($prefix), -4);
3385
3386                                 // Is the extension valid and active?
3387                                 if (isExtensionNameValid($extName)) {
3388                                         // Then add this file
3389                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
3390                                         $files[] = $fileName;
3391                                 } else {
3392                                         // Add non-extension files as well
3393                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
3394                                         if ($addBaseDir === true) {
3395                                                 $files[] = $fileName;
3396                                         } else {
3397                                                 $files[] = $baseFile;
3398                                         }
3399                                 }
3400                         } else {
3401                                 // We found .php file but should not search for them, why?
3402                                 debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
3403                         }
3404                 } elseif (substr($baseFile, -4, 4) == $extension) {
3405                         // Other, generic file found
3406                         $files[] = $fileName;
3407                 }
3408         } // END - while
3409
3410         // Close directory
3411         closedir($dirPointer);
3412
3413         // Sort array
3414         sort($files);
3415
3416         // Return array with include files
3417         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
3418         return $files;
3419 }
3420
3421 // Maps a module name into a database table name
3422 function mapModuleToTable ($moduleName) {
3423         // Map only these, still lame code...
3424         switch ($moduleName) {
3425                 // 'index' is the guest's menu
3426                 case 'index': $moduleName = 'guest';  break;
3427                 // ... and 'login' the member's menu
3428                 case 'login': $moduleName = 'member'; break;
3429                 // Anything else will not be mapped, silently.
3430         } // END - switch
3431
3432         // Return result
3433         return $moduleName;
3434 }
3435
3436 // Add SQL debug data to array for later output
3437 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
3438         // Already executed?
3439         if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
3440                 // Then abort here, we don't need to profile a query twice
3441                 return;
3442         } // END - if
3443
3444         // Remeber this as profiled (or not, but we don't care here)
3445         $GLOBALS['debug_sqls'][$F][$L][$sqlString] = true;
3446
3447         // Do we have cache?
3448         if (!isset($GLOBALS['debug_sql_available'])) {
3449                 // Check it and cache it in $GLOBALS
3450                 $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
3451         } // END - if
3452         
3453         // Don't execute anything here if we don't need or ext-other is missing
3454         if ($GLOBALS['debug_sql_available'] === false) {
3455                 return;
3456         } // END - if
3457
3458         // Generate record
3459         $record = array(
3460                 'num_rows' => SQL_NUMROWS($result),
3461                 'affected' => SQL_AFFECTEDROWS(),
3462                 'sql_str'  => $sqlString,
3463                 'timing'   => $timing,
3464                 'file'     => basename($F),
3465                 'line'     => $L
3466         );
3467
3468         // Add it
3469         $GLOBALS['debug_sqls'][] = $record;
3470 }
3471
3472 // Initializes the cache instance
3473 function initCacheInstance () {
3474         // Load include for CacheSystem class
3475         loadIncludeOnce('inc/classes/cachesystem.class.php');
3476
3477         // Initialize cache system only when it's needed
3478         $GLOBALS['cache_instance'] = new CacheSystem();
3479         if ($GLOBALS['cache_instance']->getStatus() != 'done') {
3480                 // Failed to initialize cache sustem
3481                 addFatalMessage(__FILE__, __LINE__, '(<font color="#0000aa">' . __LINE__ . '</font>): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
3482         } // END - if
3483 }
3484
3485 // Getter for message from array or raw message
3486 function getMessageFromIndexedArray ($message, $pos, $array) {
3487         // Check if the requested message was found in array
3488         if (isset($array[$pos])) {
3489                 // ... if yes then use it!
3490                 $ret = $array[$pos];
3491         } else {
3492                 // ... else use default message
3493                 $ret = $message;
3494         }
3495
3496         // Return result
3497         return $ret;
3498 }
3499
3500 // Print code with line numbers
3501 function linenumberCode ($code)    {
3502         if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
3503         $count_lines = count($codeE);
3504
3505         $r = 'Line | Code:<br />';
3506         foreach($codeE as $line => $c) {
3507                 $r .= '<div class="line"><span class="linenum">';
3508                 if ($count_lines == 1) {
3509                         $r .= 1;
3510                 } else {
3511                         $r .= ($line == ($count_lines - 1)) ? '' :  ($line+1);
3512                 }
3513                 $r .= '</span>|';
3514
3515                 // Add code
3516                 $r .= '<span class="linetext">' . htmlentities($c) . '</span></div>';
3517         }
3518
3519         return '<div class="code">' . $r . '</div>';
3520 }
3521
3522 // Convert ';' to ', ' for e.g. receiver list
3523 function convertReceivers ($old) {
3524         return str_replace(';', ', ', $old);
3525 }
3526
3527 // Determines the right page title
3528 function determinePageTitle () {
3529         // Config and database connection valid?
3530         if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
3531                 // Init title
3532                 $TITLE = '';
3533
3534                 // Title decoration enabled?
3535                 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
3536
3537                 // Do we have some extra title?
3538                 if (isExtraTitleSet()) {
3539                         // Then prepent it
3540                         $TITLE .= getExtraTitle() . ' by ';
3541                 } // END - if
3542
3543                 // Add main title
3544                 $TITLE .= getConfig('MAIN_TITLE');
3545
3546                 // Add title of module? (middle decoration will also be added!)
3547                 if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
3548                         $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
3549                 } // END - if
3550
3551                 // Add title from what file
3552                 $mode = '';
3553                 if (getModule() == 'login') $mode = 'member';
3554                 elseif (getModule() == 'index') $mode = 'guest';
3555                 if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getTitleFromMenu($mode, getWhat());
3556
3557                 // Add title decorations? (right)
3558                 if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= ' ' . trim(getConfig('title_right'));
3559
3560                 // Remember title in constant for the template
3561                 $pageTitle = $TITLE;
3562         } elseif ((isInstalled()) && (isAdminRegistered())) {
3563                 // Installed, admin registered but no ext-sql_patches
3564                 $pageTitle = '[-- ' . getConfig('MAIN_TITLE') . ' - ' . getModuleTitle(getModule()) . ' --]';
3565         } elseif ((isInstalled()) && (!isAdminRegistered())) {
3566                 // Installed but no admin registered
3567                 $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
3568         } elseif ((!isInstalled()) || (!isAdminRegistered())) {
3569                 // Installation mode
3570                 $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
3571         } else {
3572                 // Configuration not found!
3573                 $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
3574
3575                 // Do not add the fatal message in installation mode
3576                 if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
3577         }
3578
3579         // Return title
3580         return decodeEntities($pageTitle);
3581 }
3582
3583 // Checks wethere there is a cache file there. This function is cached.
3584 function isTemplateCached ($template) {
3585         // Do we have cached this result?
3586         if (!isset($GLOBALS['template_cache'][$template])) {
3587                 // Generate FQFN
3588                 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3589
3590                 // Is it there?
3591                 $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
3592         } // END - if
3593
3594         // Return it
3595         return $GLOBALS['template_cache'][$template];
3596 }
3597
3598 // Flushes non-flushed template cache to disk
3599 function flushTemplateCache ($template, $eval) {
3600         // Is this cache flushed?
3601         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template) === false) && ($eval != '404')) {
3602                 // Generate FQFN
3603                 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3604
3605                 // Replace username with a call
3606                 $eval = str_replace('$username', '".getUsername()."', $eval);
3607
3608                 // And flush it
3609                 writeToFile($FQFN, $eval, true);
3610         } // END - if
3611 }
3612
3613 // Reads a template cache
3614 function readTemplateCache ($template) {
3615         // Check it again
3616         if ((isDebuggingTemplateCache() === false) && (isTemplateCached($template))) {
3617                 // Generate FQFN
3618                 $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
3619
3620                 // And read from it
3621                 $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
3622         } // END - if
3623
3624         // And return it
3625         return $GLOBALS['template_eval'][$template];
3626 }
3627
3628 // Escapes quotes (default is only double-quotes)
3629 function escapeQuotes ($str, $single = false) {
3630         // Should we escape all?
3631         if ($single === true) {
3632                 // Escape all (including null)
3633                 $str = addslashes($str);
3634         } else {
3635                 // Escape only double-quotes but prevent double-quoting
3636                 $str = str_replace("\\\\", "\\", str_replace('"', "\\\"", $str));
3637         }
3638
3639         // Return the escaped string
3640         return $str;
3641 }
3642
3643 // Escapes the JavaScript code, prevents \r and \n becoming char 10/13
3644 function escapeJavaScriptQuotes ($str) {
3645         // Replace all double-quotes and secure back-ticks
3646         $str = str_replace('"', '\"', str_replace("\\", '{BACK}', $str));
3647
3648         // Return it
3649         return $str;
3650 }
3651
3652 // Send out mails depending on the 'mod/modes' combination
3653 // @TODO Lame description for this function
3654 function sendModeMails ($mod, $modes) {
3655         // Load hash
3656         if (fetchUserData(getMemberId())) {
3657                 // Extract salt from cookie
3658                 $salt = substr(getSession('u_hash'), 0, -40);
3659
3660                 // Now let's compare passwords
3661                 $hash = generatePassString(getUserData('password'));
3662
3663                 // Does the hash match or should we change it?
3664                 if (($hash == getSession('u_hash')) || (postRequestElement('pass1') == postRequestElement('pass2'))) {
3665                         // Load the data
3666                         $content = getUserDataArray();
3667
3668                         // Translate gender
3669                         $content['gender'] = translateGender($content['gender']);
3670
3671                         // Clear/init the content variable
3672                         $content['message'] = '';
3673
3674                         // Which mail?
3675                         // @TODO Move this in a filter
3676                         switch ($mod) {
3677                                 case 'mydata':
3678                                         foreach ($modes as $mode) {
3679                                                 switch ($mode) {
3680                                                         case 'normal': break; // Do not add any special lines
3681                                                         case 'email': // Email was changed!
3682                                                                 $content['message'] = getMessage('MEMBER_CHANGED_EMAIL').": ".postRequestElement('old_email')."\n";
3683                                                                 break;
3684
3685                                                         case 'pass': // Password was changed
3686                                                                 $content['message'] = getMessage('MEMBER_CHANGED_PASS')."\n";
3687                                                                 break;
3688
3689                                                         default:
3690                                                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown mode %s detected.", $mode));
3691                                                                 $content['message'] = getMessage('MEMBER_UNKNOWN_MODE') . ': ' . $mode . "\n\n";
3692                                                                 break;
3693                                                 } // END - switch
3694                                         } // END - foreach
3695
3696                                         if (isExtensionActive('country')) {
3697                                                 // Replace code with description
3698                                                 $content['country'] = generateCountryInfo(postRequestElement('country_code'));
3699                                         } // END - if
3700
3701                                         // Merge content with data from POST
3702                                         $content = merge_array($content, postRequestArray());
3703
3704                                         // Load template
3705                                         $message = loadEmailTemplate('member_mydata_notify', $content, getMemberId());
3706
3707                                         if (getConfig('admin_notify') == 'Y') {
3708                                                 // The admin needs to be notified about a profile change
3709                                                 $message_admin = 'admin_mydata_notify';
3710                                                 $sub_adm   = getMessage('ADMIN_CHANGED_DATA');
3711                                         } else {
3712                                                 // No mail to admin
3713                                                 $message_admin = '';
3714                                                 $sub_adm   = '';
3715                                         }
3716
3717                                         // Set subject lines
3718                                         $sub_mem = getMessage('MEMBER_CHANGED_DATA');
3719
3720                                         // Output success message
3721                                         $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3722                                         break;
3723
3724                                 default: // Unsupported module!
3725                                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported module %s detected.", $mod));
3726                                         $content = "<span class=\"member_failed\">{--UNKNOWN_MODULE--}</span>";
3727                                         break;
3728                         } // END - switch
3729                 } else {
3730                         // Passwords mismatch
3731                         $content = "<span class=\"member_failed\">{--MEMBER_PASSWORD_ERROR--}</span>";
3732                 }
3733         } else {
3734                 // Could not load profile
3735                 $content = "<span class=\"member_failed\">{--MEMBER_CANNOT_LOAD_PROFILE--}</span>";
3736         }
3737
3738         // Send email to user if required
3739         if ((!empty($sub_mem)) && (!empty($message))) {
3740                 // Send member mail
3741                 sendEmail($content['email'], $sub_mem, $message);
3742         } // END - if
3743
3744         // Send only if no other error has occured
3745         if (empty($content)) {
3746                 if ((!empty($sub_adm)) && (!empty($message_admin))) {
3747                         // Send admin mail
3748                         sendAdminNotification($sub_adm, $message_admin, $content, getMemberId());
3749                 } elseif (getConfig('admin_notify') == 'Y') {
3750                         // Cannot send mails to admin!
3751                         $content = getMessage('CANNOT_SEND_ADMIN_MAILS');
3752                 } else {
3753                         // No mail to admin
3754                         $content = "<span class=\"member_done\">{--MYDATA_MAIL_SENT--}</span>";
3755                 }
3756         } // END - if
3757
3758         // Load template
3759         loadTemplate('admin_settings_saved', false, $content);
3760 }
3761
3762 // Generates a 'selection box' from given array
3763 function generateSelectionBoxFromArray ($options, $name, $optionValue, $optionContent) {
3764         // Start the output
3765         $OUT = '<select name="' . $name . '" size="1" class="admin_select">
3766 <option value="X" disabled="disabled">{--PLEASE_SELECT--}</option>';
3767
3768         // Walk through all options
3769         foreach ($options as $option) {
3770                 // Add the <option> entry
3771                 $OUT .= '<option value="' . $option[$optionValue] . '">' . $option[$optionContent] . '</option>';
3772         } // END - foreach
3773
3774         // Finish selection box
3775         $OUT .= '</select>';
3776
3777         // Prepare output
3778         $content = array(
3779                 'selection_box' => $OUT,
3780                 'module'        => getModule(),
3781                 'what'          => getWhat()
3782         );
3783
3784         // Load template and return it
3785         return loadTemplate('select_' . $name . '_box', true, $content);
3786 }
3787
3788 // Get a module from filename and access level
3789 function getModuleFromFileName ($file, $accessLevel) {
3790         // Default is 'invalid';
3791         $modCheck = 'invalid';
3792
3793         // @TODO This is still very static, rewrite it somehow
3794         switch ($accessLevel) {
3795                 case 'admin':
3796                         $modCheck = 'admin';
3797                         break;
3798
3799                 case 'sponsor':
3800                 case 'guest':
3801                 case 'member':
3802                         $modCheck = getModule();
3803                         break;
3804
3805                 default: // Unsupported file name / access level
3806                         debug_report_bug('Unsupported file name=' . basename($file) . '/access level=' . $accessLevel);
3807                         break;
3808         }
3809
3810         // Return result
3811         return $modCheck;
3812 }
3813
3814 // Encodes an URL for adding session id, etc.
3815 function encodeUrl ($url, $outputMode = '0') {
3816         // Do we have already have a PHPSESSID inside? Then it is already converted...
3817         if (strpos($url, session_name()) !== false) return $url;
3818
3819         // Do we have a valid session?
3820         if ((($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
3821                 // Invalid session
3822                 // Determine right seperator
3823                 $seperator = '&amp;';
3824                 if (strpos($url, '?') === false) {
3825                         // No question mark
3826                         $seperator = '?';
3827                 } elseif ((getOutputMode() != '0') || ($outputMode != '0')) {
3828                         // Non-HTML mode
3829                         $seperator = '&';
3830                 }
3831
3832                 // Add it to URL
3833                 if (session_id() != '') {
3834                         $url .= $seperator . session_name() . '=' . session_id();
3835                 } // END - if
3836         } // END - if
3837
3838         // Add {?URL?} ?
3839         if ((substr($url, 0, strlen(getConfig('URL'))) != getConfig('URL')) && (substr($url, 0, 7) != '{?URL?}') && (substr($url, 0, 7) != 'http://') && (substr($url, 0, 8) != 'https://')) {
3840                 // Add it
3841                 $url = '{?URL?}/' . $url;
3842         } // END - if
3843
3844         // Return the URL
3845         return $url;
3846 }
3847
3848 // Simple check for spider
3849 function isSpider () {
3850         // Get the UA
3851         $userAgent = strtolower(detectUserAgent(true));
3852
3853         // It should not be empty, if so it is better a spider/bot
3854         if (empty($userAgent)) return true;
3855
3856         // Is it a spider?
3857         return ((strpos($userAgent, 'spider') !== false) || (strpos($userAgent, 'slurp') !== false) || (strpos($userAgent, 'bot') !== false));
3858 }
3859
3860 //////////////////////////////////////////////////
3861 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3862 //////////////////////////////////////////////////
3863 //
3864 if (!function_exists('html_entity_decode')) {
3865         // Taken from documentation on www.php.net
3866         function html_entity_decode ($string) {
3867                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3868                 $trans_tbl = array_flip($trans_tbl);
3869                 return strtr($string, $trans_tbl);
3870         }
3871 } // END - if
3872
3873 if (!function_exists('http_build_query')) {
3874         // Taken from documentation on www.php.net, credits to Marco K. (Germany)
3875         function http_build_query($data, $prefix = '', $sep = '', $key = '') {
3876                 $ret = array();
3877                 foreach ((array)$data as $k => $v) {
3878                         if (is_int($k) && $prefix != null) {
3879                                 $k = urlencode($prefix . $k);
3880                         } // END - if
3881
3882                         if ((!empty($key)) || ($key === 0))  $k = $key.'['.urlencode($k).']';
3883
3884                         if (is_array($v) || is_object($v)) {
3885                                 array_push($ret, http_build_query($v, '', $sep, $k));
3886                         } else {
3887                                 array_push($ret, $k.'='.urlencode($v));
3888                         }
3889                 } // END - foreach
3890
3891                 if (empty($sep)) $sep = ini_get('arg_separator.output');
3892
3893                 return implode($sep, $ret);
3894         }
3895 } // END - if
3896
3897 // [EOF]
3898 ?>