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