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