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