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