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