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