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