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