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