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