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