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