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