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