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