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