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