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