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