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