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