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