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