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