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