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