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