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