5c0715d6bb94e06704c683e33f737315b66c4f31
[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         /*
933         print "<pre>";
934         debug_print_backtrace();
935         die("</pre>");
936         */
937         $OUTPUT = ob_get_contents();
938
939         // Clear it only if there is content
940         if (!empty($OUTPUT)) {
941                 ob_end_clean();
942         } // END - if
943
944         // Add some data to URL if cookies are not accepted
945         if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
946
947         // Probe for bot from search engine
948         if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
949                 // Search engine bot detected so let's rewrite many chars for the link
950                 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
951
952                 // Output new location link as anchor
953                 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
954         } elseif (!headers_sent()) {
955                 // Load URL when headers are not sent
956                 /*
957                 print("<pre>");
958                 debug_print_backtrace();
959                 die("</pre>URL={$URL}");
960                 */
961                 @header ("Location: ".str_replace("&amp;", "&", $URL));
962         } else {
963                 // Output error message
964                 include(PATH."inc/header.php");
965                 LOAD_TEMPLATE("redirect_url", false, str_replace("&amp;", "&", $URL));
966                 include(PATH."inc/footer.php");
967         }
968         exit();
969 }
970 //
971 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
972         global $SEC_CHARS, $URL_CHARS;
973         // Is the code a string?
974         if (!is_string($code)) {
975                 // Silently return it
976                 return $code;
977         } // END - if
978
979         $ARRAY = $SEC_CHARS;
980
981         // Select smaller set of chars to replace when we e.g. want to compile URLs
982         if (!$full) $ARRAY = $URL_CHARS;
983
984         // Compile constants
985         if ($constants) {
986                 // BEFORE 0.2.1 : Language and data constants
987                 // WITH 0.2.1+  : Only language constants
988                 $code = str_replace('{--','".', str_replace('--}','."', $code));
989
990                 // BEFORE 0.2.1 : Not used
991                 // WITH 0.2.1+  : Data constants
992                 $code = str_replace('{!','".', str_replace("!}", '."', $code));
993         } // END - if
994
995         // Compile QUOT and other non-HTML codes
996         foreach ($ARRAY['to'] as $k => $to) {
997                 // Do the reversed thing as in inc/libs/security_functions.php
998                 $code = str_replace($to, $ARRAY['from'][$k], $code);
999         } // END - foreach
1000
1001         // But shall I keep simple quotes for later use?
1002         if ($simple) $code = str_replace("'", '{QUOT}', $code);
1003
1004         // Find $content[bla][blub] entries
1005         @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1006
1007         // Are some matches found?
1008         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1009                 // Replace all matches
1010                 $matchesFound = array();
1011                 foreach ($matches[0] as $key => $match) {
1012                         // Fuzzy look has failed by default
1013                         $fuzzyFound = false;
1014
1015                         // Fuzzy look on match if already found
1016                         foreach ($matchesFound as $found => $set) {
1017                                 // Get test part
1018                                 $test = substr($found, 0, strlen($match));
1019
1020                                 // Does this entry exist?
1021                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1022                                 if ($test == $match) {
1023                                         // Match found!
1024                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1025                                         $fuzzyFound = true;
1026                                         break;
1027                                 } // END - if
1028                         } // END - foreach
1029
1030                         // Skip this entry?
1031                         if ($fuzzyFound) continue;
1032
1033                         // Take all string elements
1034                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1035                                 // Replace it in the code
1036                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1037                                 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1038                                 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1039                                 $matchesFound[$key."_".$matches[4][$key]] = 1;
1040                                 $matchesFound[$match] = 1;
1041                         } elseif (!isset($matchesFound[$match])) {
1042                                 // Not yet replaced!
1043                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1044                                 $code = str_replace($match, "\".".$match.".\"", $code);
1045                                 $matchesFound[$match] = 1;
1046                         }
1047                 } // END - foreach
1048         } // END - if
1049
1050         // Return compiled code
1051         return $code;
1052 }
1053 //
1054 /************************************************************************
1055  *                                                                      *
1056  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
1057  * $a_sort sortiert:                                                    *
1058  *                                                                      *
1059  * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1060  * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben    *
1061  * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird   *
1062  * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A             *
1063  * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren   *
1064  *                                                                      *
1065  * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array    *
1066  * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1067  * Sie, dass es doch nicht so schwer ist! :-)                           *
1068  *                                                                      *
1069  ************************************************************************/
1070 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1071 {
1072         $dummy = $array;
1073         while ($primary_key < count($a_sort)) {
1074                 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1075                         foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1076                                 $match = false;
1077                                 if (!$nums) {
1078                                         // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1079                                         if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1080                                 } elseif ($key != $key2) {
1081                                         // Sort numbers (E.g.: 9 < 10)
1082                                         if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1083                                         if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1))  $match = true;
1084                                 }
1085
1086                                 if ($match) {
1087                                         // We have found two different values, so let's sort whole array
1088                                         foreach ($dummy as $sort_key => $sort_val) {
1089                                                 $t                       = $dummy[$sort_key][$key];
1090                                                 $dummy[$sort_key][$key]  = $dummy[$sort_key][$key2];
1091                                                 $dummy[$sort_key][$key2] = $t;
1092                                                 unset($t);
1093                                         } // END - foreach
1094                                 } // END - if
1095                         } // END - foreach
1096                 } // END - foreach
1097
1098                 // Count one up
1099                 $primary_key++;
1100         } // END - while
1101
1102         // Write back sorted array
1103         $array = $dummy;
1104 }
1105 //
1106 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1107         global $MONTH_DESCR;
1108         $OUT = "";
1109
1110         if ($type == "yn") {
1111                 // This is a yes/no selection only!
1112                 if ($id > 0) $prefix .= "[".$id."]";
1113                 $OUT .= "    <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1114         } else {
1115                 // Begin with regular selection box here
1116                 if (!empty($prefix)) $prefix .= "_";
1117                 $type2 = $type;
1118                 if ($id > 0) $type2 .= "[".$id."]";
1119                 $OUT .= "    <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1120         }
1121
1122         switch ($type) {
1123         case "day": // Day
1124                 for ($idx = 1; $idx < 32; $idx++) {
1125                         $OUT .= "<OPTION value=\"".$idx."\"";
1126                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1127                         $OUT .= ">".$idx."</OPTION>\n";
1128                 } // END - for
1129                 break;
1130
1131         case "month": // Month
1132                 foreach ($MONTH_DESCR as $month => $descr) {
1133                         $OUT .= "<OPTION value=\"".$month."\"";
1134                         if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1135                         $OUT .= ">".$descr."</OPTION>\n";
1136                 } // END - for
1137                 break;
1138
1139         case "year": // Year
1140                 // Get current year
1141                 $YEAR = date('Y', time());
1142
1143                 // Use configured min age or fixed?
1144                 if (GET_EXT_VERSION("other") >= "0.2.1") {
1145                         // Configured
1146                         $startYear = $YEAR - getConfig('min_age');
1147                 } else {
1148                         // Fixed 16 years
1149                         $startYear = $YEAR - 16;
1150                 }
1151
1152                 // Calculate earliest year (100 years old people can still enter Internet???)
1153                 $minYear = $YEAR - 100;
1154
1155                 // Check if the default value is larger than minimum and bigger than actual year
1156                 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1157                         for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1158                                 $OUT .= "<OPTION value=\"".$idx."\"";
1159                                 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1160                                 $OUT .= ">".$idx."</OPTION>\n";
1161                         } // END - for
1162                 } elseif ($DEFAULT == -1) {
1163                         // Current year minus 1
1164                         for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1165                         {
1166                                 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1167                         }
1168                 } else {
1169                         // Get current year and subtract the configured minimum age
1170                         $OUT .= "<OPTION value=\"".($minYear - 1)."\">&lt;".$minYear."</OPTION>\n";
1171                         // Calculate earliest year depending on extension version
1172                         if (GET_EXT_VERSION("other") >= "0.2.1") {
1173                                 // Use configured minimum age
1174                                 $YEAR = date('Y', time()) - getConfig('min_age');
1175                         } else {
1176                                 // Use fixed 16 years age
1177                                 $YEAR = date('Y', time()) - 16;
1178                         }
1179
1180                         // Construct year selection list
1181                         for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1182                                 $OUT .= "<OPTION value=\"".$idx."\"";
1183                                 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1184                                 $OUT .= ">".$idx."</OPTION>\n";
1185                         } // END - for
1186                 }
1187                 break;
1188
1189         case "sec":
1190         case "min":
1191                 for ($idx = 0; $idx < 60; $idx+=5) {
1192                         if (strlen($idx) == 1) $idx = "0".$idx;
1193                         $OUT .= "<OPTION value=\"".$idx."\"";
1194                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1195                         $OUT .= ">".$idx."</OPTION>\n";
1196                 } // END - for
1197                 break;
1198
1199         case "hour":
1200                 for ($idx = 0; $idx < 24; $idx++) {
1201                         if (strlen($idx) == 1) $idx = "0".$idx;
1202                         $OUT .= "<OPTION value=\"".$idx."\"";
1203                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1204                         $OUT .= ">".$idx."</OPTION>\n";
1205                 } // END - for
1206                 break;
1207
1208         case "yn":
1209                 $OUT .= "<OPTION value=\"Y\"";
1210                 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1211                 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1212                 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1213                 $OUT .= ">".NO."</OPTION>\n";
1214                 break;
1215         }
1216         $OUT .= "    </SELECT>\n";
1217         return $OUT;
1218 }
1219 //
1220 function TRANSLATE_YESNO($yn)
1221 {
1222         switch ($yn)
1223         {
1224                 case "Y": $yn = YES; break;
1225                 case "N": $yn = NO; break;
1226                 default : $yn = "??? (".$yn.")"; break;
1227         }
1228         return $yn;
1229 }
1230 //
1231 // Deprecated : $length
1232 // Optional   : $DATA
1233 //
1234 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1235         // Fix missing _MAX constant
1236         if (!defined('_MAX')) define('_MAX', 15235);
1237
1238         // Build server string
1239         $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1240
1241         // Build key string
1242         $keys   = SITE_KEY.":".DATE_KEY;
1243         if (getConfig('secret_key') != null)  $keys .= ":".getConfig('secret_key');
1244         if (getConfig('file_hash') != null)   $keys .= ":".getConfig('file_hash');
1245         $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1246         if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1247
1248         // Build string from misc data
1249         $data   = $code.":".$uid.":".$DATA;
1250
1251         // Add more additional data
1252         if (isSessionVariableSet('u_hash'))                     $data .= ":".get_session('u_hash');
1253         if (isset($GLOBALS['userid']))                          $data .= ":".$GLOBALS['userid'];
1254         if (isSessionVariableSet('lifetime'))           $data .= ":".get_session('lifetime');
1255         if (isSessionVariableSet('mxchange_theme'))     $data .= ":".get_session('mxchange_theme');
1256         if (isSessionVariableSet('mx_lang'))            $data .= ":".GET_LANGUAGE();
1257         if (isset($GLOBALS['refid']))                           $data .= ":".$GLOBALS['refid'];
1258
1259         // Calculate number for generating the code
1260         $a = $code + _ADD - 1;
1261
1262         if (getConfig('master_hash') != null) {
1263                 // Generate hash with master salt from modula of number with the prime number and other data
1264                 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1265
1266                 // Create number from hash
1267                 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1268         } else {
1269                 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1270                 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1271
1272                 // Create number from hash
1273                 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1274         }
1275
1276         // At least 10 numbers shall be secure enought!
1277         $len = getConfig('code_length');
1278         if ($len == 0) $len = $length;
1279         if ($len == 0) $len = 10;
1280
1281         // Cut off requested counts of number
1282         $return = substr(str_replace('.', "", $rcode), 0, $len);
1283
1284         // Done building code
1285         return $return;
1286 }
1287 // Does only allow numbers
1288 function bigintval($num, $castValue = true) {
1289         // Filter all numbers out
1290         $ret = preg_replace("/[^0123456789]/", "", $num);
1291
1292         // Shall we cast?
1293         if ($castValue) $ret = (double)$ret;
1294
1295         // Has the whole value changed?
1296         if ("".$ret."" != "".$num."") {
1297                 // Log the values
1298                 print("<pre>");
1299                 debug_print_backtrace();
1300                 die("</pre>");
1301                 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1302         } // END - if
1303
1304         // Return result
1305         return $ret;
1306 }
1307 // Insert the code in $img_code into jpeg or PNG image
1308 function GENERATE_IMAGE($img_code, $header=true) {
1309         if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1310                 // Stop execution of function here because of over-sized code length
1311                 return;
1312         } elseif (!$header) {
1313                 // Return in an HTML code code
1314                 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1315         }
1316
1317         // Load image
1318         $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), getConfig('img_type'));
1319         if (FILE_READABLE($img)) {
1320                 // Switch image type
1321                 switch (getConfig('img_type'))
1322                 {
1323                 case "jpg":
1324                         // Okay, load image and hide all errors
1325                         $image = @imagecreatefromjpeg($img);
1326                         break;
1327
1328                 case "png":
1329                         // Okay, load image and hide all errors
1330                         $image = @imagecreatefrompng($img);
1331                         break;
1332                 }
1333         } else {
1334                 // Exit function here
1335                 return;
1336         }
1337
1338         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1339         $text_color = imagecolorallocate($image, 0, 0, 0);
1340
1341         // Insert code into image
1342         imagestring($image, 5, 14, 2, $img_code, $text_color);
1343
1344         // Return to browser
1345         header ("Content-Type: image/".getConfig('img_type'));
1346
1347         // Output image with matching image factory
1348         switch (getConfig('img_type')) {
1349                 case "jpg": imagejpeg($image); break;
1350                 case "png": imagepng($image);  break;
1351         }
1352
1353         // Remove image from memory
1354         imagedestroy($image);
1355 }
1356 // Create selection box or array of splitted timestamp
1357 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1358         // Calculate 2-seconds timestamp
1359         $stamp = round($timestamp);
1360         //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1361
1362         // Do we have a leap year?
1363         $SWITCH = 0;
1364         $TEST = date('Y', time()) / 4;
1365         $M1 = date("m", time());
1366         $M2 = date("m", (time() + $timestamp));
1367
1368         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1369         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02"))  $SWITCH = getConfig('one_day');
1370
1371         // First of all years...
1372         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1373         //* DEBUG: */ print("Y={$Y}<br />\n");
1374         // Next months...
1375         $M = abs(floor($timestamp / 2628000 - $Y * 12));
1376         //* DEBUG: */ print("M={$M}<br />\n");
1377         // Next weeks
1378         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1379         //* DEBUG: */ print("W={$W}<br />\n");
1380         // Next days...
1381         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1382         //* DEBUG: */ print("D={$D}<br />\n");
1383         // Next hours...
1384         $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));
1385         //* DEBUG: */ print("h={$h}<br />\n");
1386         // Next minutes..
1387         $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));
1388         //* DEBUG: */ print("m={$m}<br />\n");
1389         // And at last seconds...
1390         $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));
1391         //* DEBUG: */ print("s={$s}<br />\n");
1392
1393         // Is seconds zero and time is < 60 seconds?
1394         if (($s == 0) && ($timestamp < 60)) {
1395                 // Fix seconds
1396                 $s = round($timestamp);
1397         } // END - if
1398
1399         //
1400         // Now we convert them in seconds...
1401         //
1402         if ($return_array) {
1403                 // Just put all data in an array for later use
1404                 $OUT = array(
1405                         'YEARS'   => $Y,
1406                         'MONTHS'  => $M,
1407                         'WEEKS'   => $W,
1408                         'DAYS'    => $D,
1409                         'HOURS'   => $h,
1410                         'MINUTES' => $m,
1411                         'SECONDS' => $s
1412                 );
1413         } else {
1414                 // Generate table
1415                 $OUT  = "<DIV align=\"".$align."\">\n";
1416                 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1417                 $OUT .= "<TR>\n";
1418
1419                 if (ereg('Y', $display) || (empty($display))) {
1420                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1421                 }
1422
1423                 if (ereg("M", $display) || (empty($display))) {
1424                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1425                 }
1426
1427                 if (ereg("W", $display) || (empty($display))) {
1428                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1429                 }
1430
1431                 if (ereg("D", $display) || (empty($display))) {
1432                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1433                 }
1434
1435                 if (ereg("h", $display) || (empty($display))) {
1436                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1437                 }
1438
1439                 if (ereg("m", $display) || (empty($display))) {
1440                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1441                 }
1442
1443                 if (ereg("s", $display) || (empty($display))) {
1444                         $OUT .= "  <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1445                 }
1446
1447                 $OUT .= "</TR>\n";
1448                 $OUT .= "<TR>\n";
1449
1450                 if (ereg('Y', $display) || (empty($display))) {
1451                         // Generate year selection
1452                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1453                         for ($idx = 0; $idx <= 10; $idx++) {
1454                                 $OUT .= "    <OPTION class=\"mini_select\" value=\"".$idx."\"";
1455                                 if ($idx == $Y) $OUT .= " selected default";
1456                                 $OUT .= ">".$idx."</OPTION>\n";
1457                         }
1458                         $OUT .= "  </SELECT></TD>\n";
1459                 } else {
1460                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1461                 }
1462
1463                 if (ereg("M", $display) || (empty($display))) {
1464                         // Generate month selection
1465                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1466                         for ($idx = 0; $idx <= 11; $idx++)
1467                         {
1468                                         $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1469                                 if ($idx == $M) $OUT .= " selected default";
1470                                 $OUT .= ">".$idx."</OPTION>\n";
1471                         }
1472                         $OUT .= "  </SELECT></TD>\n";
1473                 } else {
1474                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1475                 }
1476
1477                 if (ereg("W", $display) || (empty($display))) {
1478                         // Generate week selection
1479                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1480                         for ($idx = 0; $idx <= 4; $idx++) {
1481                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1482                                 if ($idx == $W) $OUT .= " selected default";
1483                                 $OUT .= ">".$idx."</OPTION>\n";
1484                         }
1485                         $OUT .= "  </SELECT></TD>\n";
1486                 } else {
1487                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1488                 }
1489
1490                 if (ereg("D", $display) || (empty($display))) {
1491                         // Generate day selection
1492                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1493                         for ($idx = 0; $idx <= 31; $idx++) {
1494                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1495                                 if ($idx == $D) $OUT .= " selected default";
1496                                 $OUT .= ">".$idx."</OPTION>\n";
1497                         }
1498                         $OUT .= "  </SELECT></TD>\n";
1499                 } else {
1500                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1501                 }
1502
1503                 if (ereg("h", $display) || (empty($display))) {
1504                         // Generate hour selection
1505                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1506                         for ($idx = 0; $idx <= 23; $idx++)      {
1507                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1508                                 if ($idx == $h) $OUT .= " selected default";
1509                                 $OUT .= ">".$idx."</OPTION>\n";
1510                         }
1511                         $OUT .= "  </SELECT></TD>\n";
1512                 } else {
1513                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1514                 }
1515
1516                 if (ereg("m", $display) || (empty($display))) {
1517                         // Generate minute selection
1518                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1519                         for ($idx = 0; $idx <= 59; $idx++) {
1520                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1521                                 if ($idx == $m) $OUT .= " selected default";
1522                                 $OUT .= ">".$idx."</OPTION>\n";
1523                         }
1524                         $OUT .= "  </SELECT></TD>\n";
1525                 } else {
1526                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1527                 }
1528
1529                 if (ereg("s", $display) || (empty($display))) {
1530                         // Generate second selection
1531                         $OUT .= "  <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1532                         for ($idx = 0; $idx <= 59; $idx++) {
1533                                 $OUT .= "  <OPTION class=\"mini_select\" value=\"".$idx."\"";
1534                                 if ($idx == $s) $OUT .= " selected default";
1535                                 $OUT .= ">".$idx."</OPTION>\n";
1536                         }
1537                         $OUT .= "  </SELECT></TD>\n";
1538                 } else {
1539                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1540                 }
1541                 $OUT .= "</TR>\n";
1542                 $OUT .= "</TABLE>\n";
1543                 $OUT .= "</DIV>\n";
1544                 // Return generated HTML code
1545         }
1546         return $OUT;
1547 }
1548 //
1549 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1550         // Initial return value
1551         $ret = 0;
1552
1553         // Do we have a leap year?
1554         $SWITCH = 0;
1555         $TEST = date('Y', time()) / 4;
1556         $M1   = date("m", time());
1557         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1558         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02"))  $SWITCH = getConfig('one_day');
1559         // First add years...
1560         $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1561         // Next months...
1562         $ret += $POST[$prefix."_mo"] * 2628000;
1563         // Next weeks
1564         $ret += $POST[$prefix."_we"] * 604800;
1565         // Next days...
1566         $ret += $POST[$prefix."_da"] * 86400;
1567         // Next hours...
1568         $ret += $POST[$prefix."_ho"] * 3600;
1569         // Next minutes..
1570         $ret += $POST[$prefix."_mi"] * 60;
1571         // And at last seconds...
1572         $ret += $POST[$prefix."_se"];
1573         // Return calculated value
1574         return $ret;
1575 }
1576 // Sends out mail to all administrators
1577 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1578 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1579         // Trim template name
1580         $template = trim($template);
1581
1582         // Load email template
1583         $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1584
1585         if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1586                 // Older version detected!
1587                 return SEND_ADMIN_EMAILS($subj, $msg);
1588         } // END - if
1589
1590         // Check which admin shall receive this mail
1591         $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1592                 array($template), __FILE__, __LINE__);
1593         if (SQL_NUMROWS($result) == 0) {
1594                 // Create new entry (to all admins)
1595                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1596                         array($template), __FILE__, __LINE__);
1597         } else {
1598                 // Load admin IDs...
1599                 $aids = array();
1600                 while(list($aid) = SQL_FETCHROW($result)) {
1601                         $aids[] = $aid;
1602                 }
1603
1604                 // Free memory
1605                 SQL_FREERESULT($result);
1606
1607                 // "implode" IDs and query string
1608                 $aid = implode(",", $aids);
1609                 if ($aid == "-1") {
1610                         // Add line to userlog
1611                         USERLOG_ADD_LINE($subj, $msg, $UID);
1612                         return;
1613                 } elseif ($aid == "0") {
1614                         // Select all email adresses
1615                         $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1616                 } else {
1617                         // If Admin-ID is not "to-all" select
1618                         $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1619                 }
1620         }
1621
1622         // Load email addresses and send away
1623         while (list($email) = SQL_FETCHROW($result)) {
1624                 SEND_EMAIL($email, $subj, $msg);
1625         }
1626
1627         // Free memory
1628         SQL_FREERESULT($result);
1629 }
1630 //
1631 function CREATE_FANCY_TIME ($stamp) {
1632         // Get data array with years/months/weeks/days/...
1633         $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1634         $ret = "";
1635         foreach($data as $k => $v) {
1636                 if ($v > 0) {
1637                         // Value is greater than 0 "eval" data to return string
1638                         $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1639                         eval($eval);
1640                         break;
1641                 } // END - if
1642         } // END - foreach
1643
1644         // Do we have something there?
1645         if (strlen($ret) > 0) {
1646                 // Remove leading commata and space
1647                 $ret = substr($ret, 2);
1648         } else {
1649                 // Zero seconds
1650                 $ret = "0 "._SECONDS;
1651         }
1652
1653         // Return fancy time string
1654         return $ret;
1655 }
1656 //
1657 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1658         $SEP = ""; $TOP = "";
1659         if (!$show_form) {
1660                 $TOP = " top2";
1661                 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\">&nbsp;</TD></TR>";
1662         }
1663
1664         $NAV = "";
1665         for ($page = 1; $page <= $PAGES; $page++) {
1666                 // Is the page currently selected or shall we generate a link to it?
1667                 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1668                         // Is currently selected, so only highlight it
1669                         $NAV .= "<STRONG>-";
1670                 } else {
1671                         // Open anchor tag and add base URL
1672                         $NAV .= "<A href=\"".URL."/modules.php?module=admin&amp;what=".$GLOBALS['what']."&amp;page=".$page."&amp;offset=".$offset;
1673
1674                         // Add userid when we shall show all mails from a single member
1675                         if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&amp;u_id=".bigintval($_GET['u_id']);
1676
1677                         // Close open anchor tag
1678                         $NAV .= "\">";
1679                 }
1680                 $NAV .= $page;
1681                 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1682                         // Is currently selected, so only highlight it
1683                         $NAV .= "-</STRONG>";
1684                 } else {
1685                         // Close anchor tag
1686                         $NAV .= "</A>";
1687                 }
1688
1689                 // Add seperator if we have not yet reached total pages
1690                 if ($page < $PAGES) $NAV .= "&nbsp;|&nbsp;";
1691         }
1692
1693         // Define constants only once
1694         if (!defined('__NAV_OUTPUT')) {
1695                 define('__NAV_OUTPUT' , $NAV);
1696                 define('__NAV_COLSPAN', $colspan);
1697                 define('__NAV_TOP'    , $TOP);
1698                 define('__NAV_SEP'    , $SEP);
1699         }
1700
1701         // Load navigation template
1702         $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1703
1704         if ($return) {
1705                 // Return generated HTML-Code
1706                 return $OUT;
1707         } else {
1708                 // Output HTML-Code
1709                 OUTPUT_HTML($OUT);
1710         }
1711 }
1712
1713 // Extract host from script name
1714 function EXTRACT_HOST (&$script) {
1715         // Use default SERVER_URL by default... ;) So?
1716         $url = SERVER_URL;
1717
1718         // Is this URL valid?
1719         if (substr($script, 0, 7) == "http://") {
1720                 // Use the hostname from script URL as new hostname
1721                 $url = substr($script, 7);
1722                 $extract = explode("/", $url);
1723                 $url = $extract[0];
1724                 // Done extracting the URL :)
1725         } // END - if
1726
1727         // Extract host name
1728         $host = str_replace("http://", "", $url);
1729         if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1730
1731         // Generate relative URL
1732         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1733         if (substr(strtolower($script), 0, 7) == "http://") {
1734                 // But only if http:// is in front!
1735                 $script = substr($script, (strlen($url) + 7));
1736         } elseif (substr(strtolower($script), 0, 8) == "https://") {
1737                 // Does this work?!
1738                 $script = substr($script, (strlen($url) + 8));
1739         }
1740
1741         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1742         if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1743
1744         // Return host name
1745         return $host;
1746 }
1747
1748 // Send a GET request
1749 function GET_URL ($script) {
1750         // Compile the script name
1751         $script = COMPILE_CODE($script);
1752
1753         // Extract host name from script
1754         $host = EXTRACT_HOST($script);
1755
1756         // Generate GET request header
1757         $request  = "GET /" . trim($script) . " HTTP/1.1\r\n";
1758         $request .= "Host: " . $host . "\r\n";
1759         $request .= "Referer: " . URL . "/admin.php\r\n";
1760         $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1761         $request .= "Content-Type: text/plain\r\n";
1762         $request .= "Cache-Control: no-cache\r\n";
1763         $request .= "Connection: Close\r\n\r\n";
1764
1765         // Send the raw request
1766         $response = SEND_RAW_REQUEST($host, $request);
1767
1768         // Return the result to the caller function
1769         return $response;
1770 }
1771
1772 // Send a POST request
1773 function POST_URL ($script, $postData) {
1774         // Is postData an array?
1775         if (!is_array($postData)) {
1776                 // Abort here
1777                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1778                 return array("", "", "");
1779         } // END - if
1780
1781         // Compile the script name
1782         $script = COMPILE_CODE($script);
1783
1784         // Extract host name from script
1785         $host = EXTRACT_HOST($script);
1786
1787         // Construct request
1788         $data = http_build_query($postData, '','&');
1789
1790         // Generate POST request header
1791         $request  = "POST /" . trim($script) . " HTTP/1.1\r\n";
1792         $request .= "Host: " . $host . "\r\n";
1793         $request .= "Referer: " . URL . "/admin.php\r\n";
1794         $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1795         $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1796         $request .= "Content-length: " . strlen($data) . "\r\n";
1797         $request .= "Cache-Control: no-cache\r\n";
1798         $request .= "Connection: Close\r\n\r\n";
1799         $request .= $data;
1800
1801         // Send the raw request
1802         $response = SEND_RAW_REQUEST($host, $request);
1803
1804         // Return the result to the caller function
1805         return $response;
1806 }
1807
1808 // Sends a raw request to another host
1809 function SEND_RAW_REQUEST ($host, $request) {
1810         // Initialize array
1811         $response = array("", "", "");
1812
1813         // Default is not to use proxy
1814         $useProxy = false;
1815
1816         // Are proxy settins set?
1817         if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1818                 // Then use it
1819                 $useProxy = true;
1820         } // END - if
1821
1822         // Open connection
1823         //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1824         if ($useProxy) {
1825                 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1826         } else {
1827                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1828         }
1829
1830         // Is there a link?
1831         if (!is_resource($fp)) {
1832                 // Failed!
1833                 return $response;
1834         } // END - if
1835
1836         // Do we use proxy?
1837         if ($useProxy) {
1838                 // Generate CONNECT request header
1839                 $proxyTunnel  = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1840                 $proxyTunnel .= "Host: ".$host."\r\n";
1841
1842                 // Use login data to proxy? (username at least!)
1843                 if (getConfig('proxy_username') != "") {
1844                         // Add it as well
1845                         $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1846                         $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1847                 } // END - if
1848
1849                 // Add last new-line
1850                 $proxyTunnel .= "\r\n";
1851                 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1852
1853                 // Write request
1854                 fputs($fp, $proxyTunnel);
1855
1856                 // Got response?
1857                 if (feof($fp)) {
1858                         // No response received
1859                         return $response;
1860                 } // END - if
1861
1862                 // Read the first line
1863                 $resp = trim(fgets($fp, 10240));
1864                 $respArray = explode(" ", $resp);
1865                 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1866                         // Invalid response!
1867                         return $response;
1868                 } // END - if
1869         } // END - if
1870
1871         // Write request
1872         fputs($fp, $request);
1873
1874         // Read response
1875         while(!feof($fp)) {
1876                 $response[] = trim(fgets($fp, 1024));
1877         } // END - while
1878
1879         // Close socket
1880         fclose($fp);
1881
1882         // Skip first empty lines
1883         $resp = $response;
1884         foreach ($resp as $idx => $line) {
1885                 // Trim space away
1886                 $line = trim($line);
1887
1888                 // Is this line empty?
1889                 if (empty($line)) {
1890                         // Then remove it
1891                         array_shift($response);
1892                 } else {
1893                         // Abort on first non-empty line
1894                         break;
1895                 }
1896         } // END - foreach
1897
1898         //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1899
1900         // Proxy agent found?
1901         if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1902                 // Proxy header detected, so remove two lines
1903                 array_shift($response);
1904                 array_shift($response);
1905         } // END - if
1906
1907         // Was the request successfull?
1908         if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1909                 // Not found / access forbidden
1910                 $response = array("", "", "");
1911         } // END - if
1912
1913         // Return response
1914         return $response;
1915 }
1916 // Taken from www.php.net eregi() user comments
1917 function VALIDATE_EMAIL($email) {
1918         // Compile email
1919         $email = COMPILE_CODE($email);
1920
1921         // Check first part of email address
1922         $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1923
1924         //  Check domain
1925         $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1926
1927         // Generate pattern
1928         $regex = "^".$first."@".$domain."$";
1929
1930         // Return check result
1931         return eregi($regex, $email);
1932 }
1933 // Function taken from user comments on www.php.net / function eregi()
1934 function VALIDATE_URL ($URL, $compile=true) {
1935         // Trim URL a little
1936         $URL = trim(urldecode($URL));
1937         //* DEBUG: */ echo $URL."<br />";
1938
1939         // Compile some chars out...
1940         if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1941         //* DEBUG: */ echo $URL."<br />";
1942
1943         // Check for the extension filter
1944         if (EXT_IS_ACTIVE("filter")) {
1945                 // Use the extension's filter set
1946                 return FILTER_VALIDATE_URL($URL, false);
1947         }
1948
1949         // If not installed, perform a simple test. Just make it sure there is always a http:// or
1950         // https:// in front of the URLs
1951         return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1952 }
1953 //
1954 function MEMBER_ACTION_LINKS($uid, $status="") {
1955         // Define all main targets
1956         $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1957
1958         // Begin of navigation links
1959         $eval = "\$OUT = \"[&nbsp;";
1960
1961         foreach ($TARGETS as $tar) {
1962                 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&amp;what=".$tar."&amp;u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1963                 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1964                 if (($tar == "lock_user") && ($status == "LOCKED")) {
1965                         // Locked accounts shall be unlocked
1966                         $eval .= "UNLOCK_USER";
1967                 } else {
1968                         // All other status is fine
1969                         $eval .= strtoupper($tar);
1970                 }
1971                 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1972                 if (($tar == "lock_user") && ($status == "LOCKED")) {
1973                         // Locked accounts shall be unlocked
1974                         $eval .= "UNLOCK_USER";
1975                 } else {
1976                         // All other status is fine
1977                         $eval .= strtoupper($tar);
1978                 }
1979                 $eval .= ".\"</A></SPAN>&nbsp;|&nbsp;";
1980         }
1981
1982         // Finish navigation link
1983         $eval = substr($eval, 0, -7)."]\";";
1984         eval($eval);
1985
1986         // Return string
1987         return $OUT;
1988 }
1989 // Function for backward-compatiblity
1990 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
1991         // Load it from the register extension
1992         return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
1993 }
1994 // Generate an email link
1995 function CREATE_EMAIL_LINK ($email, $table = "admins") {
1996         // Default email link (INSECURE! Spammer can read this by harvester programs)
1997         $EMAIL = "mailto:".$email;
1998
1999         // Check for several extensions
2000         if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2001                 // Create email link for contacting admin in guest area
2002                 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2003         } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2004                 // Create email link for contacting a member within admin area (or later in other areas, too?)
2005                 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2006         } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2007                 // Create email link to contact sponsor within admin area (or like the link above?)
2008                 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2009         }
2010
2011         // Shall I close the link when there is no admin?
2012         if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2013
2014         // Return email link
2015         return $EMAIL;
2016 }
2017 // Generate a hash for extra-security for all passwords
2018 function generateHash ($plainText, $salt = "") {
2019         global $_SERVER;
2020
2021         // Is the required extension "sql_patches" there and a salt is not given?
2022         if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2023                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2024                 return md5($plainText);
2025         } // END - if
2026
2027         // Do we miss an arry element here?
2028         if (getConfig('file_hash') == null) {
2029                 // Stop here
2030                 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2031                 debug_print_backtrace();
2032                 die("</pre>");
2033         } // END - if
2034
2035         // When the salt is empty build a new one, else use the first x configured characters as the salt
2036         if (empty($salt)) {
2037                 // Build server string
2038                 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2039
2040                 // Build key string
2041                 $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');
2042
2043                 // Additional data
2044                 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2045
2046                 // Calculate number for generating the code
2047                 $a = time() + _ADD - 1;
2048
2049                 // Generate SHA1 sum from modula of number and the prime number
2050                 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2051                 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2052                 $sha1 = scrambleString($sha1);
2053                 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2054                 //* DEBUG: */ $sha1b = descrambleString($sha1);
2055                 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2056
2057                 // Generate the password salt string
2058                 $salt = substr($sha1, 0, getConfig('salt_length'));
2059                 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2060         } else {
2061                 // Use given salt
2062                 $salt = substr($salt, 0, getConfig('salt_length'));
2063                 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2064         }
2065
2066         // Return hash
2067         return $salt.sha1($salt.$plainText);
2068 }
2069 //
2070 function scrambleString($str) {
2071         // Init
2072         $scrambled = "";
2073
2074         // Final check, in case of failture it will return unscrambled string
2075         if (strlen($str) > 40) {
2076                 // The string is to long
2077                 return $str;
2078         } elseif (strlen($str) == 40) {
2079                 // From database
2080                 $scrambleNums = explode(":", getConfig('pass_scramble'));
2081         } else {
2082                 // Generate new numbers
2083                 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2084         }
2085
2086         // Scramble string here
2087         //* DEBUG: */ echo "***Original=".$str."***<br />";
2088         for ($idx = 0; $idx < strlen($str); $idx++) {
2089                 // Get char on scrambled position
2090                 $char = substr($str, $scrambleNums[$idx], 1);
2091
2092                 // Add it to final output string
2093                 $scrambled .= $char;
2094         } // END - for
2095
2096         // Return scrambled string
2097         //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2098         return $scrambled;
2099 }
2100 //
2101 function descrambleString($str) {
2102         // Scramble only 40 chars long strings
2103         if (strlen($str) != 40) return $str;
2104
2105         // Load numbers from config
2106         $scrambleNums = explode(":", getConfig('pass_scramble'));
2107
2108         // Validate numbers
2109         if (count($scrambleNums) != 40) return $str;
2110
2111         // Begin descrambling
2112         $orig = str_repeat(" ", 40);
2113         //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2114         for ($idx = 0; $idx < 40; $idx++) {
2115                 $char = substr($str, $idx, 1);
2116                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2117         } // END - for
2118
2119         // Return scrambled string
2120         //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2121         return $orig;
2122 }
2123 //
2124 function genScrambleString($len) {
2125         // Prepare randomizer and array for the numbers
2126         mt_srand((double) microtime() * 1000000);
2127         $scrambleNumbers = array();
2128
2129         // First we need to setup randomized numbers from 0 to 31
2130         for ($idx = 0; $idx < $len; $idx++) {
2131                 // Generate number
2132                 $rand = mt_rand(0, ($len -1));
2133
2134                 // Check for it by creating more numbers
2135                 while (array_key_exists($rand, $scrambleNumbers)) {
2136                         $rand = mt_rand(0, ($len -1));
2137                 } // END - while
2138
2139                 // Add number
2140                 $scrambleNumbers[$rand] = $rand;
2141         } // END - for
2142
2143         // So let's create the string for storing it in database
2144         $scrambleString = implode(":", $scrambleNumbers);
2145         return $scrambleString;
2146 }
2147 // Append data like session ID or referal ID to the given URL which would
2148 // normally be stored in cookies
2149 function ADD_URL_DATA ($URL) {
2150         // Init add
2151         $ADD = "";
2152
2153         // Determine URL binder
2154         $BIND = "?";
2155         if (strpos($URL, "?") !== false) $BIND = "&";
2156
2157         if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2158                 // Cookies are not accepted
2159                 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2160                         // Cookie found in URL
2161                         $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2162                 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2163                         // Not found! So let's set default here
2164                         $ADD .= $BIND."refid=".getConfig('def_refid');
2165                 }
2166
2167                 // Is there already added data? Then change the binder
2168                 if (!empty($ADD)) $BIND = "&";
2169
2170                 // Add session ID
2171                 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2172                         // Add session from URL
2173                         $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2174                 } else {
2175                         // Add current session
2176                         $ADD .= $BIND."PHPSESSID=".session_id();
2177                 }
2178         } // END - if
2179
2180         // Add all together and return it
2181         return $URL.$ADD;
2182 }
2183 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2184 function generatePassString($passHash) {
2185         // Return vanilla password hash
2186         $ret = $passHash;
2187
2188         // Is a secret key and master salt already initialized?
2189         if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2190                 // Only calculate when the secret key is generated
2191                 $newHash = ""; $start = 9;
2192                 for ($idx = 0; $idx < 10; $idx++) {
2193                         $part1 = hexdec(substr($passHash, $start, 4));
2194                         $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2195                         $mod = dechex($idx);
2196                         if ($part1 > $part2) {
2197                                 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2198                         } elseif ($part2 > $part1) {
2199                                 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2200                         }
2201                         $mod = substr(round($mod), 0, 4);
2202                         $mod = str_repeat('0', 4-strlen($mod)).$mod;
2203                         //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2204                         $start += 4;
2205                         $newHash .= $mod;
2206                 } // END - for
2207
2208                 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2209                 $ret = generateHash($newHash, getConfig('master_salt'));
2210                 //* DEBUG: */ print($ret."<br />\n");
2211         } else {
2212                 // Hash it simple
2213                 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2214                 $ret = md5($passHash);
2215                 //* DEBUG: */ echo "++".$ret."++<br />\n";
2216         }
2217
2218         // Return result
2219         return $ret;
2220 }
2221
2222 // Fix "deleted" cookies
2223 function FIX_DELETED_COOKIES ($cookies) {
2224         // Is this an array with entries?
2225         if ((is_array($cookies)) && (count($cookies) > 0)) {
2226                 // Then check all cookies if they are marked as deleted!
2227                 foreach ($cookies as $cookieName) {
2228                         // Is the cookie set to "deleted"?
2229                         if (get_session($cookieName) == "deleted") {
2230                                 set_session($cookieName, "");
2231                         }
2232                 } // END - foreach
2233         } // END - if
2234 }
2235
2236 // Output error messages in a fasioned way and die...
2237 function mxchange_die ($msg) {
2238         global $footer;
2239
2240         // Load the message template
2241         LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2242
2243         // Load footer
2244         include(PATH."inc/footer.php");
2245
2246         // Exit explicitly
2247         exit;
2248 }
2249
2250 // Display parsing time and number of SQL queries in footer
2251 function DISPLAY_PARSING_TIME_FOOTER() {
2252         // Is the timer started?
2253         if (!isset($GLOBALS['startTime'])) {
2254                 // Abort here
2255                 return false;
2256         } // END - if
2257
2258         // Get end time
2259         $endTime = microtime(true);
2260
2261         // "Explode" both times
2262         $start = explode(" ", $GLOBALS['startTime']);
2263         $end = explode(" ", $endTime);
2264         $runTime = $end[0] - $start[0];
2265         if ($runTime < 0) $runTime = 0;
2266         $runTime = TRANSLATE_COMMA($runTime);
2267
2268         // Prepare output
2269         $content = array(
2270                 'runtime'               => $runTime,
2271                 'numSQLs'               => (getConfig('sql_count') + 1),
2272                 'numTemplates'  => (getConfig('num_templates') + 1)
2273         );
2274
2275         // Load the template
2276         LOAD_TEMPLATE("show_timings", false, $content);
2277 }
2278
2279 // Unset/set session variables
2280 function set_session ($var, $value) {
2281         global $CSS;
2282
2283         // Abort in CSS mode here
2284         if ($CSS == 1) return true;
2285
2286         // Trim value and session variable
2287         $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2288
2289         // Is the session variable set?
2290         if (("".$value."" == "") && (isSessionVariableSet($var))) {
2291                 // Remove the session
2292                 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2293                 unset($_SESSION[$var]);
2294                 return session_unregister($var);
2295         } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2296                 // Set session
2297                 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2298                 $_SESSION[$var] =  $value;
2299                 return session_register($var);
2300         } elseif (!empty($value)) {
2301                 // Update session
2302                 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2303                 $_SESSION[$var] = $value;
2304                 return true;
2305         }
2306
2307         // Ignored (but valid)
2308         //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2309         return true;
2310 }
2311
2312 // Check wether a boolean constant is set
2313 // Taken from user comments in PHP documentation for function constant()
2314 function isBooleanConstantAndTrue($constName) { // : Boolean
2315         global $cacheArray;
2316
2317         // Failed by default
2318         $res = false;
2319
2320         // In cache?
2321         if (isset($cacheArray['const'][$constName])) {
2322                 // Use cache
2323                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2324                 $res = $cacheArray['const'][$constName];
2325         } else {
2326                 // Check constant
2327                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2328                 if (defined($constName)) $res = (constant($constName) === true);
2329
2330                 // Set cache
2331                 $cacheArray['const'][$constName] = $res;
2332         }
2333         //* DEBUG: */ var_dump($res);
2334
2335         // Return value
2336         return $res;
2337 }
2338
2339 // Check wether a session variable is set
2340 function isSessionVariableSet ($var) {
2341         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2342         return (isset($_SESSION[$var]));
2343 }
2344 // Returns wether the value of the session variable or NULL if not set
2345 function get_session ($var) {
2346         global $cacheArray;
2347
2348         // Default is not found! ;-)
2349         $value = null;
2350
2351         // Is the variable there or cached values?
2352         if (isset($cacheArray['session'][$var])) {
2353                 // Get cached value (skips a lot SQL_ESCAPE() calles!
2354                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2355                 $value = $cacheArray['session'][$var];
2356         } elseif (isSessionVariableSet($var)) {
2357                 // Then  get it secured!
2358                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2359                 $value = SQL_ESCAPE($_SESSION[$var]);
2360
2361                 // Cache the value
2362                 $cacheArray['session'][$var] = $value;
2363         } // END - if
2364
2365         // Return the value
2366         return $value;
2367 }
2368 // Send notification to admin
2369 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2370         if (GET_EXT_VERSION("admins") >= "0.4.1") {
2371                 // Send new way
2372                 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2373         } else {
2374                 // Send outdated way
2375                 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2376                 SEND_ADMIN_EMAILS($subject, $msg);
2377         }
2378 }
2379 // Destroy user session
2380 function destroy_user_session () {
2381         // Remove all user data from session
2382         return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2383 }
2384 // Merges an array together but only if both are arrays
2385 function merge_array ($array1, $array2) {
2386         // Are both an array?
2387         if ((is_array($array1)) && (is_array($array2))) {
2388                 // Merge all together
2389                 return array_merge($array1, $array2);
2390         } elseif (is_array($array1)) {
2391                 // Return left array
2392                 return $array1;
2393         }
2394
2395         // Something wired happened here...
2396         print(__FUNCTION__.":<pre>");
2397         debug_print_backtrace();
2398         die("</pre>");
2399 }
2400 // Debug message logger
2401 function DEBUG_LOG ($file, $line, $message, $force=true) {
2402         // Is debug mode enabled?
2403         if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2404                 // Log this message away
2405                 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2406                 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2407                 fclose($fp);
2408         } // END - if
2409 }
2410 // Reads a directory with PHP files in and gets only files back
2411 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2412         $INCs = array();
2413
2414         // Open directory
2415         $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2416
2417         // Read all entries
2418         while ($baseFile = readdir($dirPointer)) {
2419                 // Load file only if extension is active
2420                 // Make full path
2421                 $file = $baseDir.$baseFile;
2422
2423                 // Is this a valid reset file?
2424                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2425                 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2426                         // Remove both for extension name
2427                         $extName = substr($baseFile, strlen($prefix), -4);
2428
2429                         // Try to find it
2430                         $extId = GET_EXT_ID($extName);
2431
2432                         // Is the extension valid and active?
2433                         if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2434                                 // Then add this file
2435                                 $INCs[] = $file;
2436                         } elseif ($extId == 0) {
2437                                 // Add non-extension files as well
2438                                 $INCs[] = $file;
2439                         }
2440                 } // END - if
2441         } // END - while
2442
2443         // Close directory
2444         closedir($dirPointer);
2445
2446         // Sort array
2447         asort($INCs);
2448
2449         // Return array with include files
2450         return $INCs;
2451 }
2452 // Load more reset scripts
2453 function RESET_ADD_INCLUDES () {
2454         // Is the reset set or old sql_patches?
2455         if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2456                 // Then abort here
2457                 return array();
2458         } // END - if
2459
2460         // Get more daily reset scripts
2461         $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2462
2463         // Update database
2464         if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2465
2466         // Create current week mark
2467         $currWeek = date("W", time());
2468
2469         // Has it changed?
2470         if (getConfig('last_week') != $currWeek) {
2471                 // Include weekly reset scripts
2472                 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2473
2474                 // Update config
2475                 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2476         } // END - if
2477
2478         // Create current month mark
2479         $currMonth = date("m", time());
2480
2481         // Has it changed?
2482         if (getConfig('last_month') != $currMonth) {
2483                 // Include monthly reset scripts
2484                 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2485
2486                 // Update config
2487                 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2488         } // END - if
2489
2490         // Return array
2491         return $INC_POOL;
2492 }
2493 // Handle extra values
2494 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2495         // Default is the value itself
2496         $ret = $value;
2497
2498         // Do we have a special filter function?
2499         if (!empty($filterFunction)) {
2500                 // Does the filter function exist?
2501                 if (function_exists($filterFunction)) {
2502                         // Do we have extra parameters here?
2503                         if (!empty($extraValue)) {
2504                                 // Put both parameters in one new array by default
2505                                 $args = array($value, $extraValue);
2506
2507                                 // If we have an array simply use it and pre-extend it with our value
2508                                 if (is_array($extraValue)) {
2509                                         // Make the new args array
2510                                         $args = merge_array(array($value), $extraValue);
2511                                 } // END - if
2512
2513                                 // Call the multi-parameter call-back
2514                                 $ret = call_user_func_array($filterFunction, $args);
2515                         } else {
2516                                 // One parameter call
2517                                 $ret = call_user_func($filterFunction, $value);
2518                         }
2519                 } // END - if
2520         } // END - if
2521
2522         // Return the value
2523         return $ret;
2524 }
2525 // Check if given FQFN is a readable file
2526 function FILE_READABLE($fqfn) {
2527         // Check all...
2528         return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2529 }
2530 // Converts timestamp selections into a timestamp
2531 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2532         // Init test variable
2533         $test2 = "";
2534
2535         // Get last three chars
2536         $test = substr($id, -3);
2537
2538         // Improved way of checking! :-)
2539         if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2540                 // Found a multi-selection for timings?
2541                 $test = substr($id, 0, -3);
2542                 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)) {
2543                         // Generate timestamp
2544                         $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2545                         $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2546
2547                         // Remove data from array
2548                         foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2549                                 unset($POST[$test."_".$rem]);
2550                         } // END - foreach
2551
2552                         // Skip adding
2553                         unset($id); $skip = true; $test2 = $test;
2554                 } // END - if
2555         } else {
2556                 // Process this entry
2557                 $skip = false; $test2 = "";
2558         }
2559 }
2560 // Reverts the german decimal comma into Computer decimal dot
2561 function REVERT_COMMA ($str) {
2562         // Default float is not a float... ;-)
2563         $float = false;
2564
2565         // Which language is selected?
2566         switch (GET_LANGUAGE()) {
2567                 case "de": // German language
2568                         // Remove german thousand dots first
2569                         $str = str_replace(".", "", $str);
2570
2571                         // Replace german commata with decimal dot and cast it
2572                         $float = (float)str_replace(",", ".", $str);
2573                         break;
2574
2575                 default: // US and so on
2576                         // Remove thousand dots first and cast
2577                         $float = (float)str_replace(",", "", $str);
2578                         break;
2579         }
2580
2581         // Return float
2582         return $float;
2583 }
2584 // Handle menu-depending failed logins and return the rendered content
2585 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2586         // Default output is empty ;-)
2587         $OUT = "";
2588
2589         // Is the session data set?
2590         if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2591                 // Ignore zero values
2592                 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2593                         // Non-guest has login failtures found, get both data and prepare it for template
2594                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2595                         $content = array(
2596                                 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2597                                 'last_failture'   => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2598                         );
2599
2600                         // Load template
2601                         $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2602                 } // END - if
2603
2604                 // Reset session data
2605                 set_session('mxchange_'.$accessLevel.'_failtures', "");
2606                 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2607         } // END - if
2608
2609         // Return rendered content
2610         return $OUT;
2611 }
2612 // Rebuild cache
2613 function REBUILD_CACHE ($cache, $inc="") {
2614         global $cacheInstance, $CSS;
2615
2616         // Shall I remove the cache file?
2617         if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2618                 // Rebuild cache
2619                 if ($cacheInstance->loadCacheFile($cache)) {
2620                         // Destroy it
2621                         $cacheInstance->destroyCacheFile();
2622                 } // END - if
2623
2624                 // Include file given?
2625                 if (!empty($inc)) {
2626                         // Construct FQFN
2627                         $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2628
2629                         // Is the include there?
2630                         if (FILE_READABLE($fqfn)) {
2631                                 // And rebuild it from scratch
2632                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2633                                 require($fqfn);
2634                         } else {
2635                                 // Include not found!
2636                                 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2637                         }
2638                 } // END - if
2639         } // END - if
2640 }
2641 // Purge admin menu cache
2642 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2643         global $cacheInstance;
2644
2645         // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2646         if (!EXT_IS_ACTIVE("cache")) {
2647                 // Cache extension not active
2648                 return false;
2649         } elseif (!is_object($cacheInstance)) {
2650                 // No cache instance!
2651                 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2652                 return false;
2653         } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2654                 // Caching disabled (currently experiemental!)
2655                 return false;
2656         }
2657
2658         // Experiemental feature!
2659         trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2660 }
2661 // Translates the "pool type" into human-readable
2662 function TRANSLATE_POOL_TYPE ($type) {
2663         // Default type is unknown
2664         $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2665
2666         // Generate constant
2667         $constName = sprintf("POOL_TYPE_%s", $type);
2668
2669         // Does it exist?
2670         if (defined($constName)) {
2671                 // Then use it
2672                 $translated = constant($constName);
2673         } // END - if
2674
2675         // Return "translation"
2676         return $translated;
2677 }
2678 // "Getter" for remote IP number
2679 function GET_REMOTE_ADDR () {
2680         // Get remote ip from environment
2681         $remoteAddr = getenv('REMOTE_ADDR');
2682
2683         // Is removeip installed?
2684         if (EXT_IS_ACTIVE("removeip")) {
2685                 // Then anonymize it
2686                 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2687         } // END - if
2688
2689         // Return it
2690         return $remoteAddr;
2691 }
2692 // "Getter" for remote hostname
2693 function GET_REMOTE_HOST () {
2694         // Get remote ip from environment
2695         $remoteHost = getenv('REMOTE_HOST');
2696
2697         // Is removeip installed?
2698         if (EXT_IS_ACTIVE("removeip")) {
2699                 // Then anonymize it
2700                 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2701         } // END - if
2702
2703         // Return it
2704         return $remoteHost;
2705 }
2706 // "Getter" for user agent
2707 function GET_USER_AGENT () {
2708         // Get remote ip from environment
2709         $userAgent = getenv('HTTP_USER_AGENT');
2710
2711         // Is removeip installed?
2712         if (EXT_IS_ACTIVE("removeip")) {
2713                 // Then anonymize it
2714                 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2715         } // END - if
2716
2717         // Return it
2718         return $userAgent;
2719 }
2720 // "Getter" for referer
2721 function GET_REFERER () {
2722         // Get remote ip from environment
2723         $referer = getenv('HTTP_REFERER');
2724
2725         // Is removeip installed?
2726         if (EXT_IS_ACTIVE("removeip")) {
2727                 // Then anonymize it
2728                 $referer = GET_ANONYMOUS_REFERER($referer);
2729         } // END - if
2730
2731         // Return it
2732         return $referer;
2733 }
2734
2735 // Adds a bonus mail to the queue
2736 // This is a high-level function!
2737 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2738         // Use mode from data if not set and availble ;-)
2739         if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2740
2741         // Generate receiver list
2742         $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2743
2744         // Receivers added?
2745         if (!empty($RECEIVER)) {
2746                 // Add bonus mail to queue
2747                 ADD_BONUS_MAIL_TO_QUEUE(
2748                         $data['subject'],
2749                         $data['text'],
2750                         $RECEIVER,
2751                         $data['points'],
2752                         $data['seconds'],
2753                         $data['url'],
2754                         $data['cat'],
2755                         $mode,
2756                         $data['receiver']
2757                 );
2758
2759                 // Mail inserted into bonus pool
2760                 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2761         } elseif ($output) {
2762                 // More entered than can be reached!
2763                 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2764         } else {
2765                 // Debug log
2766                 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2767         }
2768 }
2769 // Determines referal id and sets it
2770 function DETERMINE_REFID () {
2771         global $CLICK, $_SERVER;
2772
2773         // Check if refid is set
2774         if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2775                 // The variable user comes from the click-counter script click.php and we only accept this here
2776                 $GLOBALS['refid'] = bigintval($_GET['user']);
2777         } elseif (!empty($_POST['refid'])) {
2778                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2779                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2780         } elseif (!empty($_GET['refid'])) {
2781                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2782                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2783         } elseif (!empty($_GET['ref'])) {
2784                 // Set refid=ref (the referal link uses such variable)
2785                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2786         } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2787                 // Set session refid als global
2788                 $GLOBALS['refid'] = bigintval(get_session('refid'));
2789         } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2790                 // Set default refid as refid in URL
2791                 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2792         } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2793                 // Select a random user which has confirmed enougth mails
2794                 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2795         } else {
2796                 // No default ID when sql_patches is not installed or none set
2797                 $GLOBALS['refid'] = 0;
2798         }
2799
2800         // Set cookie when default refid > 0
2801         if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2802                 // Set cookie
2803                 set_session('refid', $GLOBALS['refid']);
2804         } // END - if
2805
2806         // Return determined refid
2807         return $GLOBALS['refid'];
2808 }
2809
2810 // Destroys the admin session
2811 function DESTROY_ADMIN_SESSION ($destroy = true) {
2812         // Kill maybe existing session variables including array elements
2813         set_session('admin_login', "");
2814         set_session('admin_md5'  , "");
2815         set_session('admin_last' , "");
2816         set_session('admin_to'   , "");
2817
2818         // Destroy session and return status
2819         if ($destroy) {
2820                 return @session_destroy();
2821         } // END - if
2822
2823         // All fine if we shall not really destroy the session
2824         return true;
2825 }
2826
2827 // Checks if a given apache module is loaded
2828 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2829         // Check it and return result
2830         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2831 }
2832
2833 // Getter for $_CONFIG entries
2834 function getConfig ($entry) {
2835         global $_CONFIG;
2836
2837         // Default value
2838         $value = null;
2839
2840         // Is the entry there?
2841         if (isset($_CONFIG[$entry])) {
2842                 // Then use it
2843                 $value = $_CONFIG[$entry];
2844         } // END - if
2845
2846         // Return it
2847         return $value;
2848 }
2849
2850 // @TODO Rewrite all language constants to the function getLanguage().
2851 // "Getter" for language strings
2852 function getMessage ($messageId) {
2853         // Default is not found!
2854         $return = "!".$messageId."!";
2855
2856         // Is the language string found?
2857         if (isset($GLOBALS['msg'][$messageId])) {
2858                 // Language array element found
2859                 $return = $GLOBALS['msg'][$messageId];
2860         } elseif (defined($messageId)) {
2861                 // @DEPRECATED Deprecated constant found
2862                 $return = constant($messageId);
2863         } else {
2864                 // Missing language constant
2865                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2866         }
2867
2868         // Return the string
2869         return $return;
2870 }
2871
2872 // Get current theme name
2873 function GET_CURR_THEME() {
2874         global $INC_POOL, $CSS, $cacheArray;
2875
2876         // The default theme is 'default'... ;-)
2877         $ret = "default";
2878
2879         // Load default theme if not empty from configuration
2880         if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2881
2882         if (!isSessionVariableSet('mxchange_theme')) {
2883                 // Set default theme
2884                 set_session("mxchange_theme", $ret);
2885         } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2886                 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2887                 // Get theme from cookie
2888                 $ret = get_session('mxchange_theme');
2889
2890                 // Is it valid?
2891                 if (THEME_GET_ID($ret) == 0) {
2892                         // Fix it to default
2893                         $ret = "default";
2894                 } // END - if
2895         } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2896                 // Prepare FQFN for checking
2897                 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_GET['theme']));
2898
2899                 // Installation mode active
2900                 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2901                         // Set cookie from URL data
2902                         set_session("mxchange_theme", SQL_ESCAPE($_GET['theme']));
2903                 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_POST['theme'])))) {
2904                         // Set cookie from posted data
2905                         set_session("mxchange_theme", SQL_ESCAPE($_POST['theme']));
2906                 }
2907
2908                 // Set return value
2909                 $ret = get_session('mxchange_theme');
2910         } else {
2911                 // Invalid design, reset cookie
2912                 set_session("mxchange_theme", $ret);
2913         }
2914
2915         // Add (maybe) found theme.php file to inclusion list
2916         $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($ret));
2917
2918         // Try to load the requested include file
2919         if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2920
2921         // Return theme value
2922         return $ret;
2923 }
2924
2925 // Get id from theme
2926 function THEME_GET_ID ($name) {
2927         global $cacheArray;
2928
2929         // Is the extension "theme" installed?
2930         if (!EXT_IS_ACTIVE("theme")) {
2931                 // Then abort here
2932                 return 0;
2933         } // END - if
2934
2935         // Default id
2936         $id = 0;
2937
2938         // Is the cache entry there?
2939         if (isset($cacheArray['themes']['id'][$name])) {
2940                 // Get the version from cache
2941                 $id = $cacheArray['themes']['id'][$name];
2942
2943                 // Count up
2944                 incrementConfigEntry('cache_hits');
2945         } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2946                 // Check if current theme is already imported or not
2947                 $result = SQL_QUERY_ESC("SELECT id FROM `"._MYSQL_PREFIX."_themes` WHERE theme_path='%s' LIMIT 1",
2948                         array($name), __FILE__, __LINE__);
2949
2950                 // Entry found?
2951                 if (SQL_NUMROWS($result) == 1) {
2952                         // Fetch data
2953                         list($id) = SQL_FETCHROW($result);
2954                 } // END - if
2955
2956                 // Free result
2957                 SQL_FREERESULT($result);
2958         }
2959
2960         // Return id
2961         return $id;
2962 }
2963
2964 // Increment or init with 1 the given config entry
2965 function incrementConfigEntry ($configEntry) {
2966         global $_CONFIG;
2967
2968         // Increment it if set or init it with 1
2969         if (getConfig($configEntry) > 0) { $_CONFIG[$configEntry]++; } else { $_CONFIG[$configEntry] = 1; }
2970 }
2971
2972 //////////////////////////////////////////////////
2973 //                                              //
2974 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2975 //                                              //
2976 //////////////////////////////////////////////////
2977 //
2978 if (!function_exists('html_entity_decode')) {
2979         // Taken from documentation on www.php.net
2980         function html_entity_decode ($string) {
2981                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2982                 $trans_tbl = array_flip($trans_tbl);
2983                 return strtr($string, $trans_tbl);
2984         }
2985 } // END - if
2986
2987 //
2988 ?>