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