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