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