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