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