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