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