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