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