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