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