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