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