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