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