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