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