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