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