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