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