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