98eddd5d9bea9b2ab84eac3e241ea1db7e0fe16e
[mailer.git] / inc / functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 08/25/2003 *
4  * ===============                              Last change: 11/29/2005 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : functions.php                                    *
8  * -------------------------------------------------------------------- *
9  * Short description : Many non-MySQL functions (also file access)      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12  * -------------------------------------------------------------------- *
13  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
37         require($INC);
38 }
39
40 // Check if our config file is writeable or not
41 function IS_INC_WRITEABLE ($inc) {
42         // Generate FQFN
43         $FQFN = sprintf("%sinc/%s.php", constant('PATH'), $inc);
44
45         // Abort by simple test
46         if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN))) {
47                 return false;
48         } // END - if
49
50         // Test write-access on directory
51         return is_writeable(dirname($FQFN));
52 }
53
54 // Output HTML code directly or "render" it. You addionally switch the new-line character off
55 function OUTPUT_HTML ($HTML, $newLine = true) {
56         // Some global variables
57         global $OUTPUT;
58
59         // Do we have HTML-Code here?
60         if (!empty($HTML)) {
61                 // Yes, so we handle it as you have configured
62                 switch (constant('OUTPUT_MODE'))
63                 {
64                 case "render":
65                         // That's why you don't need any \n at the end of your HTML code... :-)
66                         if (constant('_OB_CACHING') == "on") {
67                                 // Output into PHP's internal buffer
68                                 OUTPUT_RAW($HTML);
69
70                                 // That's why you don't need any \n at the end of your HTML code... :-)
71                                 if ($newLine) echo "\n";
72                         } else {
73                                 // Render mode for old or lame servers...
74                                 $OUTPUT .= $HTML;
75
76                                 // That's why you don't need any \n at the end of your HTML code... :-)
77                                 if ($newLine) $OUTPUT .= "\n";
78                         }
79                         break;
80
81                 case "direct":
82                         // If we are switching from render to direct output rendered code
83                         if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
84
85                         // The same as above... ^
86                         OUTPUT_RAW($HTML);
87                         if ($newLine) echo "\n";
88                         break;
89
90                 default:
91                         // Huh, something goes wrong or maybe you have edited config.php ???
92                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
93                         mxchange_die("<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
94                         break;
95                 }
96         } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
97                 // Headers already sent?
98                 if (headers_sent()) {
99                         // Log this error
100                         DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
101
102                         // Trigger an user error
103                         debug_report_bug("Headers are already sent!");
104                 } // END - if
105
106                 // Output cached HTML code
107                 $OUTPUT = ob_get_contents();
108
109                 // Clear output buffer for later output if output is found
110                 if (!empty($OUTPUT)) {
111                         clearOutputBuffer();
112                 } // END - if
113
114                 // Send HTTP header
115                 header("HTTP/1.1 200");
116
117                 // Used later
118                 $now = gmdate('D, d M Y H:i:s') . ' GMT';
119
120                 // General headers for no caching
121                 header("Expired: " . $now); // RFC2616 - Section 14.21
122                 header("Last-Modified: " . $now);
123                 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
124                 header("Pragma: no-cache"); // HTTP/1.0
125                 header("Connection: Close");
126
127                 // Extension "rewrite" installed?
128                 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
129                         $OUTPUT = REWRITE_LINKS($OUTPUT);
130                 } // END - if
131
132                 // Compile and run finished rendered HTML code
133                 while (strpos($OUTPUT, '{!') > 0) {
134                         // Prepare the content and eval() it...
135                         $newContent = "";
136                         $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
137                         eval($eval);
138
139                         // Was that eval okay?
140                         if (empty($newContent)) {
141                                 // Something went wrong!
142                                 mxchange_die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
143                         } // END - if
144                         $OUTPUT = $newContent;
145                 } // END - while
146
147                 // Output code here, DO NOT REMOVE! ;-)
148                 OUTPUT_RAW($OUTPUT);
149         } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
150                 // Rewrite links when rewrite extension is active
151                 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
152                         $OUTPUT = REWRITE_LINKS($OUTPUT);
153                 } // END - if
154
155                 // Compile and run finished rendered HTML code
156                 while (strpos($OUTPUT, '{!') > 0) {
157                         $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
158                         eval($eval);
159                 } // END - while
160
161                 // Output code here, DO NOT REMOVE! ;-)
162                 OUTPUT_RAW($OUTPUT);
163         }
164 }
165
166 // Output the raw HTML code
167 function OUTPUT_RAW ($HTML) {
168         // Output stripped HTML code to avoid broken JavaScript code, etc.
169         echo stripslashes(stripslashes($HTML));
170
171         // Flush the output if only constant('_OB_CACHING') is not "on"
172         if (constant('_OB_CACHING') != "on") {
173                 // Flush it
174                 flush();
175         } // END - if
176 }
177
178 // Init fatal message array
179 function initFatalMessages () {
180         $GLOBALS['fatal_messages'] = array();
181 }
182
183 // Getter for whole fatal error messages
184 function getFatalArray () {
185         return $GLOBALS['fatal_messages'];
186 }
187
188 // Add a fatal error message to the queue array
189 function addFatalMessage ($F, $L, $message, $extra="") {
190         if (is_array($extra)) {
191                 // Multiple extras for a message with masks
192                 $message = call_user_func_array('sprintf', $extra);
193         } elseif (!empty($extra)) {
194                 // $message is text with a mask plus extras to insert into the text
195                 $message = sprintf($message, $extra);
196         }
197
198         // Add message to $GLOBALS['fatal_messages']
199         $GLOBALS['fatal_messages'][] = $message;
200
201         // Log fatal messages away
202         DEBUG_LOG($F, $L, " message={$message}");
203 }
204
205 // Getter for total fatal message count
206 function getTotalFatalErrors () {
207         // Init coun
208         $count = 0;
209
210         // Do we have at least the first entry?
211         if (!empty($GLOBALS['fatal_messages'][0])) {
212                 // Get total count
213                 $count = count($GLOBALS['fatal_messages']);
214         } // END - if
215
216         // Return value
217         return $count;
218 }
219
220 // Load a template file and return it's content (only it's name; do not use ' or ")
221 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
222         // Add more variables which you want to use in your template files
223         global $DATA, $_CONFIG, $username;
224
225         // Make all template names lowercase
226         $template = strtolower($template);
227
228         // Count the template load
229         incrementConfigEntry('num_templates');
230
231         // Prepare IP number and User Agent
232         $REMOTE_ADDR     = GET_REMOTE_ADDR();
233         if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
234         $HTTP_USER_AGENT = GET_USER_AGENT();
235
236         // Init some data
237         $ret = "";
238         if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
239
240         // @DEPRECATED Try to rewrite the if() condition
241         if ($template == "member_support_form") {
242                 // Support request of a member
243                 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
244                         array($GLOBALS['userid']), __FUNCTION__, __LINE__);
245
246                 // Is content an array?
247                 if (is_array($content)) {
248                         // Merge data
249                         $content = merge_array($content, SQL_FETCHARRAY($result));
250
251                         // Translate gender
252                         $content['gender'] = TRANSLATE_GENDER($content['gender']);
253                 } else {
254                         // @DEPRECATED
255                         // @TODO Fine all templates which are using these direct variables and rewrite them.
256                         // @TODO After this step is done, this else-block is history
257                         list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
258
259                         // Translate gender
260                         $gender = TRANSLATE_GENDER($gender);
261                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
262                 }
263
264                 // Free result
265                 SQL_FREERESULT($result);
266         } // END - if
267
268         // Generate date/time string
269         $date_time = MAKE_DATETIME(time(), "1");
270
271         // Base directory
272         $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
273         $MODE = "";
274
275         // Check for admin/guest/member templates
276         if (strpos($template, "admin_") > -1) {
277                 // Admin template found
278                 $MODE = "admin/";
279         } elseif (strpos($template, "guest_") > -1) {
280                 // Guest template found
281                 $MODE = "guest/";
282         } elseif (strpos($template, "member_") > -1) {
283                 // Member template found
284                 $MODE = "member/";
285         } elseif (strpos($template, "install_") > -1) {
286                 // Installation template found
287                 $MODE = "install/";
288         } elseif (strpos($template, "ext_") > -1) {
289                 // Extension template found
290                 $MODE = "ext/";
291         } elseif (strpos($template, "la_") > -1) {
292                 // "Logical-area" template found
293                 $MODE = "la/";
294         } else {
295                 // Test for extension
296                 $test = substr($template, 0, strpos($template, "_"));
297                 if (EXT_IS_ACTIVE($test)) {
298                         // Set extra path to extension's name
299                         $MODE = $test."/";
300                 }
301         }
302
303         ////////////////////////
304         // Generate file name //
305         ////////////////////////
306         $FQFN = $BASE.$MODE.$template.".tpl";
307
308         if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
309                 // Select what depended header/footer template file for admin/guest/member area
310                 $file2 = sprintf("%s%s%s_%s.tpl",
311                         $BASE,
312                         $MODE,
313                         $template,
314                         SQL_ESCAPE($GLOBALS['what'])
315                 );
316
317                 // Probe for it...
318                 if (FILE_READABLE($file2)) $FQFN = $file2;
319
320                 // Remove variable from memory
321                 unset($file2);
322         }
323
324         // Does the special template exists?
325         if (!FILE_READABLE($FQFN)) {
326                 // Reset to default template
327                 $FQFN = $BASE.$template.".tpl";
328         } // END - if
329
330         // Now does the final template exists?
331         if (FILE_READABLE($FQFN)) {
332                 // The local file does exists so we load it. :)
333                 $tmpl_file = READ_FILE($FQFN);
334
335                 // Replace ' to our own chars to preventing them being quoted
336                 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
337
338                 // Do we have to compile the code?
339                 $ret = "";
340                 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
341                         // Okay, compile it!
342                         $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
343                         eval($tmpl_file);
344                 } else {
345                         // Simply return loaded code
346                         $ret = $tmpl_file;
347                 }
348
349                 // Add surrounding HTML comments to help finding bugs faster
350                 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
351         } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
352                 // Only admins shall see this warning or when installation mode is active
353                 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
354 (".basename($FQFN).")<br />
355 <br />
356 ".TEMPLATE_CONTENT."
357 <pre>".print_r($content, true)."</pre>
358 ".TEMPLATE_DATA."
359 <pre>".print_r($DATA, true)."</pre>
360 <br /><br />";
361         }
362
363         // Remove content and data
364         unset($content);
365         unset($DATA);
366
367         // Do we have some content to output or return?
368         if (!empty($ret)) {
369                 // Not empty so let's put it out! ;)
370                 if ($return === true) {
371                         // Return the HTML code
372                         return $ret;
373                 } else {
374                         // Output direct
375                         OUTPUT_HTML($ret);
376                 }
377         } elseif (isDebugModeEnabled()) {
378                 // Warning, empty output!
379                 return "E:".$template."<br />\n";
380         }
381 }
382
383 // Send mail out to an email address
384 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
385         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
386
387         // Compile subject line (for POINTS constant etc.)
388         $eval = "\$SUBJECT = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($SUBJECT))."\");";
389         eval($eval);
390
391         // Set from header
392         if ((!eregi("@", $TO)) && ($TO > 0)) {
393                 // Value detected, is the message extension installed?
394                 if (EXT_IS_ACTIVE("msg")) {
395                         ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
396                         return;
397                 } else {
398                         // Load email address
399                         $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FUNCTION__, __LINE__);
400                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
401
402                         // Does the user exist?
403                         if (SQL_NUMROWS($result_email)) {
404                                 // Load email address
405                                 list($TO) = SQL_FETCHROW($result_email);
406                         } else {
407                                 // Set webmaster
408                                 $TO = constant('WEBMASTER');
409                         }
410
411                         // Free result
412                         SQL_FREERESULT($result_email);
413                 }
414         } elseif ("$TO" == "0") {
415                 // Is the webmaster!
416                 $TO = constant('WEBMASTER');
417         }
418         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
419
420         // Check for PHPMailer or debug-mode
421         if (!CHECK_PHPMAILER_USAGE()) {
422                 // Not in PHPMailer-Mode
423                 if (empty($FROM)) {
424                         // Load email header template
425                         $FROM = LOAD_EMAIL_TEMPLATE("header");
426                 } else {
427                         // Append header
428                         $FROM .= LOAD_EMAIL_TEMPLATE("header");
429                 }
430         } elseif (isDebugModeEnabled()) {
431                 if (empty($FROM)) {
432                         // Load email header template
433                         $FROM = LOAD_EMAIL_TEMPLATE("header");
434                 } else {
435                         // Append header
436                         $FROM .= LOAD_EMAIL_TEMPLATE("header");
437                 }
438         }
439
440         // Compile "TO"
441         $eval = "\$TO = \"".COMPILE_CODE(smartAddSlashes($TO))."\";";
442         eval($eval);
443
444         // Compile "MSG"
445         $eval = "\$MSG = \"".COMPILE_CODE(smartAddSlashes($MSG))."\";";
446         eval($eval);
447
448         // Fix HTML parameter (default is no!)
449         if (empty($HTML)) $HTML = "N";
450         if (isDebugModeEnabled()) {
451                 // In debug mode we want to display the mail instead of sending it away so we can debug this part
452                 print("<pre>
453 ".htmlentities(trim($FROM))."
454 To      : ".$TO."
455 Subject : ".$SUBJECT."
456 Message : ".$MSG."
457 </pre>\n");
458         } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
459                 // Send mail as HTML away
460                 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
461         } elseif (!empty($TO)) {
462                 // Send Mail away
463                 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
464         } elseif ($HTML == "N") {
465                 // Problem found!
466                 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
467         }
468 }
469
470 // Check if legacy or PHPMailer command
471 // @TODO Rewrite this to an extension 'smtp'
472 // @private
473 function CHECK_PHPMAILER_USAGE() {
474         return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != "") && (constant('SMTP_USER') != ""));
475 }
476
477 /*
478  * Send out a raw email with PHPMailer class or legacy mail() command
479  */
480 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
481         // Shall we use PHPMailer class or legacy mode?
482         if (CHECK_PHPMAILER_USAGE()) {
483                 // Use PHPMailer class with SMTP enabled
484                 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
485                 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
486
487                 // get new instance
488                 $mail = new PHPMailer();
489                 $mail->PluginDir  = sprintf("%sinc/phpmailer/", constant('PATH'));
490
491                 $mail->IsSMTP();
492                 $mail->SMTPAuth   = true;
493                 $mail->Host       = constant('SMTP_HOSTNAME');
494                 $mail->Port       = 25;
495                 $mail->Username   = constant('SMTP_USER');
496                 $mail->Password   = constant('SMTP_PASSWORD');
497                 if (empty($from)) {
498                         $mail->From = constant('WEBMASTER');
499                 } else {
500                         $mail->From = $from;
501                 }
502                 $mail->FromName   = constant('MAIN_TITLE');
503                 $mail->Subject    = $subject;
504                 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
505                         $mail->Body       = $msg;
506                         $mail->AltBody    = "Your mail program required HTML support to read this mail!";
507                         $mail->WordWrap   = 70;
508                         $mail->IsHTML(true);
509                 } else {
510                         $mail->Body       = decodeEntities($msg);
511                 }
512                 $mail->AddAddress($to, "");
513                 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
514                 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
515                 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
516                 $mail->Send();
517         } else {
518                 // Use legacy mail() command
519                 @mail($to, $subject, decodeEntities($msg), $from);
520         }
521 }
522 //
523
524 // Generate a password in a specified length or use default password length
525 function GEN_PASS ($LEN = 0) {
526         // Auto-fix invalid length of zero
527         if ($LEN == 0) $LEN = getConfig('pass_len');
528
529         // Initialize array with all allowed chars
530         $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,-,+,_,/");
531
532         // Start creating password
533         $PASS = "";
534         for ($i = 0; $i < $LEN; $i++) {
535                 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
536         } // END - for
537
538         // When the size is below 40 we can also add additional security by scrambling it
539         if (strlen($PASS) <= 40) {
540                 // Also scramble the password
541                 $PASS = scrambleString($PASS);
542         } // END - if
543
544         // Return the password
545         return $PASS;
546 }
547 //
548 function MAKE_DATETIME ($time, $mode="0")
549 {
550         if ($time == 0) {
551                 // Never happend
552                 return NEVER_HAPPENED;
553         } else {
554                 // Filter out numbers
555                 $time = bigintval($time);
556         }
557
558         switch (GET_LANGUAGE())
559         {
560         case "de": // German date / time format
561                 switch ($mode) {
562                         case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
563                         case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
564                         case "2": $ret = date("d.m.Y|H:i", $time); break;
565                         case "3": $ret = date("d.m.Y", $time); break;
566                         default:
567                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
568                                 break;
569                 }
570                 break;
571
572         default:        // Default is the US date / time format!
573                 switch ($mode) {
574                         case "0": $ret = date("r", $time); break;
575                         case "1": $ret = date("Y-m-d - g:i A", $time); break;
576                         case "2": $ret = date("y-m-d|H:i", $time); break;
577                         case "3": $ret = date("y-m-d", $time); break;
578                         default:
579                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
580                                 break;
581                 }
582         }
583         return $ret;
584 }
585
586 // Translates the american decimal dot into a german comma
587 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
588         // Default is 3 you can change this in admin area "Misc -> Misc Options"
589         if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
590
591         // Use from config is default
592         $maxComma = getConfig('max_comma');
593
594         // Use from parameter?
595         if ($max > 0) $maxComma = $max;
596
597         // Cut zeros off?
598         if (($cut) && ($max == 0)) {
599                 // Test for commata if in cut-mode
600                 $com = explode(".", $dotted);
601                 if (count($com) < 2) {
602                         // Don't display commatas even if there are none... ;-)
603                         $maxComma = 0;
604                 }
605         } // END - if
606
607         // Debug log
608         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
609
610         // Translate it now
611         switch (GET_LANGUAGE()) {
612         case "de":
613                 $dotted = number_format($dotted, $maxComma, ",", ".");
614                 break;
615
616         default:
617                 $dotted = number_format($dotted, $maxComma, ".", ",");
618                 break;
619         }
620
621         // Return translated value
622         return $dotted;
623 }
624
625 //
626 function DEREFERER ($URL) {
627         // Don't de-refer our own links!
628         if (substr($URL, 0, strlen(URL)) != URL) {
629                 // De-refer this link
630                 $URL = "modules.php?module=loader&amp;url=".encodeString(compileUriCode($URL));
631         } // END - if
632
633         // Return link
634         return $URL;
635 }
636
637 // Translate Uni*-like gender to human-readable
638 function TRANSLATE_GENDER ($gender) {
639         // Default
640         $ret = "!{$gender}!";
641
642         // Male/female or company?
643         switch ($gender) {
644                 case "M": $ret = getMessage('GENDER_M'); break;
645                 case "F": $ret = getMessage('GENDER_F'); break;
646                 case "C": $ret = getMessage('GENDER_C'); break;
647                 default:
648                         // Log unknown gender
649                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
650                         break;
651         }
652
653         // Return translated gender
654         return $ret;
655 }
656
657 //
658 function FRAMETESTER ($URL) {
659         // Prepare frametester URL
660         $frametesterUrl = sprintf("%s/modules.php?module=frametester&amp;url=%s",
661                 URL,
662                 encodeString(compileUriCode($URL))
663         );
664         return $frametesterUrl;
665 }
666
667 //
668 function SELECTION_COUNT ($array) {
669         $ret = 0;
670         if (is_array($array)) {
671                 foreach ($array as $key => $selected) {
672                         if (!empty($selected)) $ret++;
673                 }
674         }
675         return $ret;
676 }
677 //
678 function IMG_CODE ($code, $type, $DATA, $uid) {
679         return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&amp;".$type."=".$DATA."&amp;mode=img&amp;code=".$code."\">";
680 }
681 //
682 function TRANSLATE_STATUS ($status) {
683         switch ($status)
684         {
685         case "UNCONFIRMED":
686         case "CONFIRMED":
687         case "LOCKED":
688                 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
689                 break;
690
691         case "":
692         case null:
693                 $ret = getMessage('ACCOUNT_DELETED');
694                 break;
695
696         default:
697                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
698                 $ret = sprintf(getMessage('UNKNOWN_STATUS"'), $status);
699                 break;
700         }
701
702         // Return it
703         return $ret;
704 }
705 //
706 function GET_LANGUAGE() {
707         // Set default return value to default language from config
708         $ret = constant('DEFAULT_LANG');
709
710         // Init variable
711         $lang = "";
712
713         // Is the variable set
714         if (REQUEST_ISSET_GET(('mx_lang'))) {
715                 // Accept only first 2 chars
716                 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
717         } elseif (isset($GLOBALS['cache_array']['language'])) {
718                 // Use cached
719                 $ret = $GLOBALS['cache_array']['language'];
720         } elseif (!empty($lang)) {
721                 // Check if main language file does exist
722                 if (FILE_READABLE(constant('PATH')."inc/language/".$lang.".php")) {
723                         // Okay found, so let's update cookies
724                         SET_LANGUAGE($lang);
725                 }
726         } elseif (!isSessionVariableSet('mx_lang')) {
727                 // Return stored value from cookie
728                 $ret = get_session('mx_lang');
729
730                 // Fixes a warning before the session has the mx_lang constant
731                 if (empty($ret)) $ret = constant('DEFAULT_LANG');
732         }
733
734         // Cache entry
735         $GLOBALS['cache_array']['language'] = $ret;
736
737         // Return value
738         return $ret;
739 }
740 //
741 function SET_LANGUAGE ($lang) {
742         // Accept only first 2 chars!
743         $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
744
745         // Set cookie
746         set_session('mx_lang', $lang);
747 }
748 //
749 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
750         global $DATA, $_CONFIG;
751
752         // Make sure all template names are lowercase!
753         $template = strtolower($template);
754
755         // Default "nickname" if extension is not installed
756         $nick = "---";
757
758         // Prepare IP number and User Agent
759         $REMOTE_ADDR     = GET_REMOTE_ADDR();
760         $HTTP_USER_AGENT = GET_USER_AGENT();
761
762         // Default admin
763         $ADMIN = constant('MAIN_TITLE');
764
765         // Is the admin logged in?
766         if (IS_ADMIN()) {
767                 // Get admin id
768                 $aid = GET_CURRENT_ADMIN_ID();
769
770                 // Load Admin data
771                 $ADMIN = GET_ADMIN_EMAIL($aid);
772         } // END - if
773
774         // Neutral email address is default
775         $email = constant('WEBMASTER');
776
777         // Expiration in a nice output format
778         if (getConfig('auto_purge') == 0) {
779                 // Will never expire!
780                 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
781         } else {
782                 // Create nice date string
783                 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
784         }
785
786         // Is content an array?
787         if (is_array($content)) {
788                 // Add expiration to array, $EXPIRATION is now deprecated!
789                 $content['expiration'] = $EXPIRATION;
790         } // END - if
791
792         // Load user's data
793         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
794         if (($UID > 0) && (is_array($content))) {
795                 // If nickname extension is installed, fetch nickname as well
796                 if (EXT_IS_ACTIVE("nickname")) {
797                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
798                         // Load nickname
799                         $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
800                                 array(bigintval($UID)), __FUNCTION__, __LINE__);
801                 } else {
802                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
803                         /// Load normal data
804                         $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
805                                 array(bigintval($UID)), __FUNCTION__, __LINE__);
806                 }
807
808                 // Fetch and merge data
809                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
810                 $content = merge_array($content, SQL_FETCHARRAY($result));
811                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
812
813                 // Free result
814                 SQL_FREERESULT($result);
815         } // END - if
816
817         // Translate M to male or F to female if present
818         if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
819
820         // Overwrite email from data if present
821         if (isset($content['email'])) $email = $content['email'];
822
823         // Store email for some functions in global data array
824         $DATA['email'] = $email;
825
826         // Base directory
827         $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
828
829         // Check for admin/guest/member templates
830         if (strpos($template, "admin_") > -1) {
831                 // Admin template found
832                 $FQFN = $BASE."admin/".$template.".tpl";
833         } elseif (strpos($template, "guest_") > -1) {
834                 // Guest template found
835                 $FQFN = $BASE."guest/".$template.".tpl";
836         } elseif (strpos($template, "member_") > -1) {
837                 // Member template found
838                 $FQFN = $BASE."member/".$template.".tpl";
839         } else {
840                 // Test for extension
841                 $test = substr($template, 0, strpos($template, "_"));
842                 if (EXT_IS_ACTIVE($test)) {
843                         // Set extra path to extension's name
844                         $FQFN = $BASE.$test."/".$template.".tpl";
845                 } else {
846                         // No special filename
847                         $FQFN = $BASE.$template.".tpl";
848                 }
849         }
850
851         // Does the special template exists?
852         if (!FILE_READABLE($FQFN)) {
853                 // Reset to default template
854                 $FQFN = $BASE.$template.".tpl";
855         } // END - if
856
857         // Now does the final template exists?
858         $newContent = "";
859         if (FILE_READABLE($FQFN)) {
860                 // The local file does exists so we load it. :)
861                 $tmpl_file = READ_FILE($FQFN);
862                 $tmpl_file = SQL_ESCAPE($tmpl_file);
863
864                 // Run code
865                 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
866                 eval($tmpl_file);
867         } elseif (!empty($template)) {
868                 // Template file not found!
869                 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
870 {--TEMPLATE_CONTENT--}
871 <pre>".print_r($content, true)."</pre>
872 {--TEMPLATE_DATA--}
873 <pre>".print_r($DATA, true)."</pre>
874 <br /><br />";
875
876                 // Debug mode not active? Then remove the HTML tags
877                 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
878         } else {
879                 // No template name supplied!
880                 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
881         }
882
883         // Is there some content?
884         if (empty($newContent)) {
885                 // Compiling failed
886                 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
887                 // Add last error if the required function exists
888                 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
889         } // END - if
890
891         // Remove content and data
892         unset($content);
893         unset($DATA);
894
895         // Return compiled content
896         return COMPILE_CODE($newContent);
897 }
898 //
899 function MAKE_TIME ($H, $M, $S, $stamp) {
900         // Extract day, month and year from given timestamp
901         $DAY   = date("d", $stamp);
902         $MONTH = date("m", $stamp);
903         $YEAR  = date('Y', $stamp);
904
905         // Create timestamp for wished time which depends on extracted date
906         return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
907 }
908 //
909 function LOAD_URL ($URL, $addUrlData=true) {
910         // Compile out URI codes
911         $URL = compileUriCode($URL);
912
913         // Check if http(s):// is there
914         if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
915                 // Make all URLs full-qualified
916                 $URL = "".$URL;
917         }
918
919         // Get output buffer
920         //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
921         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
922         $OUTPUT = ob_get_contents();
923
924         // Clear it only if there is content
925         if (!empty($OUTPUT)) {
926                 clearOutputBuffer();
927         } // END - if
928
929         // Add some data to URL if cookies are not accepted
930         if (((!defined('__COOKIES')) || (!constant('__COOKIES'))) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
931
932         // Probe for bot from search engine
933         if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
934                 // Search engine bot detected so let's rewrite many chars for the link
935                 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
936
937                 // Output new location link as anchor
938                 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
939         } elseif (!headers_sent()) {
940                 // Load URL when headers are not sent
941                 //* DEBUG: */ debug_report_bug("URL={$URL}");
942                 header ("Location: ".str_replace("&amp;", "&", $URL));
943         } else {
944                 // Output error message
945                 LOAD_INC("inc/header.php");
946                 LOAD_TEMPLATE("redirect_url", false, str_replace("&amp;", "&", $URL));
947                 LOAD_INC("inc/footer.php");
948         }
949         exit;
950 }
951
952 // Wrapper for LOAD_URL but URL comes from a configuration entry
953 function LOAD_CONFIGURED_URL ($configEntry) {
954         // Get the URL
955         $URL = getConfig($configEntry);
956
957         // Is this URL set?
958         if (is_null($URL)) {
959                 // Then abort here
960                 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
961         } // END - if
962
963         // Load the URL
964         LOAD_URL($URL);
965 }
966
967 //
968 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
969         // Is the code a string?
970         if (!is_string($code)) {
971                 // Silently return it
972                 return $code;
973         } // END - if
974
975         $ARRAY = $GLOBALS['security_chars'];
976
977         // Select smaller set of chars to replace when we e.g. want to compile URLs
978         if (!$full) $ARRAY = $GLOBALS['url_chars'];
979
980         // Compile constants
981         if ($constants) {
982                 // BEFORE 0.2.1 : Language and data constants
983                 // WITH 0.2.1+  : Only language constants
984                 $code = str_replace('{--','".', str_replace('--}','."', $code));
985
986                 // BEFORE 0.2.1 : Not used
987                 // WITH 0.2.1+  : Data constants
988                 $code = str_replace('{!','".', str_replace("!}", '."', $code));
989         } // END - if
990
991         // Compile QUOT and other non-HTML codes
992         foreach ($ARRAY['to'] as $k => $to) {
993                 // Do the reversed thing as in inc/libs/security_functions.php
994                 $code = str_replace($to, $ARRAY['from'][$k], $code);
995         } // END - foreach
996
997         // But shall I keep simple quotes for later use?
998         if ($simple) $code = str_replace("'", '{QUOT}', $code);
999
1000         // Find $content[bla][blub] entries
1001         @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1002
1003         // Are some matches found?
1004         if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1005                 // Replace all matches
1006                 $matchesFound = array();
1007                 foreach ($matches[0] as $key => $match) {
1008                         // Fuzzy look has failed by default
1009                         $fuzzyFound = false;
1010
1011                         // Fuzzy look on match if already found
1012                         foreach ($matchesFound as $found => $set) {
1013                                 // Get test part
1014                                 $test = substr($found, 0, strlen($match));
1015
1016                                 // Does this entry exist?
1017                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1018                                 if ($test == $match) {
1019                                         // Match found!
1020                                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1021                                         $fuzzyFound = true;
1022                                         break;
1023                                 } // END - if
1024                         } // END - foreach
1025
1026                         // Skip this entry?
1027                         if ($fuzzyFound) continue;
1028
1029                         // Take all string elements
1030                         if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1031                                 // Replace it in the code
1032                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1033                                 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1034                                 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1035                                 $matchesFound[$key."_".$matches[4][$key]] = 1;
1036                                 $matchesFound[$match] = 1;
1037                         } elseif (!isset($matchesFound[$match])) {
1038                                 // Not yet replaced!
1039                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1040                                 $code = str_replace($match, "\".".$match.".\"", $code);
1041                                 $matchesFound[$match] = 1;
1042                         }
1043                 } // END - foreach
1044         } // END - if
1045
1046         // Return compiled code
1047         return $code;
1048 }
1049 //
1050 /************************************************************************
1051  *                                                                      *
1052  * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!)       *
1053  * $a_sort sortiert:                                                    *
1054  *                                                                      *
1055  * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1056  * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben    *
1057  * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird   *
1058  * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a             *
1059  * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren   *
1060  *                                                                      *
1061  * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array    *
1062  * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1063  * Sie, dass es doch nicht so schwer ist! :-)                           *
1064  *                                                                      *
1065  ************************************************************************/
1066 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1067         $dummy = $array;
1068         while ($primary_key < count($a_sort)) {
1069                 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1070                         foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1071                                 $match = false;
1072                                 if (!$nums) {
1073                                         // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1074                                         if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1075                                 } elseif ($key != $key2) {
1076                                         // Sort numbers (E.g.: 9 < 10)
1077                                         if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1078                                         if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1))  $match = true;
1079                                 }
1080
1081                                 if ($match) {
1082                                         // We have found two different values, so let's sort whole array
1083                                         foreach ($dummy as $sort_key => $sort_val) {
1084                                                 $t                       = $dummy[$sort_key][$key];
1085                                                 $dummy[$sort_key][$key]  = $dummy[$sort_key][$key2];
1086                                                 $dummy[$sort_key][$key2] = $t;
1087                                                 unset($t);
1088                                         } // END - foreach
1089                                 } // END - if
1090                         } // END - foreach
1091                 } // END - foreach
1092
1093                 // Count one up
1094                 $primary_key++;
1095         } // END - while
1096
1097         // Write back sorted array
1098         $array = $dummy;
1099 }
1100
1101 //
1102 function ADD_SELECTION ($type, $DEFAULT, $prefix="", $id="0") {
1103         $OUT = "";
1104
1105         if ($type == "yn") {
1106                 // This is a yes/no selection only!
1107                 if ($id > 0) $prefix .= "[".$id."]";
1108                 $OUT .= "    <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1109         } else {
1110                 // Begin with regular selection box here
1111                 if (!empty($prefix)) $prefix .= "_";
1112                 $type2 = $type;
1113                 if ($id > 0) $type2 .= "[".$id."]";
1114                 $OUT .= "    <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1115         }
1116
1117         switch ($type) {
1118         case "day": // Day
1119                 for ($idx = 1; $idx < 32; $idx++) {
1120                         $OUT .= "<option value=\"".$idx."\"";
1121                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1122                         $OUT .= ">".$idx."</option>\n";
1123                 } // END - for
1124                 break;
1125
1126         case "month": // Month
1127                 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1128                         $OUT .= "<option value=\"".$month."\"";
1129                         if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1130                         $OUT .= ">".$descr."</option>\n";
1131                 } // END - for
1132                 break;
1133
1134         case "year": // Year
1135                 // Get current year
1136                 $YEAR = date('Y', time());
1137
1138                 // Use configured min age or fixed?
1139                 if (GET_EXT_VERSION("other") >= "0.2.1") {
1140                         // Configured
1141                         $startYear = $YEAR - getConfig('min_age');
1142                 } else {
1143                         // Fixed 16 years
1144                         $startYear = $YEAR - 16;
1145                 }
1146
1147                 // Calculate earliest year (100 years old people can still enter Internet???)
1148                 $minYear = $YEAR - 100;
1149
1150                 // Check if the default value is larger than minimum and bigger than actual year
1151                 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1152                         for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1153                                 $OUT .= "<option value=\"".$idx."\"";
1154                                 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1155                                 $OUT .= ">".$idx."</option>\n";
1156                         } // END - for
1157                 } elseif ($DEFAULT == -1) {
1158                         // Current year minus 1
1159                         for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1160                         {
1161                                 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1162                         }
1163                 } else {
1164                         // Get current year and subtract the configured minimum age
1165                         $OUT .= "<option value=\"".($minYear - 1)."\">&lt;".$minYear."</option>\n";
1166                         // Calculate earliest year depending on extension version
1167                         if (GET_EXT_VERSION("other") >= "0.2.1") {
1168                                 // Use configured minimum age
1169                                 $YEAR = date('Y', time()) - getConfig('min_age');
1170                         } else {
1171                                 // Use fixed 16 years age
1172                                 $YEAR = date('Y', time()) - 16;
1173                         }
1174
1175                         // Construct year selection list
1176                         for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1177                                 $OUT .= "<option value=\"".$idx."\"";
1178                                 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1179                                 $OUT .= ">".$idx."</option>\n";
1180                         } // END - for
1181                 }
1182                 break;
1183
1184         case "sec":
1185         case "min":
1186                 for ($idx = 0; $idx < 60; $idx+=5) {
1187                         if (strlen($idx) == 1) $idx = "0".$idx;
1188                         $OUT .= "<option value=\"".$idx."\"";
1189                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1190                         $OUT .= ">".$idx."</option>\n";
1191                 } // END - for
1192                 break;
1193
1194         case "hour":
1195                 for ($idx = 0; $idx < 24; $idx++) {
1196                         if (strlen($idx) == 1) $idx = "0".$idx;
1197                         $OUT .= "<option value=\"".$idx."\"";
1198                         if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1199                         $OUT .= ">".$idx."</option>\n";
1200                 } // END - for
1201                 break;
1202
1203         case "yn":
1204                 $OUT .= "<option value=\"Y\"";
1205                 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1206                 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1207                 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1208                 $OUT .= ">{--NO--}</option>\n";
1209                 break;
1210         }
1211         $OUT .= "    </select>\n";
1212         return $OUT;
1213 }
1214
1215 //
1216 function TRANSLATE_YESNO ($yn) {
1217         // Default
1218         $translated = "??? (".$yn.")";
1219         switch ($yn) {
1220                 case "Y": $translated = getMessage('YES'); break;
1221                 case "N": $translated = getMessage('NO'); break;
1222                 default:
1223                         // Log unknown value
1224                         DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
1225                         break;
1226         }
1227
1228         // Return it
1229         return $translated;
1230 }
1231
1232 //
1233 // Deprecated : $length
1234 // Optional   : $DATA
1235 //
1236 function generateRandomCodde ($length, $code, $uid, $DATA="") {
1237         // Fix missing _MAX constant
1238         // @TODO Rewrite this unnice code
1239         if (!defined('_MAX')) define('_MAX', 15235);
1240
1241         // Build server string
1242         $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
1243
1244         // Build key string
1245         $keys   = constant('SITE_KEY').":".constant('DATE_KEY');
1246         if (isConfigEntrySet('secret_key'))  $keys .= ":".getConfig('secret_key');
1247         if (isConfigEntrySet('file_hash'))   $keys .= ":".getConfig('file_hash');
1248         $keys .= ":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1249         if (isConfigEntrySet('master_salt')) $keys .= ":".getConfig('master_salt');
1250
1251         // Build string from misc data
1252         $data   = $code.":".$uid.":".$DATA;
1253
1254         // Add more additional data
1255         if (isSessionVariableSet('u_hash'))                     $data .= ":".get_session('u_hash');
1256         if (isset($GLOBALS['userid']))                          $data .= ":".$GLOBALS['userid'];
1257         if (isSessionVariableSet('mxchange_theme'))             $data .= ":".get_session('mxchange_theme');
1258         if (isSessionVariableSet('mx_lang'))                    $data .= ":".GET_LANGUAGE();
1259         if (isset($GLOBALS['refid']))                                   $data .= ":".$GLOBALS['refid'];
1260
1261         // Calculate number for generating the code
1262         $a = $code + constant('_ADD') - 1;
1263
1264         if (isConfigEntrySet('master_hash')) {
1265                 // Generate hash with master salt from modula of number with the prime number and other data
1266                 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1267
1268                 // Create number from hash
1269                 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1270         } else {
1271                 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1272                 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1273
1274                 // Create number from hash
1275                 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1276         }
1277
1278         // At least 10 numbers shall be secure enought!
1279         $len = getConfig('code_length');
1280         if ($len == 0) $len = $length;
1281         if ($len == 0) $len = 10;
1282
1283         // Cut off requested counts of number
1284         $return = substr(str_replace('.', "", $rcode), 0, $len);
1285
1286         // Done building code
1287         return $return;
1288 }
1289
1290 // Does only allow numbers
1291 function bigintval ($num, $castValue = true) {
1292         // Filter all numbers out
1293         $ret = preg_replace("/[^0123456789]/", "", $num);
1294
1295         // Shall we cast?
1296         if ($castValue) $ret = (double)$ret;
1297
1298         // Has the whole value changed?
1299         // @TODO Remove this if() block if all is working fine
1300         if ("".$ret."" != "".$num."") {
1301                 // Log the values
1302                 debug_report_bug("{$ret}<>{$num}");
1303         } // END - if
1304
1305         // Return result
1306         return $ret;
1307 }
1308
1309 // Insert the code in $img_code into jpeg or PNG image
1310 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1311         if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1312                 // Stop execution of function here because of over-sized code length
1313                 return;
1314         } elseif (!$headerSent) {
1315                 // Return in an HTML code code
1316                 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1317         }
1318
1319         // Load image
1320         $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1321         if (FILE_READABLE($img)) {
1322                 // Switch image type
1323                 switch (getConfig('img_type'))
1324                 {
1325                 case "jpg":
1326                         // Okay, load image and hide all errors
1327                         $image = @imagecreatefromjpeg($img);
1328                         break;
1329
1330                 case "png":
1331                         // Okay, load image and hide all errors
1332                         $image = @imagecreatefrompng($img);
1333                         break;
1334                 }
1335         } else {
1336                 // Exit function here
1337                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1338                 return;
1339         }
1340
1341         // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1342         $text_color = imagecolorallocate($image, 0, 0, 0);
1343
1344         // Insert code into image
1345         imagestring($image, 5, 14, 2, $img_code, $text_color);
1346
1347         // Return to browser
1348         header ("Content-Type: image/".getConfig('img_type'));
1349
1350         // Output image with matching image factory
1351         switch (getConfig('img_type')) {
1352                 case "jpg": imagejpeg($image); break;
1353                 case "png": imagepng($image);  break;
1354         }
1355
1356         // Remove image from memory
1357         imagedestroy($image);
1358 }
1359 // Create selection box or array of splitted timestamp
1360 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1361         // Calculate 2-seconds timestamp
1362         $stamp = round($timestamp);
1363         //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1364
1365         // Do we have a leap year?
1366         $SWITCH = 0;
1367         $TEST = date('Y', time()) / 4;
1368         $M1 = date("m", time());
1369         $M2 = date("m", (time() + $timestamp));
1370
1371         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1372         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02"))  $SWITCH = getConfig('one_day');
1373
1374         // First of all years...
1375         $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1376         //* DEBUG: */ print("Y={$Y}<br />\n");
1377         // Next months...
1378         $M = abs(floor($timestamp / 2628000 - $Y * 12));
1379         //* DEBUG: */ print("M={$M}<br />\n");
1380         // Next weeks
1381         $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1382         //* DEBUG: */ print("W={$W}<br />\n");
1383         // Next days...
1384         $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1385         //* DEBUG: */ print("D={$D}<br />\n");
1386         // Next hours...
1387         $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
1388         //* DEBUG: */ print("h={$h}<br />\n");
1389         // Next minutes..
1390         $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1391         //* DEBUG: */ print("m={$m}<br />\n");
1392         // And at last seconds...
1393         $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1394         //* DEBUG: */ print("s={$s}<br />\n");
1395
1396         // Is seconds zero and time is < 60 seconds?
1397         if (($s == 0) && ($timestamp < 60)) {
1398                 // Fix seconds
1399                 $s = round($timestamp);
1400         } // END - if
1401
1402         //
1403         // Now we convert them in seconds...
1404         //
1405         if ($return_array) {
1406                 // Just put all data in an array for later use
1407                 $OUT = array(
1408                         'YEARS'   => $Y,
1409                         'MONTHS'  => $M,
1410                         'WEEKS'   => $W,
1411                         'DAYS'    => $D,
1412                         'HOURS'   => $h,
1413                         'MINUTES' => $m,
1414                         'SECONDS' => $s
1415                 );
1416         } else {
1417                 // Generate table
1418                 $OUT  = "<div align=\"".$align."\">\n";
1419                 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1420                 $OUT .= "<tr>\n";
1421
1422                 if (ereg('Y', $display) || (empty($display))) {
1423                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1424                 }
1425
1426                 if (ereg("M", $display) || (empty($display))) {
1427                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1428                 }
1429
1430                 if (ereg("W", $display) || (empty($display))) {
1431                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1432                 }
1433
1434                 if (ereg("D", $display) || (empty($display))) {
1435                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1436                 }
1437
1438                 if (ereg("h", $display) || (empty($display))) {
1439                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1440                 }
1441
1442                 if (ereg("m", $display) || (empty($display))) {
1443                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1444                 }
1445
1446                 if (ereg("s", $display) || (empty($display))) {
1447                         $OUT .= "  <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1448                 }
1449
1450                 $OUT .= "</tr>\n";
1451                 $OUT .= "<tr>\n";
1452
1453                 if (ereg('Y', $display) || (empty($display))) {
1454                         // Generate year selection
1455                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1456                         for ($idx = 0; $idx <= 10; $idx++) {
1457                                 $OUT .= "    <option class=\"mini_select\" value=\"".$idx."\"";
1458                                 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1459                                 $OUT .= ">".$idx."</option>\n";
1460                         }
1461                         $OUT .= "  </select></td>\n";
1462                 } else {
1463                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1464                 }
1465
1466                 if (ereg("M", $display) || (empty($display))) {
1467                         // Generate month selection
1468                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1469                         for ($idx = 0; $idx <= 11; $idx++)
1470                         {
1471                                         $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1472                                 if ($idx == $M) $OUT .= " selected=\"selected\"";
1473                                 $OUT .= ">".$idx."</option>\n";
1474                         }
1475                         $OUT .= "  </select></td>\n";
1476                 } else {
1477                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1478                 }
1479
1480                 if (ereg("W", $display) || (empty($display))) {
1481                         // Generate week selection
1482                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1483                         for ($idx = 0; $idx <= 4; $idx++) {
1484                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1485                                 if ($idx == $W) $OUT .= " selected=\"selected\"";
1486                                 $OUT .= ">".$idx."</option>\n";
1487                         }
1488                         $OUT .= "  </select></td>\n";
1489                 } else {
1490                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1491                 }
1492
1493                 if (ereg("D", $display) || (empty($display))) {
1494                         // Generate day selection
1495                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1496                         for ($idx = 0; $idx <= 31; $idx++) {
1497                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1498                                 if ($idx == $D) $OUT .= " selected=\"selected\"";
1499                                 $OUT .= ">".$idx."</option>\n";
1500                         }
1501                         $OUT .= "  </select></td>\n";
1502                 } else {
1503                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1504                 }
1505
1506                 if (ereg("h", $display) || (empty($display))) {
1507                         // Generate hour selection
1508                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1509                         for ($idx = 0; $idx <= 23; $idx++)      {
1510                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1511                                 if ($idx == $h) $OUT .= " selected=\"selected\"";
1512                                 $OUT .= ">".$idx."</option>\n";
1513                         }
1514                         $OUT .= "  </select></td>\n";
1515                 } else {
1516                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1517                 }
1518
1519                 if (ereg("m", $display) || (empty($display))) {
1520                         // Generate minute selection
1521                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1522                         for ($idx = 0; $idx <= 59; $idx++) {
1523                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1524                                 if ($idx == $m) $OUT .= " selected=\"selected\"";
1525                                 $OUT .= ">".$idx."</option>\n";
1526                         }
1527                         $OUT .= "  </select></td>\n";
1528                 } else {
1529                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1530                 }
1531
1532                 if (ereg("s", $display) || (empty($display))) {
1533                         // Generate second selection
1534                         $OUT .= "  <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1535                         for ($idx = 0; $idx <= 59; $idx++) {
1536                                 $OUT .= "  <option class=\"mini_select\" value=\"".$idx."\"";
1537                                 if ($idx == $s) $OUT .= " selected=\"selected\"";
1538                                 $OUT .= ">".$idx."</option>\n";
1539                         }
1540                         $OUT .= "  </select></td>\n";
1541                 } else {
1542                         $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1543                 }
1544                 $OUT .= "</tr>\n";
1545                 $OUT .= "</table>\n";
1546                 $OUT .= "</div>\n";
1547                 // Return generated HTML code
1548         }
1549         return $OUT;
1550 }
1551
1552 //
1553 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1554         // Initial return value
1555         $ret = 0;
1556
1557         // Do we have a leap year?
1558         $SWITCH = 0;
1559         $TEST = date('Y', time()) / 4;
1560         $M1   = date("m", time());
1561         // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1562         if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02"))  $SWITCH = getConfig('one_day');
1563         // First add years...
1564         $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1565         // Next months...
1566         $ret += $POST[$prefix."_mo"] * 2628000;
1567         // Next weeks
1568         $ret += $POST[$prefix."_we"] * 604800;
1569         // Next days...
1570         $ret += $POST[$prefix."_da"] * 86400;
1571         // Next hours...
1572         $ret += $POST[$prefix."_ho"] * 3600;
1573         // Next minutes..
1574         $ret += $POST[$prefix."_mi"] * 60;
1575         // And at last seconds...
1576         $ret += $POST[$prefix."_se"];
1577         // Return calculated value
1578         return $ret;
1579 }
1580
1581 // Sends out mail to all administrators
1582 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1583 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1584         // Trim template name
1585         $template = trim($template);
1586
1587         // Load email template
1588         $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1589
1590         // Check which admin shall receive this mail
1591         $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1592                 array($template), __FUNCTION__, __LINE__);
1593         if (SQL_NUMROWS($result) == 0) {
1594                 // Create new entry (to all admins)
1595                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1596                         array($template), __FUNCTION__, __LINE__);
1597         } else {
1598                 // Load admin IDs...
1599                 // @TODO This can be, somehow, rewritten
1600                 $adminIds = array();
1601                 while ($content = SQL_FETCHARRAY($result)) {
1602                         $adminIds[] = $content['admin_id'];
1603                 } // END - while
1604
1605                 // Free memory
1606                 SQL_FREERESULT($result);
1607
1608                 // Init result
1609                 $result = false;
1610
1611                 // "implode" IDs and query string
1612                 $aid = implode(",", $adminIds);
1613                 if ($aid == "-1") {
1614                         if (EXT_IS_ACTIVE("events")) {
1615                                 // Add line to user events
1616                                 EVENTS_ADD_LINE($subj, $msg, $UID);
1617                         } else {
1618                                 // Log error for debug
1619                                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1620                                         $template,
1621                                         $subj,
1622                                         $UID
1623                                 ));
1624                         }
1625                 } elseif ($aid == "0") {
1626                         // Select all email adresses
1627                         $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1628                                 __FUNCTION__, __LINE__);
1629                 } else {
1630                         // If Admin-ID is not "to-all" select
1631                         $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1632                                 array($aid), __FUNCTION__, __LINE__);
1633                 }
1634         }
1635
1636         // Load email addresses and send away
1637         while ($content = SQL_FETCHARRAY($result)) {
1638                 SEND_EMAIL($content['email'], $subj, $msg);
1639         } // END - while
1640
1641         // Free memory
1642         SQL_FREERESULT($result);
1643 }
1644
1645 //
1646 function CREATE_FANCY_TIME ($stamp) {
1647         // Get data array with years/months/weeks/days/...
1648         $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1649         $ret = "";
1650         foreach($data as $k => $v) {
1651                 if ($v > 0) {
1652                         // Value is greater than 0 "eval" data to return string
1653                         $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1654                         eval($eval);
1655                         break;
1656                 } // END - if
1657         } // END - foreach
1658
1659         // Do we have something there?
1660         if (strlen($ret) > 0) {
1661                 // Remove leading commata and space
1662                 $ret = substr($ret, 2);
1663         } else {
1664                 // Zero seconds
1665                 $ret = "0 {--_SECONDS--}";
1666         }
1667
1668         // Return fancy time string
1669         return $ret;
1670 }
1671
1672 //
1673 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1674         $SEP = ""; $TOP = "";
1675         if (!$show_form) {
1676                 $TOP = " top2";
1677                 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\">&nbsp;</td></tr>";
1678         }
1679
1680         $NAV = "";
1681         for ($page = 1; $page <= $PAGES; $page++) {
1682                 // Is the page currently selected or shall we generate a link to it?
1683                 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1684                         // Is currently selected, so only highlight it
1685                         $NAV .= "<strong>-";
1686                 } else {
1687                         // Open anchor tag and add base URL
1688                         $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$GLOBALS['what']."&amp;page=".$page."&amp;offset=".$offset;
1689
1690                         // Add userid when we shall show all mails from a single member
1691                         if ((REQUEST_ISSET_GET(('uid'))) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&amp;uid=".bigintval(REQUEST_GET('uid'));
1692
1693                         // Close open anchor tag
1694                         $NAV .= "\">";
1695                 }
1696                 $NAV .= $page;
1697                 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1698                         // Is currently selected, so only highlight it
1699                         $NAV .= "-</strong>";
1700                 } else {
1701                         // Close anchor tag
1702                         $NAV .= "</a>";
1703                 }
1704
1705                 // Add seperator if we have not yet reached total pages
1706                 if ($page < $PAGES) $NAV .= "&nbsp;|&nbsp;";
1707         }
1708
1709         // Define constants only once
1710         if (!defined('__NAV_OUTPUT')) {
1711                 define('__NAV_OUTPUT' , $NAV);
1712                 define('__NAV_COLSPAN', $colspan);
1713                 define('__NAV_TOP'    , $TOP);
1714                 define('__NAV_SEP'    , $SEP);
1715         }
1716
1717         // Load navigation template
1718         $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1719
1720         if ($return === true) {
1721                 // Return generated HTML-Code
1722                 return $OUT;
1723         } else {
1724                 // Output HTML-Code
1725                 OUTPUT_HTML($OUT);
1726         }
1727 }
1728
1729 // Extract host from script name
1730 function EXTRACT_HOST (&$script) {
1731         // Use default SERVER_URL by default... ;) So?
1732         $url = constant('SERVER_URL');
1733
1734         // Is this URL valid?
1735         if (substr($script, 0, 7) == "http://") {
1736                 // Use the hostname from script URL as new hostname
1737                 $url = substr($script, 7);
1738                 $extract = explode("/", $url);
1739                 $url = $extract[0];
1740                 // Done extracting the URL :)
1741         } // END - if
1742
1743         // Extract host name
1744         $host = str_replace("http://", "", $url);
1745         if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1746
1747         // Generate relative URL
1748         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1749         if (substr(strtolower($script), 0, 7) == "http://") {
1750                 // But only if http:// is in front!
1751                 $script = substr($script, (strlen($url) + 7));
1752         } elseif (substr(strtolower($script), 0, 8) == "https://") {
1753                 // Does this work?!
1754                 $script = substr($script, (strlen($url) + 8));
1755         }
1756
1757         //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1758         if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1759
1760         // Return host name
1761         return $host;
1762 }
1763
1764 // Send a GET request
1765 function GET_URL ($script) {
1766         // Compile the script name
1767         $script = COMPILE_CODE($script);
1768
1769         // Extract host name from script
1770         $host = EXTRACT_HOST($script);
1771
1772         // Generate GET request header
1773         $request  = "GET /" . trim($script) . " HTTP/1.1\r\n";
1774         $request .= "Host: " . $host . "\r\n";
1775         $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1776         $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1777         $request .= "Content-Type: text/plain\r\n";
1778         $request .= "Cache-Control: no-cache\r\n";
1779         $request .= "Connection: Close\r\n\r\n";
1780
1781         // Send the raw request
1782         $response = SEND_RAW_REQUEST($host, $request);
1783
1784         // Return the result to the caller function
1785         return $response;
1786 }
1787
1788 // Send a POST request
1789 function POST_URL ($script, $postData) {
1790         // Is postData an array?
1791         if (!is_array($postData)) {
1792                 // Abort here
1793                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1794                 return array("", "", "");
1795         } // END - if
1796
1797         // Compile the script name
1798         $script = COMPILE_CODE($script);
1799
1800         // Extract host name from script
1801         $host = EXTRACT_HOST($script);
1802
1803         // Construct request
1804         $data = http_build_query($postData, '','&');
1805
1806         // Generate POST request header
1807         $request  = "POST /" . trim($script) . " HTTP/1.1\r\n";
1808         $request .= "Host: " . $host . "\r\n";
1809         $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1810         $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1811         $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1812         $request .= "Content-length: " . strlen($data) . "\r\n";
1813         $request .= "Cache-Control: no-cache\r\n";
1814         $request .= "Connection: Close\r\n\r\n";
1815         $request .= $data;
1816
1817         // Send the raw request
1818         $response = SEND_RAW_REQUEST($host, $request);
1819
1820         // Return the result to the caller function
1821         return $response;
1822 }
1823
1824 // Sends a raw request to another host
1825 function SEND_RAW_REQUEST ($host, $request) {
1826         // Initialize array
1827         $response = array("", "", "");
1828
1829         // Default is not to use proxy
1830         $useProxy = false;
1831
1832         // Are proxy settins set?
1833         if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1834                 // Then use it
1835                 $useProxy = true;
1836         } // END - if
1837
1838         // Open connection
1839         //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1840         if ($useProxy) {
1841                 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1842         } else {
1843                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1844         }
1845
1846         // Is there a link?
1847         if (!is_resource($fp)) {
1848                 // Failed!
1849                 return $response;
1850         } // END - if
1851
1852         // Do we use proxy?
1853         if ($useProxy) {
1854                 // Generate CONNECT request header
1855                 $proxyTunnel  = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1856                 $proxyTunnel .= "Host: ".$host."\r\n";
1857
1858                 // Use login data to proxy? (username at least!)
1859                 if (getConfig('proxy_username') != "") {
1860                         // Add it as well
1861                         $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1862                         $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1863                 } // END - if
1864
1865                 // Add last new-line
1866                 $proxyTunnel .= "\r\n";
1867                 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1868
1869                 // Write request
1870                 fputs($fp, $proxyTunnel);
1871
1872                 // Got response?
1873                 if (feof($fp)) {
1874                         // No response received
1875                         return $response;
1876                 } // END - if
1877
1878                 // Read the first line
1879                 $resp = trim(fgets($fp, 10240));
1880                 $respArray = explode(" ", $resp);
1881                 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1882                         // Invalid response!
1883                         return $response;
1884                 } // END - if
1885         } // END - if
1886
1887         // Write request
1888         fputs($fp, $request);
1889
1890         // Read response
1891         while (!feof($fp)) {
1892                 $response[] = trim(fgets($fp, 1024));
1893         } // END - while
1894
1895         // Close socket
1896         fclose($fp);
1897
1898         // Skip first empty lines
1899         $resp = $response;
1900         foreach ($resp as $idx => $line) {
1901                 // Trim space away
1902                 $line = trim($line);
1903
1904                 // Is this line empty?
1905                 if (empty($line)) {
1906                         // Then remove it
1907                         array_shift($response);
1908                 } else {
1909                         // Abort on first non-empty line
1910                         break;
1911                 }
1912         } // END - foreach
1913
1914         //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1915
1916         // Proxy agent found?
1917         if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1918                 // Proxy header detected, so remove two lines
1919                 array_shift($response);
1920                 array_shift($response);
1921         } // END - if
1922
1923         // Was the request successfull?
1924         if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1925                 // Not found / access forbidden
1926                 $response = array("", "", "");
1927         } // END - if
1928
1929         // Return response
1930         return $response;
1931 }
1932
1933 // Taken from www.php.net eregi() user comments
1934 function VALIDATE_EMAIL ($email) {
1935         // Compile email
1936         $email = COMPILE_CODE($email);
1937
1938         // Check first part of email address
1939         $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1940
1941         //  Check domain
1942         $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1943
1944         // Generate pattern
1945         $regex = "^".$first."@".$domain."$";
1946
1947         // Return check result
1948         return eregi($regex, $email);
1949 }
1950
1951 // Function taken from user comments on www.php.net / function eregi()
1952 function VALIDATE_URL ($URL, $compile=true) {
1953         // Trim URL a little
1954         $URL = trim(urldecode($URL));
1955         //* DEBUG: */ echo $URL."<br />";
1956
1957         // Compile some chars out...
1958         if ($compile) $URL = compileUriCode($URL, false, false, false);
1959         //* DEBUG: */ echo $URL."<br />";
1960
1961         // Check for the extension filter
1962         if (EXT_IS_ACTIVE("filter")) {
1963                 // Use the extension's filter set
1964                 return FILTER_VALIDATE_URL($URL, false);
1965         }
1966
1967         // If not installed, perform a simple test. Just make it sure there is always a http:// or
1968         // https:// in front of the URLs
1969         return isUrlValid($URL);
1970 }
1971
1972 // Generate a list of administrative links to a given userid
1973 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1974         // Define all main targets
1975         $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1976
1977         // Begin of navigation links
1978         $eval = "\$OUT = \"[&nbsp;";
1979
1980         foreach ($TARGETS as $tar) {
1981                 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&amp;what=".$tar."&amp;uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1982                 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1983                 if (($tar == "lock_user") && ($status == "LOCKED")) {
1984                         // Locked accounts shall be unlocked
1985                         $eval .= "UNLOCK_USER";
1986                 } else {
1987                         // All other status is fine
1988                         $eval .= strtoupper($tar);
1989                 }
1990                 $eval .= "_TITLE--}\\\">{--ADMIN_";
1991                 if (($tar == "lock_user") && ($status == "LOCKED")) {
1992                         // Locked accounts shall be unlocked
1993                         $eval .= "UNLOCK_USER";
1994                 } else {
1995                         // All other status is fine
1996                         $eval .= strtoupper($tar);
1997                 }
1998                 $eval .= "--}</a></span>&nbsp;|&nbsp;";
1999         }
2000
2001         // Finish navigation link
2002         $eval = substr($eval, 0, -7)."]\";";
2003         eval($eval);
2004
2005         // Return string
2006         return $OUT;
2007 }
2008
2009 // Generate an email link
2010 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2011         // Default email link (INSECURE! Spammer can read this by harvester programs)
2012         $EMAIL = "mailto:".$email;
2013
2014         // Check for several extensions
2015         if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2016                 // Create email link for contacting admin in guest area
2017                 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2018         } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2019                 // Create email link for contacting a member within admin area (or later in other areas, too?)
2020                 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2021         } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2022                 // Create email link to contact sponsor within admin area (or like the link above?)
2023                 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2024         }
2025
2026         // Shall I close the link when there is no admin?
2027         if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2028
2029         // Return email link
2030         return $EMAIL;
2031 }
2032
2033 // Generate a hash for extra-security for all passwords
2034 function generateHash ($plainText, $salt = "") {
2035         global $_SERVER;
2036
2037         // Is the required extension "sql_patches" there and a salt is not given?
2038         if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2039                 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2040                 return md5($plainText);
2041         } // END - if
2042
2043         // Do we miss an arry element here?
2044         if (!isConfigEntrySet('file_hash')) {
2045                 // Stop here
2046                 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2047         } // END - if
2048
2049         // When the salt is empty build a new one, else use the first x configured characters as the salt
2050         if (empty($salt)) {
2051                 // Build server string
2052                 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
2053
2054                 // Build key string
2055                 $keys   = constant('SITE_KEY').":".constant('DATE_KEY').":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).":".getConfig('master_salt');
2056
2057                 // Additional data
2058                 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2059
2060                 // Calculate number for generating the code
2061                 $a = time() + constant('_ADD') - 1;
2062
2063                 // Generate SHA1 sum from modula of number and the prime number
2064                 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2065                 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2066                 $sha1 = scrambleString($sha1);
2067                 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2068                 //* DEBUG: */ $sha1b = descrambleString($sha1);
2069                 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2070
2071                 // Generate the password salt string
2072                 $salt = substr($sha1, 0, getConfig('salt_length'));
2073                 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2074         } else {
2075                 // Use given salt
2076                 $salt = substr($salt, 0, getConfig('salt_length'));
2077                 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2078         }
2079
2080         // Return hash
2081         return $salt.sha1($salt.$plainText);
2082 }
2083
2084 // Scramble a string
2085 function scrambleString($str) {
2086         // Init
2087         $scrambled = "";
2088
2089         // Final check, in case of failture it will return unscrambled string
2090         if (strlen($str) > 40) {
2091                 // The string is to long
2092                 return $str;
2093         } elseif (strlen($str) == 40) {
2094                 // From database
2095                 $scrambleNums = explode(":", getConfig('pass_scramble'));
2096         } else {
2097                 // Generate new numbers
2098                 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2099         }
2100
2101         // Scramble string here
2102         //* DEBUG: */ echo "***Original=".$str."***<br />";
2103         for ($idx = 0; $idx < strlen($str); $idx++) {
2104                 // Get char on scrambled position
2105                 $char = substr($str, $scrambleNums[$idx], 1);
2106
2107                 // Add it to final output string
2108                 $scrambled .= $char;
2109         } // END - for
2110
2111         // Return scrambled string
2112         //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2113         return $scrambled;
2114 }
2115
2116 // De-scramble a string scrambled by scrambleString()
2117 function descrambleString($str) {
2118         // Scramble only 40 chars long strings
2119         if (strlen($str) != 40) return $str;
2120
2121         // Load numbers from config
2122         $scrambleNums = explode(":", getConfig('pass_scramble'));
2123
2124         // Validate numbers
2125         if (count($scrambleNums) != 40) return $str;
2126
2127         // Begin descrambling
2128         $orig = str_repeat(" ", 40);
2129         //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2130         for ($idx = 0; $idx < 40; $idx++) {
2131                 $char = substr($str, $idx, 1);
2132                 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2133         } // END - for
2134
2135         // Return scrambled string
2136         //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2137         return $orig;
2138 }
2139
2140 // Generated a "string" for scrambling
2141 function genScrambleString ($len) {
2142         // Prepare array for the numbers
2143         $scrambleNumbers = array();
2144
2145         // First we need to setup randomized numbers from 0 to 31
2146         for ($idx = 0; $idx < $len; $idx++) {
2147                 // Generate number
2148                 $rand = mt_rand(0, ($len -1));
2149
2150                 // Check for it by creating more numbers
2151                 while (array_key_exists($rand, $scrambleNumbers)) {
2152                         $rand = mt_rand(0, ($len -1));
2153                 } // END - while
2154
2155                 // Add number
2156                 $scrambleNumbers[$rand] = $rand;
2157         } // END - for
2158
2159         // So let's create the string for storing it in database
2160         $scrambleString = implode(":", $scrambleNumbers);
2161         return $scrambleString;
2162 }
2163
2164 // Append data like session ID or referal ID to the given URL which would
2165 // normally be stored in cookies
2166 function ADD_URL_DATA ($URL) {
2167         // Init add
2168         $ADD = "";
2169
2170         // Determine URL binder
2171         $BIND = "?";
2172         if (strpos($URL, "?") !== false) $BIND = "&amp;";
2173
2174         if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2175                 // Cookies are not accepted
2176                 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2177                         // Cookie found in URL
2178                         $ADD .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2179                 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2180                         // Not found! So let's set default here
2181                         $ADD .= $BIND."refid=".getConfig('def_refid');
2182                 }
2183         } // END - if
2184
2185         // Add all together and return it
2186         return $URL . $ADD;
2187 }
2188
2189 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2190 function generatePassString ($passHash) {
2191         // Return vanilla password hash
2192         $ret = $passHash;
2193
2194         // Is a secret key and master salt already initialized?
2195         if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2196                 // Only calculate when the secret key is generated
2197                 $newHash = ""; $start = 9;
2198                 for ($idx = 0; $idx < 10; $idx++) {
2199                         $part1 = hexdec(substr($passHash, $start, 4));
2200                         $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2201                         $mod = dechex($idx);
2202                         if ($part1 > $part2) {
2203                                 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2204                         } elseif ($part2 > $part1) {
2205                                 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2206                         }
2207                         $mod = substr(round($mod), 0, 4);
2208                         $mod = str_repeat('0', 4-strlen($mod)).$mod;
2209                         //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2210                         $start += 4;
2211                         $newHash .= $mod;
2212                 } // END - for
2213
2214                 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2215                 $ret = generateHash($newHash, getConfig('master_salt'));
2216                 //* DEBUG: */ print($ret."<br />\n");
2217         } else {
2218                 // Hash it simple
2219                 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2220                 $ret = md5($passHash);
2221                 //* DEBUG: */ echo "++".$ret."++<br />\n";
2222         }
2223
2224         // Return result
2225         return $ret;
2226 }
2227
2228 // Fix "deleted" cookies
2229 function FIX_DELETED_COOKIES ($cookies) {
2230         // Is this an array with entries?
2231         if ((is_array($cookies)) && (count($cookies) > 0)) {
2232                 // Then check all cookies if they are marked as deleted!
2233                 foreach ($cookies as $cookieName) {
2234                         // Is the cookie set to "deleted"?
2235                         if (get_session($cookieName) == "deleted") {
2236                                 set_session($cookieName, "");
2237                         }
2238                 } // END - foreach
2239         } // END - if
2240 }
2241
2242 // Output error messages in a fasioned way and die...
2243 function mxchange_die ($msg) {
2244         // Load header
2245         LOAD_INC_ONCE("inc/header.php");
2246
2247         // Load the message template
2248         LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2249
2250         // Load footer
2251         LOAD_INC_ONCE("inc/footer.php");
2252
2253         // Exit explicitly
2254         exit;
2255 }
2256
2257 // Display parsing time and number of SQL queries in footer
2258 function DISPLAY_PARSING_TIME_FOOTER() {
2259         // Is the timer started?
2260         if (!isset($GLOBALS['startTime'])) {
2261                 // Abort here
2262                 return false;
2263         } // END - if
2264
2265         // Get end time
2266         $endTime = microtime(true);
2267
2268         // "Explode" both times
2269         $start = explode(" ", $GLOBALS['startTime']);
2270         $end = explode(" ", $endTime);
2271         $runTime = $end[0] - $start[0];
2272         if ($runTime < 0) $runTime = 0;
2273         $runTime = TRANSLATE_COMMA($runTime);
2274
2275         // Prepare output
2276         $content = array(
2277                 'runtime'               => $runTime,
2278                 'numSQLs'               => (getConfig('sql_count') + 1),
2279                 'numTemplates'  => (getConfig('num_templates') + 1)
2280         );
2281
2282         // Load the template
2283         LOAD_TEMPLATE("show_timings", false, $content);
2284 }
2285
2286 // Check wether a boolean constant is set
2287 // Taken from user comments in PHP documentation for function constant()
2288 function isBooleanConstantAndTrue ($constName) { // : Boolean
2289         // Failed by default
2290         $res = false;
2291
2292         // In cache?
2293         if (isset($GLOBALS['cache_array']['const'][$constName])) {
2294                 // Use cache
2295                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2296                 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2297         } else {
2298                 // Check constant
2299                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2300                 if (defined($constName)) {
2301                         // Found!
2302                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2303                         $res = (constant($constName) === true);
2304                 } // END - if
2305
2306                 // Set cache
2307                 $GLOBALS['cache_array']['const'][$constName] = $res;
2308         }
2309         //* DEBUG: */ var_dump($res);
2310
2311         // Return value
2312         return $res;
2313 }
2314
2315 // Checks if a given apache module is loaded
2316 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2317         // Check it and return result
2318         return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2319 }
2320
2321 // "Getter" for language strings
2322 // @TODO Rewrite all language constants to this function.
2323 function getMessage ($messageId) {
2324         // Default is not found!
2325         $return = "!".$messageId."!";
2326
2327         // Is the language string found?
2328         if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2329                 // Language array element found in small_letters
2330                 $return = $GLOBALS['msg'][$messageId];
2331         } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2332                 // @DEPRECATED Language array element found in BIG_LETTERS
2333                 $return = $GLOBALS['msg'][$messageId];
2334         } elseif (defined($messageId)) {
2335                 // @DEPRECATED Deprecated constant found
2336                 $return = constant($messageId);
2337         } else {
2338                 // Missing language constant
2339                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2340         }
2341
2342         // Return the string
2343         return $return;
2344 }
2345
2346 // Get current theme name
2347 function GET_CURR_THEME() {
2348         global $INC_POOL;
2349
2350         // The default theme is 'default'... ;-)
2351         $ret = "default";
2352
2353         // Load default theme if not empty from configuration
2354         if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2355
2356         if (!isSessionVariableSet('mxchange_theme')) {
2357                 // Set default theme
2358                 set_session('mxchange_theme', $ret);
2359         } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2360                 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2361                 // Get theme from cookie
2362                 $ret = get_session('mxchange_theme');
2363
2364                 // Is it valid?
2365                 if (THEME_GET_ID($ret) == 0) {
2366                         // Fix it to default
2367                         $ret = "default";
2368                 } // END - if
2369         } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET(('theme'))) || (REQUEST_ISSET_POST(('theme'))))) {
2370                 // Prepare FQFN for checking
2371                 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET(('theme')));
2372
2373                 // Installation mode active
2374                 if ((REQUEST_ISSET_GET(('theme'))) && (FILE_READABLE($theme))) {
2375                         // Set cookie from URL data
2376                         set_session('mxchange_theme', REQUEST_GET(('theme')));
2377                 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2378                         // Set cookie from posted data
2379                         set_session('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2380                 }
2381
2382                 // Set return value
2383                 $ret = get_session('mxchange_theme');
2384         } else {
2385                 // Invalid design, reset cookie
2386                 set_session('mxchange_theme', $ret);
2387         }
2388
2389         // Add (maybe) found theme.php file to inclusion list
2390         $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
2391
2392         // Try to load the requested include file
2393         if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2394
2395         // Return theme value
2396         return $ret;
2397 }
2398
2399 // Get id from theme
2400 function THEME_GET_ID ($name) {
2401         // Is the extension "theme" installed?
2402         if (!EXT_IS_ACTIVE("theme")) {
2403                 // Then abort here
2404                 return 0;
2405         } // END - if
2406
2407         // Default id
2408         $id = 0;
2409
2410         // Is the cache entry there?
2411         if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2412                 // Get the version from cache
2413                 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2414
2415                 // Count up
2416                 incrementConfigEntry('cache_hits');
2417         } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2418                 // Check if current theme is already imported or not
2419                 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2420                         array($name), __FUNCTION__, __LINE__);
2421
2422                 // Entry found?
2423                 if (SQL_NUMROWS($result) == 1) {
2424                         // Fetch data
2425                         list($id) = SQL_FETCHROW($result);
2426                 } // END - if
2427
2428                 // Free result
2429                 SQL_FREERESULT($result);
2430         }
2431
2432         // Return id
2433         return $id;
2434 }
2435
2436 // Read a given file
2437 function READ_FILE ($FQFN, $sqlPrepare = false) {
2438         // Load the file
2439         if (function_exists('file_get_contents')) {
2440                 // Use new function
2441                 $content = file_get_contents($FQFN);
2442         } else {
2443                 // Fall-back to implode-file chain
2444                 $content = implode("", file($FQFN));
2445         }
2446
2447         // Prepare SQL queries?
2448         if ($sqlPrepare === true) {
2449                 // Remove some unwanted chars
2450                 $content = str_replace("\r", "", $content);
2451                 $content = str_replace("\n\n", "\n", $content);
2452         } // END - if
2453
2454         // Return the content
2455         return $content;
2456 }
2457
2458 // Writes content to a file
2459 function WRITE_FILE ($FQFN, $content) {
2460         // Is the file writeable?
2461         if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2462                 // Not writeable!
2463                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2464
2465                 // Failed! :(
2466                 return false;
2467         } // END - if
2468
2469         // By default all is failed...
2470         $return = false;
2471
2472         // Is the function there?
2473         if (function_exists('file_put_contents')) {
2474                 // Write it directly
2475                 $return = file_put_contents($FQFN, $content);
2476         } else {
2477                 // Write it with fopen
2478                 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
2479                 fwrite($fp, $content);
2480                 fclose($fp);
2481
2482                 // Set CHMOD rights
2483                 $return = chmod($FQFN, 0644);
2484         }
2485
2486         // Return status
2487         return $return;
2488 }
2489
2490 // Generates an error code from given account status
2491 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
2492         // Default error code if unknown account status
2493         $ERROR = constant('CODE_UNKNOWN_STATUS');
2494
2495         // Generate constant name
2496         $constantName = sprintf("CODE_ID_%s", $status);
2497
2498         // Is the constant there?
2499         if (defined($constantName)) {
2500                 // Then get it!
2501                 $ERROR = constant($constantName);
2502         } else {
2503                 // Unknown status
2504                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2505         }
2506
2507         // Return error code
2508         return $ERROR;
2509 }
2510
2511 // Clears the output buffer. This function does *NOT* backup sent content.
2512 function clearOutputBuffer () {
2513         // Trigger an error on failure
2514         if (!ob_end_clean()) {
2515                 // Failed!
2516                 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
2517         } // END - if
2518 }
2519
2520 // "Getter" for revision/version data
2521 function getActualVersion ($type = 0) {
2522         // By default nothing is new... ;-)
2523         $new = false;
2524
2525         // FQFN of revision file
2526         $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2527
2528         // Check for revision file
2529         if (!FILE_READABLE($FQFN)) {
2530                 // Not found, so we need to create it
2531                 $new = true;
2532         } else {
2533                 // Revision file found
2534                 $ins_vers = explode("\n", READ_FILE($FQFN));
2535
2536                 // Is the content valid?
2537                 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
2538                         // File needs update!
2539                         $new = true;
2540                 } else {
2541                         // Revision-File has valid Data and isn't 'new' so return the Rev-Number
2542                         return trim($ins_vers[$type]);
2543                 }
2544         }
2545
2546         // Has it been updated?
2547         if ($new === true)  {
2548                 // No Revision-File or has no valid Data so read the Revision from the Server.
2549                 $version = GET_URL("check-updates3.php");
2550
2551                 // Prepare content
2552                 $akt_vers[] = trim($version[10]);
2553                 $akt_vers[] = trim($version[9]);
2554                 $akt_vers[] = trim($version[8]);
2555
2556                 // Write file
2557                 WRITE_FILE($FQFN, implode("\n", $akt_vers));
2558
2559                 // Return requested content
2560                 return trim($akt_vers[$type]);
2561         }
2562 }
2563
2564 // Loads an include file and logs any missing files for debug purposes
2565 function LOAD_INC ($INC) {
2566         // Add the path. This is why we need a trailing slash in config.php
2567         $FQFN = constant('PATH') . $INC;
2568
2569         // Is the include file there?
2570         if (!FILE_READABLE($FQFN)) {
2571                 // Not there so log it
2572                 debug_report_bug(sprintf("Include file %s not found.", $INC));
2573                 return false;
2574         } // END - if
2575
2576         // Try to load it
2577         require($FQFN);
2578 }
2579
2580 // Loads an include file once
2581 function LOAD_INC_ONCE ($INC) {
2582         // Is it not loaded?
2583         if (!isset($GLOBALS['load_once'][$INC])) {
2584                 // Then try to load it
2585                 LOAD_INC($INC);
2586
2587                 // And mark it as loaded
2588                 $GLOBALS['load_once'][$INC] = "loaded";
2589         } // END - if
2590 }
2591
2592 // Back-ported from the new ship-simu engine. :-)
2593 function debug_get_printable_backtrace () {
2594         // Init variable
2595         $backtrace = "<ol>\n";
2596
2597         // Get and prepare backtrace for output
2598         $backtraceArray = debug_backtrace();
2599         foreach ($backtraceArray as $key => $trace) {
2600                 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2601                 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2602                 if (!isset($trace['args'])) $trace['args'] = array();
2603                 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span></li>\n";
2604         } // END - foreach
2605
2606         // Close it
2607         $backtrace .= "</ol>\n";
2608
2609         // Return the backtrace
2610         return $backtrace;
2611 }
2612
2613 // Output a debug backtrace to the user
2614 function debug_report_bug ($message = "") {
2615         // Init message
2616         $debug = "";
2617         // Is the optional message set?
2618         if (!empty($message)) {
2619                 // Use and log it
2620                 $debug = sprintf("Note: %s<br />\n",
2621                         $message
2622                 );
2623
2624                 // @TODO Add a little more infos here
2625                 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2626         } // END - if
2627
2628         // Add output
2629         $debug .= ("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
2630         $debug .= (debug_get_printable_backtrace());
2631         $debug .= ("</pre>Thank you for your help finding bugs.");
2632
2633         // And abort here
2634         die($debug);
2635 }
2636
2637 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2638 function generateSeed () {
2639         list($usec, $sec) = explode(" ", microtime());
2640         return ((float)$sec + (float)$usec);
2641 }
2642
2643 // Converts a message code to a human-readable message
2644 function convertCodeToMessage ($code) {
2645         $msg = "";
2646         switch ($code) {
2647                 case constant('CODE_LOGOUT_DONE')      : $msg = getMessage('LOGOUT_DONE'); break;
2648                 case constant('CODE_LOGOUT_FAILED')    : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2649                 case constant('CODE_DATA_INVALID')     : $msg = getMessage('MAIL_DATA_INVALID'); break;
2650                 case constant('CODE_POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2651                 case constant('CODE_ACCOUNT_LOCKED')   : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2652                 case constant('CODE_USER_404')         : $msg = getMessage('USER_NOT_FOUND'); break;
2653                 case constant('CODE_STATS_404')        : $msg = getMessage('MAIL_STATS_404'); break;
2654                 case constant('CODE_ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2655
2656                 case constant('CODE_ERROR_MAILID'):
2657                         if (EXT_IS_ACTIVE($ext, true)) {
2658                                 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2659                         } else {
2660                                 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
2661                         }
2662                         break;
2663
2664                 case constant('CODE_EXTENSION_PROBLEM'):
2665                         if (REQUEST_ISSET_GET(('ext'))) {
2666                                 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2667                         } else {
2668                                 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2669                         }
2670                         break;
2671
2672                 case constant('CODE_COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2673                 case constant('CODE_BEG_SAME_AS_OWN')  : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2674                 case constant('CODE_LOGIN_FAILED')     : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2675                 default                                : $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code); break;
2676         } // END - switch
2677
2678         // Return the message
2679         return $msg;
2680 }
2681
2682 // Checks wether the given extension is currently not installed
2683 // and redirects if so.
2684 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
2685         // Is the extension uninstalled/inactive?
2686         if (!EXT_IS_ACTIVE($ext_name)) {
2687                 // Redirect to index
2688                 LOAD_URL("modules.php?module=index&amp;msg=".constant('CODE_EXTENSION_PROBLEM')."&amp;ext=".$ext_name);
2689         } // END - if
2690 }
2691
2692 // Generate a "link" for the given admin id (aid)
2693 function GENERATE_AID_LINK ($aid) {
2694         // No assigned admin is default
2695         $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2696
2697         // Zero? = Not assigned
2698         if ($aid == "0") {
2699                 // Load admin's login
2700                 $login = GET_ADMIN_LOGIN($aid);
2701                 if ($login != "***") {
2702                         // Is the extension there?
2703                         if (EXT_IS_ACTIVE("admins")) {
2704                                 // Admin found
2705                                 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
2706                         } else {
2707                                 // Extension not found
2708                                 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
2709                         }
2710                 } else {
2711                         // Maybe deleted?
2712                         $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2713                 }
2714         } // END - if
2715
2716         // Return result
2717         return $admin;
2718 }
2719
2720 // Checks wether an include file (non-FQFN better) is readable
2721 function INCLUDE_READABLE ($INC) {
2722         // Construct FQFN
2723         $FQFN = constant('PATH') . $INC;
2724
2725         // Is it readable?
2726         return FILE_READABLE($FQFN);
2727 }
2728
2729 // Encode strings
2730 // @TODO Implement $compress
2731 function encodeString ($str, $compress=true) {
2732         $str = urlencode(base64_encode(compileUriCode($str)));
2733         return $str;
2734 }
2735
2736 // Decode strings encoded with encodeString()
2737 // @TODO Implement $decompress
2738 function decodeString ($str, $decompress=true) {
2739         $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2740         return $str;
2741 }
2742
2743 // Compile characters which are allowed in URLs
2744 function compileUriCode ($code, $simple=true) {
2745         // Compile constants
2746         if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2747
2748         // Compile QUOT and other non-HTML codes
2749         $code = str_replace("{DOT}", ".",
2750                 str_replace("{SLASH}", "/",
2751                 str_replace("{QUOT}", "'",
2752                 str_replace("{DOLLAR}", "$",
2753                 str_replace("{OPEN_ANCHOR}", "(",
2754                 str_replace("{CLOSE_ANCHOR}", ")",
2755                 str_replace("{OPEN_SQR}", "[",
2756                 str_replace("{CLOSE_SQR}", "]",
2757                 str_replace("{PER}", "%",
2758                 $code
2759         )))))))));
2760
2761         // Return compiled code
2762         return $code;
2763 }
2764
2765 // Function taken from user comments on www.php.net / function eregi()
2766 function isUrlValid ($url) {
2767         // Prepare URL
2768         $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
2769
2770         // Allows http and https
2771         $http      = "(http|https)+(:\/\/)";
2772         // Test domain
2773         $domain1   = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2774         // Test double-domains (e.g. .de.vu)
2775         $domain2   = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2776         // Test IP number
2777         $ip        = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2778         // ... directory
2779         $dir       = "((/)+([-_\.[:alnum:]])+)*";
2780         // ... page
2781         $page      = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2782         // ... and the string after and including question character
2783         $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2784         // Pattern for URLs like http://url/dir/doc.html?var=value
2785         $pattern['d1dpg1']  = $http.$domain1.$dir.$page.$getstring1;
2786         $pattern['d2dpg1']  = $http.$domain2.$dir.$page.$getstring1;
2787         $pattern['ipdpg1']  = $http.$ip.$dir.$page.$getstring1;
2788         // Pattern for URLs like http://url/dir/?var=value
2789         $pattern['d1dg1']  = $http.$domain1.$dir."/".$getstring1;
2790         $pattern['d2dg1']  = $http.$domain2.$dir."/".$getstring1;
2791         $pattern['ipdg1']  = $http.$ip.$dir."/".$getstring1;
2792         // Pattern for URLs like http://url/dir/page.ext
2793         $pattern['d1dp']  = $http.$domain1.$dir.$page;
2794         $pattern['d1dp']  = $http.$domain2.$dir.$page;
2795         $pattern['ipdp']  = $http.$ip.$dir.$page;
2796         // Pattern for URLs like http://url/dir
2797         $pattern['d1d']  = $http.$domain1.$dir;
2798         $pattern['d2d']  = $http.$domain2.$dir;
2799         $pattern['ipd']  = $http.$ip.$dir;
2800         // Pattern for URLs like http://url/?var=value
2801         $pattern['d1g1']  = $http.$domain1."/".$getstring1;
2802         $pattern['d2g1']  = $http.$domain2."/".$getstring1;
2803         $pattern['ipg1']  = $http.$ip."/".$getstring1;
2804         // Pattern for URLs like http://url?var=value
2805         $pattern['d1g12']  = $http.$domain1.$getstring1;
2806         $pattern['d2g12']  = $http.$domain2.$getstring1;
2807         $pattern['ipg12']  = $http.$ip.$getstring1;
2808         // Test all patterns
2809         $reg = false;
2810         foreach ($pattern as $key=>$pat) {
2811                 // Debug regex?
2812                 if (defined('DEBUG_REGEX')) {
2813                         $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2814                         $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2815                         $pat = str_replace("[:digit:]", "0-9", $pat);
2816                         $pat = str_replace(".", "\.", $pat);
2817                         $pat = str_replace("@", "\@", $pat);
2818                         echo $key."=&nbsp;".$pat."<br />";
2819                 }
2820
2821                 // Check if expression matches
2822                 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2823
2824                 // Does it match?
2825                 if ($reg === true) break;
2826         }
2827
2828         // Return true/false
2829         return $reg;
2830 }
2831
2832 // Smartly adds slashes
2833 function smartAddSlashes ($unquoted) {
2834         $unquoted = str_replace("\\", "", $unquoted);
2835         return addslashes($unquoted);
2836 }
2837
2838 // Decode entities in a nicer way
2839 function decodeEntities ($str) {
2840         // @TODO We may want to switch over to UTF-8 here!
2841         $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
2842
2843         // Return decoded string
2844         return $decodedString;
2845 }
2846
2847 // Wtites data to a config.php-style file
2848 // @TODO Rewrite this function to use READ_FILE() and WRITE_FILE()
2849 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2850         // Initialize some variables
2851         $done = false;
2852         $seek++;
2853         $next  = -1;
2854         $found = false;
2855
2856         // Is the file there and read-/write-able?
2857         if ((FILE_READABLE($FQFN)) && (is_writeable($FQFN))) {
2858                 $search = "CFG: ".$comment;
2859                 $tmp = $FQFN.".tmp";
2860
2861                 // Open the source file
2862                 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
2863
2864                 // Is the resource valid?
2865                 if (is_resource($fp)) {
2866                         // Open temporary file
2867                         $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
2868
2869                         // Is the resource again valid?
2870                         if (is_resource($fp_tmp)) {
2871                                 while (!feof($fp)) {
2872                                         // Read from source file
2873                                         $line = fgets ($fp, 1024);
2874
2875                                         if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2876
2877                                         if ($next > -1) {
2878                                                 if ($next === $seek) {
2879                                                         $next = -1;
2880                                                         $line = $prefix . $DATA . $suffix."\n";
2881                                                 } else {
2882                                                         $next++;
2883                                                 }
2884                                         }
2885
2886                                         // Write to temp file
2887                                         fputs($fp_tmp, $line);
2888                                 }
2889
2890                                 // Close temp file
2891                                 fclose($fp_tmp);
2892
2893                                 // Finished writing tmp file
2894                                 $done = true;
2895                         }
2896
2897                         // Close source file
2898                         fclose($fp);
2899
2900                         if (($done) && ($found)) {
2901                                 // Copy back tmp file and delete tmp :-)
2902                                 copy($tmp, $FQFN);
2903                                 return unlink($tmp);
2904                         } elseif (!$found) {
2905                                 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
2906                         } else {
2907                                 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
2908                         }
2909                 }
2910         } else {
2911                 // File not found, not readable or writeable
2912                 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
2913         }
2914
2915         // An error was detected!
2916         return false;
2917 }
2918 // Send notification to admin
2919 function SEND_ADMIN_NOTIFICATION ($subject, $templateName, $content=array(), $uid="0") {
2920         if (GET_EXT_VERSION("admins") >= "0.4.1") {
2921                 // Send new way
2922                 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2923         } else {
2924                 // Send out out-dated way
2925                 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2926                 SEND_ADMIN_EMAILS($subject, $msg);
2927         }
2928 }
2929
2930 // Merges an array together but only if both are arrays
2931 function merge_array ($array1, $array2) {
2932         // Are both an array?
2933         if ((is_array($array1)) && (is_array($array2))) {
2934                 // Merge all together
2935                 return array_merge($array1, $array2);
2936         } elseif (is_array($array1)) {
2937                 // Return left array
2938                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
2939                 return $array1;
2940         } elseif (is_array($array2)) {
2941                 // Return right array
2942                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
2943                 return $array2;
2944         }
2945
2946         // Both are not arrays
2947         debug_report_bug(__FUNCTION__.": No arrays provided!");
2948 }
2949
2950 // Debug message logger
2951 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2952         // Is debug mode enabled?
2953         if ((isDebugModeEnabled()) || ($force === true)) {
2954                 // Log this message away
2955                 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2956                 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
2957                 fclose($fp);
2958         } // END - if
2959 }
2960
2961 // Reads a directory with PHP files in and gets only files back
2962 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2963         $INCs = array();
2964
2965         // Open directory
2966         $dirPointer = opendir(constant('PATH') . $baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2967
2968         // Read all entries
2969         while ($baseFile = readdir($dirPointer)) {
2970                 // Load file only if extension is active
2971                 $INC = $baseDir.$baseFile;
2972                 $FQFN = constant('PATH') . $INC;
2973
2974                 // Is this a valid reset file?
2975                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2976                 if ((FILE_READABLE($FQFN)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2977                         // Remove both for extension name
2978                         $extName = substr($baseFile, strlen($prefix), -4);
2979
2980                         // Try to find it
2981                         $extId = GET_EXT_ID($extName);
2982
2983                         // Is the extension valid and active?
2984                         if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2985                                 // Then add this file
2986                                 $INCs[] = $INC;
2987                         } elseif ($extId == 0) {
2988                                 // Add non-extension files as well
2989                                 $INCs[] = $INC;
2990                         }
2991                 } // END - if
2992         } // END - while
2993
2994         // Close directory
2995         closedir($dirPointer);
2996
2997         // Sort array
2998         asort($INCs);
2999
3000         // Return array with include files
3001         return $INCs;
3002 }
3003
3004 // Load more reset scripts
3005 function runResetIncludes () {
3006         // Is the reset set or old sql_patches?
3007         if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
3008                 // Then abort here
3009                 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3010         } // END - if
3011
3012         // Get more daily reset scripts
3013         $INC_POOL = GET_DIR_AS_ARRAY("inc/reset/", "reset_");
3014
3015         // Update database
3016         if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
3017
3018         // Is the config entry set?
3019         if (GET_EXT_VERSION("sql_patches") >= "0.4.2") {
3020                 // Create current week mark
3021                 $currWeek = date("W", time());
3022
3023                 // Has it changed?
3024                 if (getConfig('last_week') != $currWeek) {
3025                         // Include weekly reset scripts
3026                         $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY("inc/weekly/", "weekly_"));
3027
3028                         // Update config
3029                         if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
3030                 } // END - if
3031
3032                 // Create current month mark
3033                 $currMonth = date("m", time());
3034
3035                 // Has it changed?
3036                 if (getConfig('last_month') != $currMonth) {
3037                         // Include monthly reset scripts
3038                         $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY("inc/monthly/", "monthly_"));
3039
3040                         // Update config
3041                         if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
3042                 } // END - if
3043         } // END - if
3044
3045         // Run the filter
3046         runFilterChain('load_includes', $INC_POOL);
3047 }
3048
3049 // Handle extra values
3050 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
3051         // Default is the value itself
3052         $ret = $value;
3053
3054         // Do we have a special filter function?
3055         if (!empty($filterFunction)) {
3056                 // Does the filter function exist?
3057                 if (function_exists($filterFunction)) {
3058                         // Do we have extra parameters here?
3059                         if (!empty($extraValue)) {
3060                                 // Put both parameters in one new array by default
3061                                 $args = array($value, $extraValue);
3062
3063                                 // If we have an array simply use it and pre-extend it with our value
3064                                 if (is_array($extraValue)) {
3065                                         // Make the new args array
3066                                         $args = merge_array(array($value), $extraValue);
3067                                 } // END - if
3068
3069                                 // Call the multi-parameter call-back
3070                                 $ret = call_user_func_array($filterFunction, $args);
3071                         } else {
3072                                 // One parameter call
3073                                 $ret = call_user_func($filterFunction, $value);
3074                         }
3075                 } // END - if
3076         } // END - if
3077
3078         // Return the value
3079         return $ret;
3080 }
3081
3082 // Check if given FQFN is a readable file
3083 function FILE_READABLE ($FQFN) {
3084         // Check all...
3085         return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
3086 }
3087
3088 // Converts timestamp selections into a timestamp
3089 function CONVERT_SELECTIONS_TO_TIMESTAMP (&$POST, &$DATA, &$id, &$skip) {
3090         // Init test variable
3091         $test2 = "";
3092
3093         // Get last three chars
3094         $test = substr($id, -3);
3095
3096         // Improved way of checking! :-)
3097         if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
3098                 // Found a multi-selection for timings?
3099                 $test = substr($id, 0, -3);
3100                 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)) {
3101                         // Generate timestamp
3102                         $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
3103                         $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3104
3105                         // Remove data from array
3106                         foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
3107                                 unset($POST[$test."_".$rem]);
3108                         } // END - foreach
3109
3110                         // Skip adding
3111                         unset($id); $skip = true; $test2 = $test;
3112                 } // END - if
3113         } else {
3114                 // Process this entry
3115                 $skip = false;
3116                 $test2 = "";
3117         }
3118 }
3119
3120 // Reverts the german decimal comma into Computer decimal dot
3121 function REVERT_COMMA ($str) {
3122         // Default float is not a float... ;-)
3123         $float = false;
3124
3125         // Which language is selected?
3126         switch (GET_LANGUAGE()) {
3127                 case "de": // German language
3128                         // Remove german thousand dots first
3129                         $str = str_replace(".", "", $str);
3130
3131                         // Replace german commata with decimal dot and cast it
3132                         $float = (float)str_replace(",", ".", $str);
3133                         break;
3134
3135                 default: // US and so on
3136                         // Remove thousand dots first and cast
3137                         $float = (float)str_replace(",", "", $str);
3138                         break;
3139         }
3140
3141         // Return float
3142         return $float;
3143 }
3144
3145 // Handle menu-depending failed logins and return the rendered content
3146 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3147         // Default output is empty ;-)
3148         $OUT = "";
3149
3150         // Is the session data set?
3151         if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3152                 // Ignore zero values
3153                 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
3154                         // Non-guest has login failures found, get both data and prepare it for template
3155                         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3156                         $content = array(
3157                                 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
3158                                 'last_failure'   => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
3159                         );
3160
3161                         // Load template
3162                         $OUT = LOAD_TEMPLATE("login_failures", true, $content);
3163                 } // END - if
3164
3165                 // Reset session data
3166                 set_session('mxchange_'.$accessLevel.'_failures', "");
3167                 set_session('mxchange_'.$accessLevel.'_last_fail', "");
3168         } // END - if
3169
3170         // Return rendered content
3171         return $OUT;
3172 }
3173
3174 // Rebuild cache
3175 function rebuildCacheFiles ($cache, $inc="") {
3176         // Shall I remove the cache file?
3177         if ((EXT_IS_ACTIVE("cache")) && (isCacheInstanceValid())) {
3178                 // Rebuild cache
3179                 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3180                         // Destroy it
3181                         $GLOBALS['cache_instance']->destroyCacheFile();
3182                 } // END - if
3183
3184                 // Include file given?
3185                 if (!empty($inc)) {
3186                         // Construct FQFN
3187                         $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3188
3189                         // Is the include there?
3190                         if (INCLUDE_READABLE($INC)) {
3191                                 // And rebuild it from scratch
3192                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3193                                 LOAD_INC($INC);
3194                         } else {
3195                                 // Include not found!
3196                                 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3197                         }
3198                 } // END - if
3199         } // END - if
3200 }
3201
3202 // Purge admin menu cache
3203 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
3204         // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3205         if (!EXT_IS_ACTIVE("cache")) {
3206                 // Cache extension not active
3207                 return false;
3208         } elseif (!isCacheInstanceValid()) {
3209                 // No cache instance!
3210                 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3211                 return false;
3212         } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
3213                 // Caching disabled (currently experiemental!)
3214                 return false;
3215         }
3216
3217         // Experiemental feature!
3218         debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3219 }
3220
3221 // Translates the "pool type" into human-readable
3222 function TRANSLATE_POOL_TYPE ($type) {
3223         // Default type is unknown
3224         $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
3225
3226         // Generate constant
3227         $constName = sprintf("POOL_TYPE_%s", $type);
3228
3229         // Does it exist?
3230         if (defined($constName)) {
3231                 // Then use it
3232                 $translated = getMessage($constName);
3233         } // END - if
3234
3235         // Return "translation"
3236         return $translated;
3237 }
3238
3239 // "Getter" for remote IP number
3240 function GET_REMOTE_ADDR () {
3241         // Get remote ip from environment
3242         $remoteAddr = getenv('REMOTE_ADDR');
3243
3244         // Is removeip installed?
3245         if (EXT_IS_ACTIVE("removeip")) {
3246                 // Then anonymize it
3247                 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3248         } // END - if
3249
3250         // Return it
3251         return $remoteAddr;
3252 }
3253
3254 // "Getter" for remote hostname
3255 function GET_REMOTE_HOST () {
3256         // Get remote ip from environment
3257         $remoteHost = getenv('REMOTE_HOST');
3258
3259         // Is removeip installed?
3260         if (EXT_IS_ACTIVE("removeip")) {
3261                 // Then anonymize it
3262                 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3263         } // END - if
3264
3265         // Return it
3266         return $remoteHost;
3267 }
3268
3269 // "Getter" for user agent
3270 function GET_USER_AGENT () {
3271         // Get remote ip from environment
3272         $userAgent = getenv('HTTP_USER_AGENT');
3273
3274         // Is removeip installed?
3275         if (EXT_IS_ACTIVE("removeip")) {
3276                 // Then anonymize it
3277                 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3278         } // END - if
3279
3280         // Return it
3281         return $userAgent;
3282 }
3283
3284 // "Getter" for referer
3285 function GET_REFERER () {
3286         // Get remote ip from environment
3287         $referer = getenv('HTTP_REFERER');
3288
3289         // Is removeip installed?
3290         if (EXT_IS_ACTIVE("removeip")) {
3291                 // Then anonymize it
3292                 $referer = GET_ANONYMOUS_REFERER($referer);
3293         } // END - if
3294
3295         // Return it
3296         return $referer;
3297 }
3298
3299 // Adds a bonus mail to the queue
3300 // This is a high-level function!
3301 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
3302         // Use mode from data if not set and availble ;-)
3303         if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3304
3305         // Generate receiver list
3306         $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
3307
3308         // Receivers added?
3309         if (!empty($RECEIVER)) {
3310                 // Add bonus mail to queue
3311                 ADD_BONUS_MAIL_TO_QUEUE(
3312                         $data['subject'],
3313                         $data['text'],
3314                         $RECEIVER,
3315                         $data['points'],
3316                         $data['seconds'],
3317                         $data['url'],
3318                         $data['cat'],
3319                         $mode,
3320                         $data['receiver']
3321                 );
3322
3323                 // Mail inserted into bonus pool
3324                 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
3325         } elseif ($output) {
3326                 // More entered than can be reached!
3327                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
3328         } else {
3329                 // Debug log
3330                 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3331         }
3332 }
3333
3334 // Determines referal id and sets it
3335 function DETERMINE_REFID () {
3336         global $CLICK, $_SERVER;
3337
3338         // Check if refid is set
3339         if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3340                 // The variable user comes from the click-counter script click.php and we only accept this here
3341                 $GLOBALS['refid'] = bigintval($_GET['user']);
3342         } elseif (!empty($_POST['refid'])) {
3343                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3344                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3345         } elseif (!empty($_GET['refid'])) {
3346                 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3347                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3348         } elseif (!empty($_GET['ref'])) {
3349                 // Set refid=ref (the referal link uses such variable)
3350                 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3351         } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
3352                 // Set session refid als global
3353                 $GLOBALS['refid'] = bigintval(get_session('refid'));
3354         } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
3355                 // Set default refid as refid in URL
3356                 $GLOBALS['refid'] = getConfig(('def_refid'));
3357         } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
3358                 // Select a random user which has confirmed enougth mails
3359                 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3360         } else {
3361                 // No default ID when sql_patches is not installed or none set
3362                 $GLOBALS['refid'] = 0;
3363         }
3364
3365         // Set cookie when default refid > 0
3366         if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
3367                 // Set cookie
3368                 set_session('refid', $GLOBALS['refid']);
3369         } // END - if
3370
3371         // Return determined refid
3372         return $GLOBALS['refid'];
3373 }
3374
3375 // Check wether we are installing
3376 function isInstalling () {
3377         return (isset($GLOBALS['mxchange_installing']));
3378 }
3379
3380 // Check wether this script is installed
3381 function isInstalled () {
3382         return isBooleanConstantAndTrue('mxchange_installed');
3383 }
3384
3385 // Check wether an admin is registered
3386 function isAdminRegistered () {
3387         return isBooleanConstantAndTrue('admin_registered');
3388 }
3389
3390 // Enables the reset mode. Only call this function if you really want the
3391 // reset to be run!
3392 function enableResetMode () {
3393         // Enable the reset mode
3394         $GLOBALS['reset_enabled'] = true;
3395
3396         // Run filters
3397         runFilterChain('reset_enabled');
3398 }
3399
3400 // Checks wether the reset mode is active
3401 function isResetModeEnabled () {
3402         // Now simply check it
3403         return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3404 }
3405
3406 // Checks wether the debug mode is enabled
3407 function isDebugModeEnabled () {
3408         // Simply check it
3409         return isBooleanConstantAndTrue('DEBUG_MODE');
3410 }
3411
3412 // Checks wether the cache instance is valid
3413 function isCacheInstanceValid () {
3414         return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3415 }
3416
3417 //////////////////////////////////////////////////
3418 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3419 //////////////////////////////////////////////////
3420 //
3421 if (!function_exists('html_entity_decode')) {
3422         // Taken from documentation on www.php.net
3423         function html_entity_decode ($string) {
3424                 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3425                 $trans_tbl = array_flip($trans_tbl);
3426                 return strtr($string, $trans_tbl);
3427         }
3428 } // END - if
3429
3430 // [EOF]
3431 ?>