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