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