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