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