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