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