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