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