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