2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
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 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
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. *
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. *
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, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
40 // Check if our config file is writeable or not
41 function IS_INC_WRITEABLE($inc) {
43 $fqfn = sprintf("%sinc/%s.php", PATH, $inc);
45 // Abort by simple test
46 if ((FILE_READABLE($fqfn)) && (!is_writeable($fqfn))) {
50 // Test if we can append data
51 $fp = @fopen($fqfn, 'a');
52 if ($inc == "dummy") {
55 return @unlink($fqfn);
57 // Close all other files
62 // Open a table (you may want to add some header stuff here)
63 function OPEN_TABLE($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
66 // Count tables so we can generate CSS classes for every table... :-)
68 // Class is empty so count one up and create a class
69 $table_cnt++; $CLASS = "class".$table_cnt;
71 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
73 // Shall I add the classes to TABLE and TD or only to TD?
74 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
77 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
80 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
82 // Vertical align is given
83 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
84 $OUT .= ">\n<TR>\n<TD";
85 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
86 $OUT .= " class=\"".$CLASS."\">";
90 // Close a table (you may want to add some footer stuff here)
91 function CLOSE_TABLE($ADD="") {
92 OUTPUT_HTML(" </TD>\n</TR>");
93 if (!empty($ADD)) OUTPUT_HTML($ADD);
94 OUTPUT_HTML("</TABLE>");
97 // Output HTML code directly or "render" it. You addionally switch the new-line character off
98 function OUTPUT_HTML($HTML, $NEW_LINE = true) {
99 // Some global variables
100 global $OUTPUT, $footer, $CSS;
102 // Do we have HTML-Code here?
104 // Yes, so we handle it as you have configured
108 // That's why you don't need any \n at the end of your HTML code... :-)
109 if (_OB_CACHING == "on") {
110 // Output into PHP's internal buffer
113 // That's why you don't need any \n at the end of your HTML code... :-)
114 if ($NEW_LINE) echo "\n";
116 // Render mode for old or lame servers...
119 // That's why you don't need any \n at the end of your HTML code... :-)
120 if ($NEW_LINE) $OUTPUT .= "\n";
125 // If we are switching from render to direct output rendered code
126 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
128 // The same as above... ^
130 if ($NEW_LINE) echo "\n";
134 // Huh, something goes wrong or maybe you have edited config.php ???
135 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", OUTPUT_MODE));
136 MXCHANGE_DIE("<STRONG>".FATAL_ERROR.":</STRONG> ".LANG_NO_RENDER_DIRECT);
139 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
140 // Headers already sent?
141 if (headers_sent()) {
143 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
145 // Output debug trace
146 print("<stron>Headers are already sent!</strong><br />\n");
147 print("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
148 debug_print_backtrace();
149 die("</pre>Thank you for your help finding bugs.");
152 // Output cached HTML code
153 $OUTPUT = ob_get_contents();
155 // Clear output buffer for later output
159 header("HTTP/1.1 200");
162 $now = gmdate('D, d M Y H:i:s') . ' GMT';
164 // General headers for no caching
165 header("Expired: " . $now); // RFC2616 - Section 14.21
166 header("Last-Modified: " . $now);
167 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
168 header("Pragma: no-cache"); // HTTP/1.0
169 header("Connection: Close");
171 // Extension "rewrite" installed?
172 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
173 $OUTPUT = REWRITE_LINKS($OUTPUT);
176 // Compile and run finished rendered HTML code
177 while (strpos($OUTPUT, '{!') > 0) {
178 // Prepare the content and eval() it...
180 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
183 // Was that eval okay?
184 if (empty($newContent)) {
185 // Something went wrong!
186 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
188 $OUTPUT = $newContent;
191 // Output code here, DO NOT REMOVE! ;-)
193 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
194 // Rewrite links when rewrite extension is active
195 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
196 $OUTPUT = REWRITE_LINKS($OUTPUT);
199 // Compile and run finished rendered HTML code
200 while (strpos($OUTPUT, '{!') > 0) {
201 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
205 // Output code here, DO NOT REMOVE! ;-)
210 // Output the raw HTML code
211 function OUTPUT_RAW ($HTML) {
212 // Output stripped HTML code to avoid broken JavaScript code, etc.
213 echo stripslashes(stripslashes($HTML));
215 // Flush the output if only _OB_CACHING is not "on"
216 if (_OB_CACHING != "on") {
222 // Add a fatal error message to the queue array
223 function ADD_FATAL ($message, $extra="") {
227 // Regular text message to add to $FATAL
230 // $message is text with a mask plus extras to insert into the text
231 $message = sprintf($message, $extra);
235 // Log fatal messages away
236 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
239 // Load a template file and return it's content (only it's name; do not use ' or ")
240 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
241 // Add more variables which you want to use in your template files
242 global $DATA, $_CONFIG, $username;
244 // Make all template names lowercase
245 $template = strtolower($template);
247 // Count the template load
248 incrementConfigEntry('num_templates');
250 // Prepare IP number and User Agent
251 $REMOTE_ADDR = GET_REMOTE_ADDR();
252 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
253 $HTTP_USER_AGENT = GET_USER_AGENT();
257 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
259 // @DEPRECATED Try to rewrite the if() condition
260 if ($template == "member_support_form") {
261 // Support request of a member
262 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
263 array($GLOBALS['userid']), __FILE__, __LINE__);
265 // Is content an array?
266 if (is_array($content)) {
268 $content = merge_array($content, SQL_FETCHARRAY($result));
271 $content['gender'] = TRANSLATE_GENDER($content['gender']);
273 // DEPRECATED: Load data in direct variables
274 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
277 $gender = TRANSLATE_GENDER($gender);
278 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
282 SQL_FREERESULT($result);
285 // Generate date/time string
286 $date_time = MAKE_DATETIME(time(), "1");
289 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
292 // Check for admin/guest/member templates
293 if (strpos($template, "admin_") > -1) {
294 // Admin template found
296 } elseif (strpos($template, "guest_") > -1) {
297 // Guest template found
299 } elseif (strpos($template, "member_") > -1) {
300 // Member template found
302 } elseif (strpos($template, "install_") > -1) {
303 // Installation template found
305 } elseif (strpos($template, "ext_") > -1) {
306 // Extension template found
308 } elseif (strpos($template, "la_") > -1) {
309 // "Logical-area" template found
312 // Test for extension
313 $test = substr($template, 0, strpos($template, "_"));
314 if (EXT_IS_ACTIVE($test)) {
315 // Set extra path to extension's name
320 ////////////////////////
321 // Generate file name //
322 ////////////////////////
323 $file = $BASE.$MODE.$template.".tpl";
325 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
326 // Select what depended header/footer template file for admin/guest/member area
327 $file2 = sprintf("%s%s%s_%s.tpl",
331 SQL_ESCAPE($GLOBALS['what'])
335 if (FILE_READABLE($file2)) $file = $file2;
337 // Remove variable from memory
341 // Does the special template exists?
342 if (!FILE_READABLE($file)) {
343 // Reset to default template
344 $file = $BASE.$template.".tpl";
347 // Now does the final template exists?
348 if (FILE_READABLE($file)) {
349 // The local file does exists so we load it. :)
350 $tmpl_file = implode("", file($file));
352 // Replace ' to our own chars to preventing them being quoted
353 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
355 // Do we have to compile the code?
357 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
359 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
362 // Simply return loaded code
366 // Add surrounding HTML comments to help finding bugs faster
367 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
368 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
369 // Only admins shall see this warning or when installation mode is active
370 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
371 (".basename($file).")<br />
374 <pre>".print_r($content, true)."</pre>
376 <pre>".print_r($DATA, true)."</pre>
380 // Remove content and data
384 // Do we have some content to output or return?
386 // Not empty so let's put it out! ;)
388 // Return the HTML code
394 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
395 // Warning, empty output!
396 return "E:".$template."<br />\n";
400 // Send mail out to an email address
401 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
402 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
404 // Compile subject line (for POINTS constant etc.)
405 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
409 if ((!eregi("@", $TO)) && ($TO > 0)) {
410 // Value detected, is the message extension installed?
411 if (EXT_IS_ACTIVE("msg")) {
412 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
415 // Load email address
416 $result_email = SQL_QUERY_ESC("SELECT email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
417 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
419 // Does the user exist?
420 if (SQL_NUMROWS($result_email)) {
421 // Load email address
422 list($TO) = SQL_FETCHROW($result_email);
429 SQL_FREERESULT($result_email);
431 } elseif ("$TO" == "0") {
435 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
437 // Check for PHPMailer or debug-mode
438 if (!CHECK_PHPMAILER_USAGE()) {
439 // Not in PHPMailer-Mode
441 // Load email header template
442 $FROM = LOAD_EMAIL_TEMPLATE("header");
445 $FROM .= LOAD_EMAIL_TEMPLATE("header");
447 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
449 // Load email header template
450 $FROM = LOAD_EMAIL_TEMPLATE("header");
453 $FROM .= LOAD_EMAIL_TEMPLATE("header");
458 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
462 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
465 // Fix HTML parameter (default is no!)
466 if (empty($HTML)) $HTML = "N";
467 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
468 // In debug mode we want to display the mail instead of sending it away so we can debug this part
470 ".htmlentities(trim($FROM))."
472 Subject : ".$SUBJECT."
475 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
476 // Send mail as HTML away
477 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
478 } elseif (!empty($TO)) {
480 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
481 } elseif ($HTML == "N") {
483 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
487 // Check if legacy or PHPMailer command
489 function CHECK_PHPMAILER_USAGE() {
490 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
494 * Send out a raw email with PHPMailer class or legacy mail() command
496 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
497 // Shall we use PHPMailer class or legacy mode?
498 if (CHECK_PHPMAILER_USAGE()) {
499 // Use PHPMailer class with SMTP enabled
500 require_once(PATH."inc/phpmailer/class.phpmailer.php");
501 require_once(PATH."inc/phpmailer/class.smtp.php");
504 $mail = new PHPMailer();
505 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
508 $mail->SMTPAuth = true;
509 $mail->Host = SMTP_HOSTNAME;
511 $mail->Username = SMTP_USER;
512 $mail->Password = SMTP_PASSWORD;
514 $mail->From = WEBMASTER;
518 $mail->FromName = MAIN_TITLE;
519 $mail->Subject = $subject;
520 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
522 $mail->AltBody = "Your mail program required HTML support to read this mail!";
523 $mail->WordWrap = 70;
526 $mail->Body = html_entity_decode($msg);
528 $mail->AddAddress($to, "");
529 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
530 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
531 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
534 // Use legacy mail() command
535 @mail($to, $subject, html_entity_decode($msg), $from);
540 // Generate a password in a specified length or use default password length
541 function GEN_PASS ($LEN = 0) {
542 // Auto-fix invalid length of zero
543 if ($LEN == 0) $LEN = getConfig('pass_len');
545 // Initialize array with all allowed chars
546 $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,-,+,_,/");
548 // Initialize randomizer
549 mt_srand((double) microtime() * 1000000);
551 // Start creating password
553 for ($i = 0; $i < $LEN; $i++) {
554 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
557 // When the size is below 40 we can also add additional security by scrambling it
558 if (strlen($PASS) <= 40) {
559 // Also scramble the password
560 $PASS = scrambleString($PASS);
563 // Return the password
567 function MAKE_DATETIME ($time, $mode="0")
571 return NEVER_HAPPENED;
573 // Filter out numbers
574 $time = bigintval($time);
577 switch (GET_LANGUAGE())
579 case "de": // German date / time format
581 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
582 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
583 case "2": $ret = date("d.m.Y|H:i", $time); break;
584 case "3": $ret = date("d.m.Y", $time); break;
586 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
591 default: // Default is the US date / time format!
593 case "0": $ret = date("r", $time); break;
594 case "1": $ret = date("Y-m-d - g:i A", $time); break;
595 case "2": $ret = date("y-m-d|H:i", $time); break;
596 case "3": $ret = date("y-m-d", $time); break;
598 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
605 // Translates the american decimal dot into a german comma
606 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
609 // Default is 3 you can change this in admin area "Misc -> Misc Options"
610 if (getConfig('max_comma') == null) $_CONFIG['max_comma'] = "3";
612 // Use from config is default
613 $maxComma = getConfig('max_comma');
615 // Use from parameter?
616 if ($max > 0) $maxComma = $max;
619 if (($cut) && ($max == 0)) {
620 // Test for commata if in cut-mode
621 $com = explode(".", $dotted);
622 if (count($com) < 2) {
623 // Don't display commatas even if there are none... ;-)
629 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
632 switch (GET_LANGUAGE()) {
634 $dotted = number_format($dotted, $maxComma, ",", ".");
638 $dotted = number_format($dotted, $maxComma, ".", ",");
642 // Return translated value
647 function DEREFERER ($URL) {
648 // Don't de-refer our own links!
649 if (substr($URL, 0, strlen(URL)) != URL) {
650 // De-refer this link
651 $URL = URL."/modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
659 function TRANSLATE_GENDER ($gender) {
662 case "M": $ret = GENDER_M; break;
663 case "F": $ret = GENDER_F; break;
664 case "C": $ret = GENDER_C; break;
665 default : $ret = $gender; break;
670 function FRAMETESTER($URL) {
671 // Prepare frametester URL
672 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
674 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
676 return $frametesterUrl;
679 function SELECTION_COUNT($array) {
681 if (is_array($array)) {
682 foreach ($array as $key => $sel) {
683 if (!empty($sel)) $ret++;
689 function IMG_CODE ($code, $type, $DATA, $uid) {
690 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
693 function TRANSLATE_STATUS($status) {
697 $ret = ACCOUNT_UNCONFIRMED;
701 $ret = ACCOUNT_CONFIRMED;
705 $ret = ACCOUNT_LOCKED;
710 $ret = ACCOUNT_DELETED;
714 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
715 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
721 function GET_LANGUAGE() {
724 // Set default return value to default language from config
730 // Is the variable set
731 if (!empty($_GET['mx_lang'])) {
732 // Accept only first 2 chars
733 $lang = substr($_GET['mx_lang'], 0, 2);
734 } elseif (isset($cacheArray['language'])) {
736 $ret = $cacheArray['language'];
737 } elseif (!empty($lang)) {
738 // Check if main language file does exist
739 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
740 // Okay found, so let's update cookies
743 } elseif (!isSessionVariableSet('mx_lang')) {
744 // Return stored value from cookie
745 $ret = get_session('mx_lang');
747 // Fixes a warning before the session has the mx_lang constant
748 if (empty($ret)) $ret = DEFAULT_LANG;
752 $cacheArray['language'] = $ret;
758 function SET_LANGUAGE($lang) {
759 // Accept only first 2 chars!
760 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
763 set_session("mx_lang", $lang);
766 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
767 global $DATA, $REPLACER, $_CONFIG;
769 // Make sure all template names are lowercase!
770 $template = strtolower($template);
772 // Default "nickname" if extension is not installed
775 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
776 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
778 // Prepare IP number and User Agent
779 $REMOTE_ADDR = GET_REMOTE_ADDR();
780 $HTTP_USER_AGENT = GET_USER_AGENT();
785 // Is the admin logged in?
788 $aid = GET_CURRENT_ADMIN_ID();
791 $ADMIN = GET_ADMIN_EMAIL($aid);
794 // Neutral email address is default
797 // Expiration in a nice output format
798 if (getConfig('auto_purge') == 0) {
799 // Will never expire!
800 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
801 } elseif (function_exists('CREATE_FANCY_TIME')) {
802 // Create nice date string
803 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
806 $EXPIRATION = round(getConfig('auto_purge')/60/60/24)." "._DAYS;
809 // Is content an array?
810 if (is_array($content)) {
811 // Add expiration to array, $EXPIRATION is now deprecated!
812 $content['expiration'] = $EXPIRATION;
816 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
817 if (($UID > 0) && (is_array($content))) {
818 // If nickname extension is installed, fetch nickname as well
819 if (EXT_IS_ACTIVE("nickname")) {
820 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
822 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
823 array(bigintval($UID)), __FILE__, __LINE__);
825 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
827 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
828 array(bigintval($UID)), __FILE__, __LINE__);
831 // Fetch and merge data
832 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
833 $content = merge_array($content, SQL_FETCHARRAY($result));
834 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
837 SQL_FREERESULT($result);
840 // Translate M to male or F to female if present
841 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
843 // Overwrite email from data if present
844 if (isset($content['email'])) $email = $content['email'];
846 // Store email for some functions in global data array
847 $DATA['email'] = $email;
850 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
852 // Check for admin/guest/member templates
853 if (strpos($template, "admin_") > -1) {
854 // Admin template found
855 $file = $BASE."admin/".$template.".tpl";
856 } elseif (strpos($template, "guest_") > -1) {
857 // Guest template found
858 $file = $BASE."guest/".$template.".tpl";
859 } elseif (strpos($template, "member_") > -1) {
860 // Member template found
861 $file = $BASE."member/".$template.".tpl";
863 // Test for extension
864 $test = substr($template, 0, strpos($template, "_"));
865 if (EXT_IS_ACTIVE($test)) {
866 // Set extra path to extension's name
867 $file = $BASE.$test."/".$template.".tpl";
869 // No special filename
870 $file = $BASE.$template.".tpl";
874 // Does the special template exists?
875 if (!FILE_READABLE($file)) {
876 // Reset to default template
877 $file = $BASE.$template.".tpl";
880 // Now does the final template exists?
882 if (FILE_READABLE($file)) {
883 // The local file does exists so we load it. :)
884 $tmpl_file = implode("", file($file));
885 $tmpl_file = addslashes($tmpl_file);
888 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
890 } elseif (!empty($template)) {
891 // Template file not found!
892 $newContent = TEMPLATE_404.": ".$template."<br />
894 <pre>".print_r($content, true)."</pre>
896 <pre>".print_r($DATA, true)."</pre>
899 // Debug mode not active? Then remove the HTML tags
900 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
902 // No template name supplied!
903 $newContent = NO_TEMPLATE_SUPPLIED;
906 // Is there some content?
907 if (empty($newContent)) {
909 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
910 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
913 // Remove content and data
917 // Return compiled content
918 return COMPILE_CODE($newContent);
921 function MAKE_TIME($H, $M, $S, $stamp) {
922 // Extract day, month and year from given timestamp
923 $DAY = date("d", $stamp);
924 $MONTH = date("m", $stamp);
925 $YEAR = date('Y', $stamp);
927 // Create timestamp for wished time which depends on extracted date
928 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
931 function LOAD_URL($URL, $addUrlData=true) {
932 global $CSS, $footer;
934 // Compile out URI codes
935 $URL = COMPILE_CODE($URL);
937 // Check if http(s):// is there
938 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
939 // Make all URLs full-qualified
946 debug_print_backtrace();
949 $OUTPUT = ob_get_contents();
951 // Clear it only if there is content
952 if (!empty($OUTPUT)) {
956 // Add some data to URL if cookies are not accepted
957 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
959 // Probe for bot from search engine
960 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
961 // Search engine bot detected so let's rewrite many chars for the link
962 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
964 // Output new location link as anchor
965 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
966 } elseif (!headers_sent()) {
967 // Load URL when headers are not sent
970 debug_print_backtrace();
971 die("</pre>URL={$URL}");
973 @header ("Location: ".str_replace("&", "&", $URL));
975 // Output error message
976 include(PATH."inc/header.php");
977 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
978 include(PATH."inc/footer.php");
983 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
984 global $SEC_CHARS, $URL_CHARS;
985 // Is the code a string?
986 if (!is_string($code)) {
987 // Silently return it
993 // Select smaller set of chars to replace when we e.g. want to compile URLs
994 if (!$full) $ARRAY = $URL_CHARS;
998 // BEFORE 0.2.1 : Language and data constants
999 // WITH 0.2.1+ : Only language constants
1000 $code = str_replace('{--','".', str_replace('--}','."', $code));
1002 // BEFORE 0.2.1 : Not used
1003 // WITH 0.2.1+ : Data constants
1004 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1007 // Compile QUOT and other non-HTML codes
1008 foreach ($ARRAY['to'] as $k => $to) {
1009 // Do the reversed thing as in inc/libs/security_functions.php
1010 $code = str_replace($to, $ARRAY['from'][$k], $code);
1013 // But shall I keep simple quotes for later use?
1014 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1016 // Find $content[bla][blub] entries
1017 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1019 // Are some matches found?
1020 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1021 // Replace all matches
1022 $matchesFound = array();
1023 foreach ($matches[0] as $key => $match) {
1024 // Fuzzy look has failed by default
1025 $fuzzyFound = false;
1027 // Fuzzy look on match if already found
1028 foreach ($matchesFound as $found => $set) {
1030 $test = substr($found, 0, strlen($match));
1032 // Does this entry exist?
1033 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1034 if ($test == $match) {
1036 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1043 if ($fuzzyFound) continue;
1045 // Take all string elements
1046 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1047 // Replace it in the code
1048 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1049 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1050 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1051 $matchesFound[$key."_".$matches[4][$key]] = 1;
1052 $matchesFound[$match] = 1;
1053 } elseif (!isset($matchesFound[$match])) {
1054 // Not yet replaced!
1055 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1056 $code = str_replace($match, "\".".$match.".\"", $code);
1057 $matchesFound[$match] = 1;
1062 // Return compiled code
1066 /************************************************************************
1068 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1069 * $a_sort sortiert: *
1071 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1072 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1073 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1074 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1075 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1077 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1078 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1079 * Sie, dass es doch nicht so schwer ist! :-) *
1081 ************************************************************************/
1082 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1085 while ($primary_key < count($a_sort)) {
1086 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1087 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1090 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1091 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1092 } elseif ($key != $key2) {
1093 // Sort numbers (E.g.: 9 < 10)
1094 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1095 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1099 // We have found two different values, so let's sort whole array
1100 foreach ($dummy as $sort_key => $sort_val) {
1101 $t = $dummy[$sort_key][$key];
1102 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1103 $dummy[$sort_key][$key2] = $t;
1114 // Write back sorted array
1118 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1119 global $MONTH_DESCR;
1122 if ($type == "yn") {
1123 // This is a yes/no selection only!
1124 if ($id > 0) $prefix .= "[".$id."]";
1125 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1127 // Begin with regular selection box here
1128 if (!empty($prefix)) $prefix .= "_";
1130 if ($id > 0) $type2 .= "[".$id."]";
1131 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1136 for ($idx = 1; $idx < 32; $idx++) {
1137 $OUT .= "<OPTION value=\"".$idx."\"";
1138 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1139 $OUT .= ">".$idx."</OPTION>\n";
1143 case "month": // Month
1144 foreach ($MONTH_DESCR as $month => $descr) {
1145 $OUT .= "<OPTION value=\"".$month."\"";
1146 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1147 $OUT .= ">".$descr."</OPTION>\n";
1151 case "year": // Year
1153 $YEAR = date('Y', time());
1155 // Use configured min age or fixed?
1156 if (GET_EXT_VERSION("other") >= "0.2.1") {
1158 $startYear = $YEAR - getConfig('min_age');
1161 $startYear = $YEAR - 16;
1164 // Calculate earliest year (100 years old people can still enter Internet???)
1165 $minYear = $YEAR - 100;
1167 // Check if the default value is larger than minimum and bigger than actual year
1168 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1169 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1170 $OUT .= "<OPTION value=\"".$idx."\"";
1171 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1172 $OUT .= ">".$idx."</OPTION>\n";
1174 } elseif ($DEFAULT == -1) {
1175 // Current year minus 1
1176 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1178 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1181 // Get current year and subtract the configured minimum age
1182 $OUT .= "<OPTION value=\"".($minYear - 1)."\"><".$minYear."</OPTION>\n";
1183 // Calculate earliest year depending on extension version
1184 if (GET_EXT_VERSION("other") >= "0.2.1") {
1185 // Use configured minimum age
1186 $YEAR = date('Y', time()) - getConfig('min_age');
1188 // Use fixed 16 years age
1189 $YEAR = date('Y', time()) - 16;
1192 // Construct year selection list
1193 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1194 $OUT .= "<OPTION value=\"".$idx."\"";
1195 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1196 $OUT .= ">".$idx."</OPTION>\n";
1203 for ($idx = 0; $idx < 60; $idx+=5) {
1204 if (strlen($idx) == 1) $idx = "0".$idx;
1205 $OUT .= "<OPTION value=\"".$idx."\"";
1206 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1207 $OUT .= ">".$idx."</OPTION>\n";
1212 for ($idx = 0; $idx < 24; $idx++) {
1213 if (strlen($idx) == 1) $idx = "0".$idx;
1214 $OUT .= "<OPTION value=\"".$idx."\"";
1215 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1216 $OUT .= ">".$idx."</OPTION>\n";
1221 $OUT .= "<OPTION value=\"Y\"";
1222 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1223 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1224 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1225 $OUT .= ">".NO."</OPTION>\n";
1228 $OUT .= " </SELECT>\n";
1232 function TRANSLATE_YESNO($yn)
1236 case "Y": $yn = YES; break;
1237 case "N": $yn = NO; break;
1238 default : $yn = "??? (".$yn.")"; break;
1243 // Deprecated : $length
1246 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1247 // Fix missing _MAX constant
1248 if (!defined('_MAX')) define('_MAX', 15235);
1250 // Build server string
1251 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1254 $keys = SITE_KEY.":".DATE_KEY;
1255 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1256 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1257 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1258 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1260 // Build string from misc data
1261 $data = $code.":".$uid.":".$DATA;
1263 // Add more additional data
1264 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1265 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1266 if (isSessionVariableSet('lifetime')) $data .= ":".get_session('lifetime');
1267 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1268 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1269 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1271 // Calculate number for generating the code
1272 $a = $code + _ADD - 1;
1274 if (getConfig('master_hash') != null) {
1275 // Generate hash with master salt from modula of number with the prime number and other data
1276 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1278 // Create number from hash
1279 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1281 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1282 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1284 // Create number from hash
1285 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1288 // At least 10 numbers shall be secure enought!
1289 $len = getConfig('code_length');
1290 if ($len == 0) $len = $length;
1291 if ($len == 0) $len = 10;
1293 // Cut off requested counts of number
1294 $return = substr(str_replace('.', "", $rcode), 0, $len);
1296 // Done building code
1299 // Does only allow numbers
1300 function bigintval($num, $castValue = true) {
1301 // Filter all numbers out
1302 $ret = preg_replace("/[^0123456789]/", "", $num);
1305 if ($castValue) $ret = (double)$ret;
1307 // Has the whole value changed?
1308 if ("".$ret."" != "".$num."") {
1311 debug_print_backtrace();
1313 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1319 // Insert the code in $img_code into jpeg or PNG image
1320 function GENERATE_IMAGE($img_code, $header=true) {
1321 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1322 // Stop execution of function here because of over-sized code length
1324 } elseif (!$header) {
1325 // Return in an HTML code code
1326 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1330 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), getConfig('img_type'));
1331 if (FILE_READABLE($img)) {
1332 // Switch image type
1333 switch (getConfig('img_type'))
1336 // Okay, load image and hide all errors
1337 $image = @imagecreatefromjpeg($img);
1341 // Okay, load image and hide all errors
1342 $image = @imagecreatefrompng($img);
1346 // Exit function here
1350 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1351 $text_color = imagecolorallocate($image, 0, 0, 0);
1353 // Insert code into image
1354 imagestring($image, 5, 14, 2, $img_code, $text_color);
1356 // Return to browser
1357 header ("Content-Type: image/".getConfig('img_type'));
1359 // Output image with matching image factory
1360 switch (getConfig('img_type')) {
1361 case "jpg": imagejpeg($image); break;
1362 case "png": imagepng($image); break;
1365 // Remove image from memory
1366 imagedestroy($image);
1368 // Create selection box or array of splitted timestamp
1369 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1370 // Calculate 2-seconds timestamp
1371 $stamp = round($timestamp);
1372 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1374 // Do we have a leap year?
1376 $TEST = date('Y', time()) / 4;
1377 $M1 = date("m", time());
1378 $M2 = date("m", (time() + $timestamp));
1380 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1381 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1383 // First of all years...
1384 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1385 //* DEBUG: */ print("Y={$Y}<br />\n");
1387 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1388 //* DEBUG: */ print("M={$M}<br />\n");
1390 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1391 //* DEBUG: */ print("W={$W}<br />\n");
1393 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1394 //* DEBUG: */ print("D={$D}<br />\n");
1396 $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));
1397 //* DEBUG: */ print("h={$h}<br />\n");
1399 $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));
1400 //* DEBUG: */ print("m={$m}<br />\n");
1401 // And at last seconds...
1402 $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));
1403 //* DEBUG: */ print("s={$s}<br />\n");
1405 // Is seconds zero and time is < 60 seconds?
1406 if (($s == 0) && ($timestamp < 60)) {
1408 $s = round($timestamp);
1412 // Now we convert them in seconds...
1414 if ($return_array) {
1415 // Just put all data in an array for later use
1427 $OUT = "<DIV align=\"".$align."\">\n";
1428 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1431 if (ereg('Y', $display) || (empty($display))) {
1432 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1435 if (ereg("M", $display) || (empty($display))) {
1436 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1439 if (ereg("W", $display) || (empty($display))) {
1440 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1443 if (ereg("D", $display) || (empty($display))) {
1444 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1447 if (ereg("h", $display) || (empty($display))) {
1448 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1451 if (ereg("m", $display) || (empty($display))) {
1452 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1455 if (ereg("s", $display) || (empty($display))) {
1456 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1462 if (ereg('Y', $display) || (empty($display))) {
1463 // Generate year selection
1464 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1465 for ($idx = 0; $idx <= 10; $idx++) {
1466 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1467 if ($idx == $Y) $OUT .= " selected default";
1468 $OUT .= ">".$idx."</OPTION>\n";
1470 $OUT .= " </SELECT></TD>\n";
1472 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1475 if (ereg("M", $display) || (empty($display))) {
1476 // Generate month selection
1477 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1478 for ($idx = 0; $idx <= 11; $idx++)
1480 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1481 if ($idx == $M) $OUT .= " selected default";
1482 $OUT .= ">".$idx."</OPTION>\n";
1484 $OUT .= " </SELECT></TD>\n";
1486 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1489 if (ereg("W", $display) || (empty($display))) {
1490 // Generate week selection
1491 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1492 for ($idx = 0; $idx <= 4; $idx++) {
1493 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1494 if ($idx == $W) $OUT .= " selected default";
1495 $OUT .= ">".$idx."</OPTION>\n";
1497 $OUT .= " </SELECT></TD>\n";
1499 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1502 if (ereg("D", $display) || (empty($display))) {
1503 // Generate day selection
1504 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1505 for ($idx = 0; $idx <= 31; $idx++) {
1506 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1507 if ($idx == $D) $OUT .= " selected default";
1508 $OUT .= ">".$idx."</OPTION>\n";
1510 $OUT .= " </SELECT></TD>\n";
1512 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1515 if (ereg("h", $display) || (empty($display))) {
1516 // Generate hour selection
1517 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1518 for ($idx = 0; $idx <= 23; $idx++) {
1519 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1520 if ($idx == $h) $OUT .= " selected default";
1521 $OUT .= ">".$idx."</OPTION>\n";
1523 $OUT .= " </SELECT></TD>\n";
1525 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1528 if (ereg("m", $display) || (empty($display))) {
1529 // Generate minute selection
1530 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1531 for ($idx = 0; $idx <= 59; $idx++) {
1532 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1533 if ($idx == $m) $OUT .= " selected default";
1534 $OUT .= ">".$idx."</OPTION>\n";
1536 $OUT .= " </SELECT></TD>\n";
1538 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1541 if (ereg("s", $display) || (empty($display))) {
1542 // Generate second selection
1543 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1544 for ($idx = 0; $idx <= 59; $idx++) {
1545 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1546 if ($idx == $s) $OUT .= " selected default";
1547 $OUT .= ">".$idx."</OPTION>\n";
1549 $OUT .= " </SELECT></TD>\n";
1551 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1554 $OUT .= "</TABLE>\n";
1556 // Return generated HTML code
1561 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1562 // Initial return value
1565 // Do we have a leap year?
1567 $TEST = date('Y', time()) / 4;
1568 $M1 = date("m", time());
1569 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1570 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1571 // First add years...
1572 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1574 $ret += $POST[$prefix."_mo"] * 2628000;
1576 $ret += $POST[$prefix."_we"] * 604800;
1578 $ret += $POST[$prefix."_da"] * 86400;
1580 $ret += $POST[$prefix."_ho"] * 3600;
1582 $ret += $POST[$prefix."_mi"] * 60;
1583 // And at last seconds...
1584 $ret += $POST[$prefix."_se"];
1585 // Return calculated value
1588 // Sends out mail to all administrators
1589 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1590 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1591 // Trim template name
1592 $template = trim($template);
1594 // Load email template
1595 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1597 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1598 // Older version detected!
1599 return SEND_ADMIN_EMAILS($subj, $msg);
1602 // Check which admin shall receive this mail
1603 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1604 array($template), __FILE__, __LINE__);
1605 if (SQL_NUMROWS($result) == 0) {
1606 // Create new entry (to all admins)
1607 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1608 array($template), __FILE__, __LINE__);
1610 // Load admin IDs...
1612 while(list($aid) = SQL_FETCHROW($result)) {
1617 SQL_FREERESULT($result);
1619 // "implode" IDs and query string
1620 $aid = implode(",", $aids);
1622 // Add line to userlog
1623 USERLOG_ADD_LINE($subj, $msg, $UID);
1625 } elseif ($aid == "0") {
1626 // Select all email adresses
1627 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1629 // If Admin-ID is not "to-all" select
1630 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1634 // Load email addresses and send away
1635 while (list($email) = SQL_FETCHROW($result)) {
1636 SEND_EMAIL($email, $subj, $msg);
1640 SQL_FREERESULT($result);
1643 function CREATE_FANCY_TIME ($stamp) {
1644 // Get data array with years/months/weeks/days/...
1645 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1647 foreach($data as $k => $v) {
1649 // Value is greater than 0 "eval" data to return string
1650 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1656 // Do we have something there?
1657 if (strlen($ret) > 0) {
1658 // Remove leading commata and space
1659 $ret = substr($ret, 2);
1662 $ret = "0 "._SECONDS;
1665 // Return fancy time string
1669 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1670 $SEP = ""; $TOP = "";
1673 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1677 for ($page = 1; $page <= $PAGES; $page++) {
1678 // Is the page currently selected or shall we generate a link to it?
1679 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1680 // Is currently selected, so only highlight it
1681 $NAV .= "<STRONG>-";
1683 // Open anchor tag and add base URL
1684 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1686 // Add userid when we shall show all mails from a single member
1687 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1689 // Close open anchor tag
1693 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1694 // Is currently selected, so only highlight it
1695 $NAV .= "-</STRONG>";
1701 // Add seperator if we have not yet reached total pages
1702 if ($page < $PAGES) $NAV .= " | ";
1705 // Define constants only once
1706 if (!defined('__NAV_OUTPUT')) {
1707 define('__NAV_OUTPUT' , $NAV);
1708 define('__NAV_COLSPAN', $colspan);
1709 define('__NAV_TOP' , $TOP);
1710 define('__NAV_SEP' , $SEP);
1713 // Load navigation template
1714 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1717 // Return generated HTML-Code
1725 // Extract host from script name
1726 function EXTRACT_HOST (&$script) {
1727 // Use default SERVER_URL by default... ;) So?
1730 // Is this URL valid?
1731 if (substr($script, 0, 7) == "http://") {
1732 // Use the hostname from script URL as new hostname
1733 $url = substr($script, 7);
1734 $extract = explode("/", $url);
1736 // Done extracting the URL :)
1739 // Extract host name
1740 $host = str_replace("http://", "", $url);
1741 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1743 // Generate relative URL
1744 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1745 if (substr(strtolower($script), 0, 7) == "http://") {
1746 // But only if http:// is in front!
1747 $script = substr($script, (strlen($url) + 7));
1748 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1750 $script = substr($script, (strlen($url) + 8));
1753 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1754 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1760 // Send a GET request
1761 function GET_URL ($script) {
1762 // Compile the script name
1763 $script = COMPILE_CODE($script);
1765 // Extract host name from script
1766 $host = EXTRACT_HOST($script);
1768 // Generate GET request header
1769 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1770 $request .= "Host: " . $host . "\r\n";
1771 $request .= "Referer: " . URL . "/admin.php\r\n";
1772 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1773 $request .= "Content-Type: text/plain\r\n";
1774 $request .= "Cache-Control: no-cache\r\n";
1775 $request .= "Connection: Close\r\n\r\n";
1777 // Send the raw request
1778 $response = SEND_RAW_REQUEST($host, $request);
1780 // Return the result to the caller function
1784 // Send a POST request
1785 function POST_URL ($script, $postData) {
1786 // Is postData an array?
1787 if (!is_array($postData)) {
1789 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1790 return array("", "", "");
1793 // Compile the script name
1794 $script = COMPILE_CODE($script);
1796 // Extract host name from script
1797 $host = EXTRACT_HOST($script);
1799 // Construct request
1800 $data = http_build_query($postData, '','&');
1802 // Generate POST request header
1803 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1804 $request .= "Host: " . $host . "\r\n";
1805 $request .= "Referer: " . URL . "/admin.php\r\n";
1806 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1807 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1808 $request .= "Content-length: " . strlen($data) . "\r\n";
1809 $request .= "Cache-Control: no-cache\r\n";
1810 $request .= "Connection: Close\r\n\r\n";
1813 // Send the raw request
1814 $response = SEND_RAW_REQUEST($host, $request);
1816 // Return the result to the caller function
1820 // Sends a raw request to another host
1821 function SEND_RAW_REQUEST ($host, $request) {
1823 $response = array("", "", "");
1825 // Default is not to use proxy
1828 // Are proxy settins set?
1829 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1835 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1837 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1839 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1843 if (!is_resource($fp)) {
1850 // Generate CONNECT request header
1851 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1852 $proxyTunnel .= "Host: ".$host."\r\n";
1854 // Use login data to proxy? (username at least!)
1855 if (getConfig('proxy_username') != "") {
1857 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1858 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1861 // Add last new-line
1862 $proxyTunnel .= "\r\n";
1863 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1866 fputs($fp, $proxyTunnel);
1870 // No response received
1874 // Read the first line
1875 $resp = trim(fgets($fp, 10240));
1876 $respArray = explode(" ", $resp);
1877 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1878 // Invalid response!
1884 fputs($fp, $request);
1888 $response[] = trim(fgets($fp, 1024));
1894 // Skip first empty lines
1896 foreach ($resp as $idx => $line) {
1898 $line = trim($line);
1900 // Is this line empty?
1903 array_shift($response);
1905 // Abort on first non-empty line
1910 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1912 // Proxy agent found?
1913 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1914 // Proxy header detected, so remove two lines
1915 array_shift($response);
1916 array_shift($response);
1919 // Was the request successfull?
1920 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1921 // Not found / access forbidden
1922 $response = array("", "", "");
1928 // Taken from www.php.net eregi() user comments
1929 function VALIDATE_EMAIL($email) {
1931 $email = COMPILE_CODE($email);
1933 // Check first part of email address
1934 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1937 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1940 $regex = "^".$first."@".$domain."$";
1942 // Return check result
1943 return eregi($regex, $email);
1945 // Function taken from user comments on www.php.net / function eregi()
1946 function VALIDATE_URL ($URL, $compile=true) {
1947 // Trim URL a little
1948 $URL = trim(urldecode($URL));
1949 //* DEBUG: */ echo $URL."<br />";
1951 // Compile some chars out...
1952 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1953 //* DEBUG: */ echo $URL."<br />";
1955 // Check for the extension filter
1956 if (EXT_IS_ACTIVE("filter")) {
1957 // Use the extension's filter set
1958 return FILTER_VALIDATE_URL($URL, false);
1961 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1962 // https:// in front of the URLs
1963 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1966 function MEMBER_ACTION_LINKS($uid, $status="") {
1967 // Define all main targets
1968 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1970 // Begin of navigation links
1971 $eval = "\$OUT = \"[ ";
1973 foreach ($TARGETS as $tar) {
1974 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1975 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1976 if (($tar == "lock_user") && ($status == "LOCKED")) {
1977 // Locked accounts shall be unlocked
1978 $eval .= "UNLOCK_USER";
1980 // All other status is fine
1981 $eval .= strtoupper($tar);
1983 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1984 if (($tar == "lock_user") && ($status == "LOCKED")) {
1985 // Locked accounts shall be unlocked
1986 $eval .= "UNLOCK_USER";
1988 // All other status is fine
1989 $eval .= strtoupper($tar);
1991 $eval .= ".\"</A></SPAN> | ";
1994 // Finish navigation link
1995 $eval = substr($eval, 0, -7)."]\";";
2001 // Function for backward-compatiblity
2002 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
2003 // Load it from the register extension
2004 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
2006 // Generate an email link
2007 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2008 // Default email link (INSECURE! Spammer can read this by harvester programs)
2009 $EMAIL = "mailto:".$email;
2011 // Check for several extensions
2012 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2013 // Create email link for contacting admin in guest area
2014 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2015 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2016 // Create email link for contacting a member within admin area (or later in other areas, too?)
2017 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2018 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2019 // Create email link to contact sponsor within admin area (or like the link above?)
2020 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2023 // Shall I close the link when there is no admin?
2024 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2026 // Return email link
2029 // Generate a hash for extra-security for all passwords
2030 function generateHash ($plainText, $salt = "") {
2033 // Is the required extension "sql_patches" there and a salt is not given?
2034 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2035 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2036 return md5($plainText);
2039 // Do we miss an arry element here?
2040 if (getConfig('file_hash') == null) {
2042 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2043 debug_print_backtrace();
2047 // When the salt is empty build a new one, else use the first x configured characters as the salt
2049 // Build server string
2050 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2053 $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');
2056 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2058 // Calculate number for generating the code
2059 $a = time() + _ADD - 1;
2061 // Generate SHA1 sum from modula of number and the prime number
2062 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2063 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2064 $sha1 = scrambleString($sha1);
2065 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2066 //* DEBUG: */ $sha1b = descrambleString($sha1);
2067 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2069 // Generate the password salt string
2070 $salt = substr($sha1, 0, getConfig('salt_length'));
2071 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2074 $salt = substr($salt, 0, getConfig('salt_length'));
2075 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2079 return $salt.sha1($salt.$plainText);
2082 function scrambleString($str) {
2086 // Final check, in case of failture it will return unscrambled string
2087 if (strlen($str) > 40) {
2088 // The string is to long
2090 } elseif (strlen($str) == 40) {
2092 $scrambleNums = explode(":", getConfig('pass_scramble'));
2094 // Generate new numbers
2095 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2098 // Scramble string here
2099 //* DEBUG: */ echo "***Original=".$str."***<br />";
2100 for ($idx = 0; $idx < strlen($str); $idx++) {
2101 // Get char on scrambled position
2102 $char = substr($str, $scrambleNums[$idx], 1);
2104 // Add it to final output string
2105 $scrambled .= $char;
2108 // Return scrambled string
2109 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2113 function descrambleString($str) {
2114 // Scramble only 40 chars long strings
2115 if (strlen($str) != 40) return $str;
2117 // Load numbers from config
2118 $scrambleNums = explode(":", getConfig('pass_scramble'));
2121 if (count($scrambleNums) != 40) return $str;
2123 // Begin descrambling
2124 $orig = str_repeat(" ", 40);
2125 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2126 for ($idx = 0; $idx < 40; $idx++) {
2127 $char = substr($str, $idx, 1);
2128 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2131 // Return scrambled string
2132 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2136 function genScrambleString($len) {
2137 // Prepare randomizer and array for the numbers
2138 mt_srand((double) microtime() * 1000000);
2139 $scrambleNumbers = array();
2141 // First we need to setup randomized numbers from 0 to 31
2142 for ($idx = 0; $idx < $len; $idx++) {
2144 $rand = mt_rand(0, ($len -1));
2146 // Check for it by creating more numbers
2147 while (array_key_exists($rand, $scrambleNumbers)) {
2148 $rand = mt_rand(0, ($len -1));
2152 $scrambleNumbers[$rand] = $rand;
2155 // So let's create the string for storing it in database
2156 $scrambleString = implode(":", $scrambleNumbers);
2157 return $scrambleString;
2159 // Append data like session ID or referal ID to the given URL which would
2160 // normally be stored in cookies
2161 function ADD_URL_DATA ($URL) {
2165 // Determine URL binder
2167 if (strpos($URL, "?") !== false) $BIND = "&";
2169 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2170 // Cookies are not accepted
2171 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2172 // Cookie found in URL
2173 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2174 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2175 // Not found! So let's set default here
2176 $ADD .= $BIND."refid=".getConfig('def_refid');
2179 // Is there already added data? Then change the binder
2180 if (!empty($ADD)) $BIND = "&";
2183 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2184 // Add session from URL
2185 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2187 // Add current session
2188 $ADD .= $BIND."PHPSESSID=".session_id();
2192 // Add all together and return it
2195 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2196 function generatePassString($passHash) {
2197 // Return vanilla password hash
2200 // Is a secret key and master salt already initialized?
2201 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2202 // Only calculate when the secret key is generated
2203 $newHash = ""; $start = 9;
2204 for ($idx = 0; $idx < 10; $idx++) {
2205 $part1 = hexdec(substr($passHash, $start, 4));
2206 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2207 $mod = dechex($idx);
2208 if ($part1 > $part2) {
2209 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2210 } elseif ($part2 > $part1) {
2211 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2213 $mod = substr(round($mod), 0, 4);
2214 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2215 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2220 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2221 $ret = generateHash($newHash, getConfig('master_salt'));
2222 //* DEBUG: */ print($ret."<br />\n");
2225 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2226 $ret = md5($passHash);
2227 //* DEBUG: */ echo "++".$ret."++<br />\n";
2234 // Fix "deleted" cookies
2235 function FIX_DELETED_COOKIES ($cookies) {
2236 // Is this an array with entries?
2237 if ((is_array($cookies)) && (count($cookies) > 0)) {
2238 // Then check all cookies if they are marked as deleted!
2239 foreach ($cookies as $cookieName) {
2240 // Is the cookie set to "deleted"?
2241 if (get_session($cookieName) == "deleted") {
2242 set_session($cookieName, "");
2248 // Output error messages in a fasioned way and die...
2249 function mxchange_die ($msg) {
2252 // Load the message template
2253 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2256 include(PATH."inc/footer.php");
2262 // Display parsing time and number of SQL queries in footer
2263 function DISPLAY_PARSING_TIME_FOOTER() {
2264 // Is the timer started?
2265 if (!isset($GLOBALS['startTime'])) {
2271 $endTime = microtime(true);
2273 // "Explode" both times
2274 $start = explode(" ", $GLOBALS['startTime']);
2275 $end = explode(" ", $endTime);
2276 $runTime = $end[0] - $start[0];
2277 if ($runTime < 0) $runTime = 0;
2278 $runTime = TRANSLATE_COMMA($runTime);
2282 'runtime' => $runTime,
2283 'numSQLs' => (getConfig('sql_count') + 1),
2284 'numTemplates' => (getConfig('num_templates') + 1)
2287 // Load the template
2288 LOAD_TEMPLATE("show_timings", false, $content);
2291 // Unset/set session variables
2292 function set_session ($var, $value) {
2295 // Abort in CSS mode here
2296 if ($CSS == 1) return true;
2298 // Trim value and session variable
2299 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2301 // Is the session variable set?
2302 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2303 // Remove the session
2304 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2305 unset($_SESSION[$var]);
2306 return session_unregister($var);
2307 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2309 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2310 $_SESSION[$var] = $value;
2311 return session_register($var);
2312 } elseif (!empty($value)) {
2314 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2315 $_SESSION[$var] = $value;
2319 // Ignored (but valid)
2320 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2324 // Check wether a boolean constant is set
2325 // Taken from user comments in PHP documentation for function constant()
2326 function isBooleanConstantAndTrue($constName) { // : Boolean
2329 // Failed by default
2333 if (isset($cacheArray['const'][$constName])) {
2335 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2336 $res = $cacheArray['const'][$constName];
2339 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2340 if (defined($constName)) $res = (constant($constName) === true);
2343 $cacheArray['const'][$constName] = $res;
2345 //* DEBUG: */ var_dump($res);
2351 // Check wether a session variable is set
2352 function isSessionVariableSet ($var) {
2353 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2354 return (isset($_SESSION[$var]));
2356 // Returns wether the value of the session variable or NULL if not set
2357 function get_session ($var) {
2360 // Default is not found! ;-)
2363 // Is the variable there or cached values?
2364 if (isset($cacheArray['session'][$var])) {
2365 // Get cached value (skips a lot SQL_ESCAPE() calles!
2366 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2367 $value = $cacheArray['session'][$var];
2368 } elseif (isSessionVariableSet($var)) {
2369 // Then get it secured!
2370 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2371 $value = SQL_ESCAPE($_SESSION[$var]);
2374 $cacheArray['session'][$var] = $value;
2380 // Send notification to admin
2381 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2382 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2384 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2386 // Send outdated way
2387 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2388 SEND_ADMIN_EMAILS($subject, $msg);
2391 // Destroy user session
2392 function destroy_user_session () {
2393 // Remove all user data from session
2394 return ((set_session("userid", "")) && (set_session("u_hash", "")) && (set_session("lifetime", "")));
2396 // Merges an array together but only if both are arrays
2397 function merge_array ($array1, $array2) {
2398 // Are both an array?
2399 if ((is_array($array1)) && (is_array($array2))) {
2400 // Merge all together
2401 return array_merge($array1, $array2);
2402 } elseif (is_array($array1)) {
2403 // Return left array
2407 // Something wired happened here...
2408 print(__FUNCTION__.":<pre>");
2409 debug_print_backtrace();
2412 // Debug message logger
2413 function DEBUG_LOG ($file, $line, $message, $force=true) {
2414 // Is debug mode enabled?
2415 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2416 // Log this message away
2417 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2418 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2422 // Reads a directory with PHP files in and gets only files back
2423 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2427 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2430 while ($baseFile = readdir($dirPointer)) {
2431 // Load file only if extension is active
2433 $file = $baseDir.$baseFile;
2435 // Is this a valid reset file?
2436 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2437 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2438 // Remove both for extension name
2439 $extName = substr($baseFile, strlen($prefix), -4);
2442 $extId = GET_EXT_ID($extName);
2444 // Is the extension valid and active?
2445 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2446 // Then add this file
2448 } elseif ($extId == 0) {
2449 // Add non-extension files as well
2456 closedir($dirPointer);
2461 // Return array with include files
2464 // Load more reset scripts
2465 function RESET_ADD_INCLUDES () {
2466 // Is the reset set or old sql_patches?
2467 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2472 // Get more daily reset scripts
2473 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2476 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2478 // Create current week mark
2479 $currWeek = date("W", time());
2482 if (getConfig('last_week') != $currWeek) {
2483 // Include weekly reset scripts
2484 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2487 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2490 // Create current month mark
2491 $currMonth = date("m", time());
2494 if (getConfig('last_month') != $currMonth) {
2495 // Include monthly reset scripts
2496 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2499 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2505 // Handle extra values
2506 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2507 // Default is the value itself
2510 // Do we have a special filter function?
2511 if (!empty($filterFunction)) {
2512 // Does the filter function exist?
2513 if (function_exists($filterFunction)) {
2514 // Do we have extra parameters here?
2515 if (!empty($extraValue)) {
2516 // Put both parameters in one new array by default
2517 $args = array($value, $extraValue);
2519 // If we have an array simply use it and pre-extend it with our value
2520 if (is_array($extraValue)) {
2521 // Make the new args array
2522 $args = merge_array(array($value), $extraValue);
2525 // Call the multi-parameter call-back
2526 $ret = call_user_func_array($filterFunction, $args);
2528 // One parameter call
2529 $ret = call_user_func($filterFunction, $value);
2537 // Check if given FQFN is a readable file
2538 function FILE_READABLE($fqfn) {
2540 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2542 // Converts timestamp selections into a timestamp
2543 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2544 // Init test variable
2547 // Get last three chars
2548 $test = substr($id, -3);
2550 // Improved way of checking! :-)
2551 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2552 // Found a multi-selection for timings?
2553 $test = substr($id, 0, -3);
2554 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)) {
2555 // Generate timestamp
2556 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2557 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2559 // Remove data from array
2560 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2561 unset($POST[$test."_".$rem]);
2565 unset($id); $skip = true; $test2 = $test;
2568 // Process this entry
2569 $skip = false; $test2 = "";
2572 // Reverts the german decimal comma into Computer decimal dot
2573 function REVERT_COMMA ($str) {
2574 // Default float is not a float... ;-)
2577 // Which language is selected?
2578 switch (GET_LANGUAGE()) {
2579 case "de": // German language
2580 // Remove german thousand dots first
2581 $str = str_replace(".", "", $str);
2583 // Replace german commata with decimal dot and cast it
2584 $float = (float)str_replace(",", ".", $str);
2587 default: // US and so on
2588 // Remove thousand dots first and cast
2589 $float = (float)str_replace(",", "", $str);
2596 // Handle menu-depending failed logins and return the rendered content
2597 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2598 // Default output is empty ;-)
2601 // Is the session data set?
2602 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2603 // Ignore zero values
2604 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2605 // Non-guest has login failtures found, get both data and prepare it for template
2606 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2608 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2609 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2613 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2616 // Reset session data
2617 set_session('mxchange_'.$accessLevel.'_failtures', "");
2618 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2621 // Return rendered content
2625 function REBUILD_CACHE ($cache, $inc="") {
2626 global $cacheInstance, $CSS;
2628 // Shall I remove the cache file?
2629 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2631 if ($cacheInstance->loadCacheFile($cache)) {
2633 $cacheInstance->destroyCacheFile();
2636 // Include file given?
2639 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2641 // Is the include there?
2642 if (FILE_READABLE($fqfn)) {
2643 // And rebuild it from scratch
2644 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2647 // Include not found!
2648 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2653 // Purge admin menu cache
2654 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2655 global $cacheInstance;
2657 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2658 if (!EXT_IS_ACTIVE("cache")) {
2659 // Cache extension not active
2661 } elseif (!is_object($cacheInstance)) {
2662 // No cache instance!
2663 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2665 } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2666 // Caching disabled (currently experiemental!)
2670 // Experiemental feature!
2671 trigger_error("You have to delete the admin_*.cache files by yourself at this point.");
2673 // Translates the "pool type" into human-readable
2674 function TRANSLATE_POOL_TYPE ($type) {
2675 // Default type is unknown
2676 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2678 // Generate constant
2679 $constName = sprintf("POOL_TYPE_%s", $type);
2682 if (defined($constName)) {
2684 $translated = constant($constName);
2687 // Return "translation"
2690 // "Getter" for remote IP number
2691 function GET_REMOTE_ADDR () {
2692 // Get remote ip from environment
2693 $remoteAddr = getenv('REMOTE_ADDR');
2695 // Is removeip installed?
2696 if (EXT_IS_ACTIVE("removeip")) {
2697 // Then anonymize it
2698 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2704 // "Getter" for remote hostname
2705 function GET_REMOTE_HOST () {
2706 // Get remote ip from environment
2707 $remoteHost = getenv('REMOTE_HOST');
2709 // Is removeip installed?
2710 if (EXT_IS_ACTIVE("removeip")) {
2711 // Then anonymize it
2712 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2718 // "Getter" for user agent
2719 function GET_USER_AGENT () {
2720 // Get remote ip from environment
2721 $userAgent = getenv('HTTP_USER_AGENT');
2723 // Is removeip installed?
2724 if (EXT_IS_ACTIVE("removeip")) {
2725 // Then anonymize it
2726 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2732 // "Getter" for referer
2733 function GET_REFERER () {
2734 // Get remote ip from environment
2735 $referer = getenv('HTTP_REFERER');
2737 // Is removeip installed?
2738 if (EXT_IS_ACTIVE("removeip")) {
2739 // Then anonymize it
2740 $referer = GET_ANONYMOUS_REFERER($referer);
2747 // Adds a bonus mail to the queue
2748 // This is a high-level function!
2749 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2750 // Use mode from data if not set and availble ;-)
2751 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2753 // Generate receiver list
2754 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2757 if (!empty($RECEIVER)) {
2758 // Add bonus mail to queue
2759 ADD_BONUS_MAIL_TO_QUEUE(
2771 // Mail inserted into bonus pool
2772 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2773 } elseif ($output) {
2774 // More entered than can be reached!
2775 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2778 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2781 // Determines referal id and sets it
2782 function DETERMINE_REFID () {
2783 global $CLICK, $_SERVER;
2785 // Check if refid is set
2786 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2787 // The variable user comes from the click-counter script click.php and we only accept this here
2788 $GLOBALS['refid'] = bigintval($_GET['user']);
2789 } elseif (!empty($_POST['refid'])) {
2790 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2791 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2792 } elseif (!empty($_GET['refid'])) {
2793 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2794 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2795 } elseif (!empty($_GET['ref'])) {
2796 // Set refid=ref (the referal link uses such variable)
2797 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2798 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2799 // Set session refid als global
2800 $GLOBALS['refid'] = bigintval(get_session('refid'));
2801 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2802 // Set default refid as refid in URL
2803 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2804 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2805 // Select a random user which has confirmed enougth mails
2806 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2808 // No default ID when sql_patches is not installed or none set
2809 $GLOBALS['refid'] = 0;
2812 // Set cookie when default refid > 0
2813 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2815 set_session('refid', $GLOBALS['refid']);
2818 // Return determined refid
2819 return $GLOBALS['refid'];
2822 // Destroys the admin session
2823 function DESTROY_ADMIN_SESSION ($destroy = true) {
2824 // Kill maybe existing session variables including array elements
2825 set_session('admin_login', "");
2826 set_session('admin_md5' , "");
2827 set_session('admin_last' , "");
2828 set_session('admin_to' , "");
2830 // Destroy session and return status
2832 return @session_destroy();
2835 // All fine if we shall not really destroy the session
2839 // Checks if a given apache module is loaded
2840 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2841 // Check it and return result
2842 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2845 // Getter for $_CONFIG entries
2846 function getConfig ($entry) {
2852 // Is the entry there?
2853 if (isset($_CONFIG[$entry])) {
2855 $value = $_CONFIG[$entry];
2862 // @TODO Rewrite all language constants to the function getLanguage().
2863 // "Getter" for language strings
2864 function getMessage ($messageId) {
2865 // Default is not found!
2866 $return = "!".$messageId."!";
2868 // Is the language string found?
2869 if (isset($GLOBALS['msg'][$messageId])) {
2870 // Language array element found
2871 $return = $GLOBALS['msg'][$messageId];
2872 } elseif (defined($messageId)) {
2873 // @DEPRECATED Deprecated constant found
2874 $return = constant($messageId);
2876 // Missing language constant
2877 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2880 // Return the string
2884 // Get current theme name
2885 function GET_CURR_THEME() {
2886 global $INC_POOL, $CSS, $cacheArray;
2888 // The default theme is 'default'... ;-)
2891 // Load default theme if not empty from configuration
2892 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2894 if (!isSessionVariableSet('mxchange_theme')) {
2895 // Set default theme
2896 set_session("mxchange_theme", $ret);
2897 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2898 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2899 // Get theme from cookie
2900 $ret = get_session('mxchange_theme');
2903 if (THEME_GET_ID($ret) == 0) {
2904 // Fix it to default
2907 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2908 // Prepare FQFN for checking
2909 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_GET['theme']));
2911 // Installation mode active
2912 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2913 // Set cookie from URL data
2914 set_session("mxchange_theme", SQL_ESCAPE($_GET['theme']));
2915 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_POST['theme'])))) {
2916 // Set cookie from posted data
2917 set_session("mxchange_theme", SQL_ESCAPE($_POST['theme']));
2921 $ret = get_session('mxchange_theme');
2923 // Invalid design, reset cookie
2924 set_session("mxchange_theme", $ret);
2927 // Add (maybe) found theme.php file to inclusion list
2928 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($ret));
2930 // Try to load the requested include file
2931 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2933 // Return theme value
2937 // Get id from theme
2938 function THEME_GET_ID ($name) {
2941 // Is the extension "theme" installed?
2942 if (!EXT_IS_ACTIVE("theme")) {
2950 // Is the cache entry there?
2951 if (isset($cacheArray['themes']['id'][$name])) {
2952 // Get the version from cache
2953 $id = $cacheArray['themes']['id'][$name];
2956 incrementConfigEntry('cache_hits');
2957 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2958 // Check if current theme is already imported or not
2959 $result = SQL_QUERY_ESC("SELECT id FROM `"._MYSQL_PREFIX."_themes` WHERE theme_path='%s' LIMIT 1",
2960 array($name), __FILE__, __LINE__);
2963 if (SQL_NUMROWS($result) == 1) {
2965 list($id) = SQL_FETCHROW($result);
2969 SQL_FREERESULT($result);
2976 // Increment or init with 1 the given config entry
2977 function incrementConfigEntry ($configEntry) {
2980 // Increment it if set or init it with 1
2981 if (getConfig($configEntry) > 0) { $_CONFIG[$configEntry]++; } else { $_CONFIG[$configEntry] = 1; }
2984 //////////////////////////////////////////////////
2986 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
2988 //////////////////////////////////////////////////
2990 if (!function_exists('html_entity_decode')) {
2991 // Taken from documentation on www.php.net
2992 function html_entity_decode ($string) {
2993 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
2994 $trans_tbl = array_flip($trans_tbl);
2995 return strtr($string, $trans_tbl);