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