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