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