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