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