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