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