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