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