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