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