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