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