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