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