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