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") {
57 // Close all other files
62 // Open a table (you may want to add some header stuff here)
64 function OPEN_TABLE ($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
67 // Count tables so we can generate CSS classes for every table... :-)
69 // Class is empty so count one up and create a class
70 $table_cnt++; $CLASS = "class".$table_cnt;
72 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
74 // Shall I add the classes to TABLE and TD or only to TD?
75 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
78 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
81 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
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."\">";
91 // Close a table (you may want to add some footer stuff here)
93 function CLOSE_TABLE( $ADD="") {
94 OUTPUT_HTML(" </TD>\n</TR>");
95 if (!empty($ADD)) OUTPUT_HTML($ADD);
96 OUTPUT_HTML("</TABLE>");
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;
104 // Do we have HTML-Code here?
106 // Yes, so we handle it as you have configured
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
115 // That's why you don't need any \n at the end of your HTML code... :-)
116 if ($NEW_LINE) echo "\n";
118 // Render mode for old or lame servers...
121 // That's why you don't need any \n at the end of your HTML code... :-)
122 if ($NEW_LINE) $OUTPUT .= "\n";
127 // If we are switching from render to direct output rendered code
128 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
130 // The same as above... ^
132 if ($NEW_LINE) echo "\n";
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);
141 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
142 // Headers already sent?
143 if (headers_sent()) {
145 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
147 // Output debug trace
148 print("<stron>Headers are already sent!</strong><br />\n");
149 print("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
150 debug_print_backtrace();
151 die("</pre>Thank you for your help finding bugs.");
154 // Output cached HTML code
155 $OUTPUT = ob_get_contents();
157 // Clear output buffer for later output
161 header("HTTP/1.1 200");
164 $now = gmdate('D, d M Y H:i:s') . ' GMT';
166 // General headers for no caching
167 header("Expired: " . $now); // RFC2616 - Section 14.21
168 header("Last-Modified: " . $now);
169 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
170 header("Pragma: no-cache"); // HTTP/1.0
171 header("Connection: Close");
173 // Extension "rewrite" installed?
174 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
175 $OUTPUT = REWRITE_LINKS($OUTPUT);
178 // Compile and run finished rendered HTML code
179 while (strpos($OUTPUT, '{!') > 0) {
180 // Prepare the content and eval() it...
182 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
185 // Was that eval okay?
186 if (empty($newContent)) {
187 // Something went wrong!
188 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
190 $OUTPUT = $newContent;
193 // Output code here, DO NOT REMOVE! ;-)
195 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
196 // Rewrite links when rewrite extension is active
197 if ((EXT_IS_ACTIVE("rewrite")) && (function_exists('REWRITE_LINKS')) && ($CSS != "1") && ($CSS != "-1")) {
198 $OUTPUT = REWRITE_LINKS($OUTPUT);
201 // Compile and run finished rendered HTML code
202 while (strpos($OUTPUT, '{!') > 0) {
203 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
207 // Output code here, DO NOT REMOVE! ;-)
212 // Output the raw HTML code
213 function OUTPUT_RAW ($HTML) {
214 // Output stripped HTML code to avoid broken JavaScript code, etc.
215 echo stripslashes(stripslashes($HTML));
217 // Flush the output if only _OB_CACHING is not "on"
218 if (_OB_CACHING != "on") {
224 // Add a fatal error message to the queue array
225 function ADD_FATAL ($message, $extra="") {
229 // Regular text message to add to $FATAL
232 // $message is text with a mask plus extras to insert into the text
233 $message = sprintf($message, $extra);
237 // Log fatal messages away
238 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
241 // Load a template file and return it's content (only it's name; do not use ' or ")
242 function LOAD_TEMPLATE($template, $return=false, $content=array()) {
243 // Add more variables which you want to use in your template files
244 global $DATA, $_CONFIG, $username;
246 // Make all template names lowercase
247 $template = strtolower($template);
249 // Count the template load
250 incrementConfigEntry('num_templates');
252 // Prepare IP number and User Agent
253 $REMOTE_ADDR = GET_REMOTE_ADDR();
254 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
255 $HTTP_USER_AGENT = GET_USER_AGENT();
259 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
261 // @DEPRECATED Try to rewrite the if() condition
262 if ($template == "member_support_form") {
263 // Support request of a member
264 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
265 array($GLOBALS['userid']), __FILE__, __LINE__);
267 // Is content an array?
268 if (is_array($content)) {
270 $content = merge_array($content, SQL_FETCHARRAY($result));
273 $content['gender'] = TRANSLATE_GENDER($content['gender']);
275 // DEPRECATED: Load data in direct variables
276 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
279 $gender = TRANSLATE_GENDER($gender);
280 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
284 SQL_FREERESULT($result);
287 // Generate date/time string
288 $date_time = MAKE_DATETIME(time(), "1");
291 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
294 // Check for admin/guest/member templates
295 if (strpos($template, "admin_") > -1) {
296 // Admin template found
298 } elseif (strpos($template, "guest_") > -1) {
299 // Guest template found
301 } elseif (strpos($template, "member_") > -1) {
302 // Member template found
304 } elseif (strpos($template, "install_") > -1) {
305 // Installation template found
307 } elseif (strpos($template, "ext_") > -1) {
308 // Extension template found
310 } elseif (strpos($template, "la_") > -1) {
311 // "Logical-area" template found
314 // Test for extension
315 $test = substr($template, 0, strpos($template, "_"));
316 if (EXT_IS_ACTIVE($test)) {
317 // Set extra path to extension's name
322 ////////////////////////
323 // Generate file name //
324 ////////////////////////
325 $file = $BASE.$MODE.$template.".tpl";
327 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
328 // Select what depended header/footer template file for admin/guest/member area
329 $file2 = sprintf("%s%s%s_%s.tpl",
333 SQL_ESCAPE($GLOBALS['what'])
337 if (FILE_READABLE($file2)) $file = $file2;
339 // Remove variable from memory
343 // Does the special template exists?
344 if (!FILE_READABLE($file)) {
345 // Reset to default template
346 $file = $BASE.$template.".tpl";
349 // Now does the final template exists?
350 if (FILE_READABLE($file)) {
351 // The local file does exists so we load it. :)
352 $tmpl_file = READ_FILE($file);
354 // Replace ' to our own chars to preventing them being quoted
355 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
357 // Do we have to compile the code?
359 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
361 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
364 // Simply return loaded code
368 // Add surrounding HTML comments to help finding bugs faster
369 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
370 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
371 // Only admins shall see this warning or when installation mode is active
372 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
373 (".basename($file).")<br />
376 <pre>".print_r($content, true)."</pre>
378 <pre>".print_r($DATA, true)."</pre>
382 // Remove content and data
386 // Do we have some content to output or return?
388 // Not empty so let's put it out! ;)
390 // Return the HTML code
396 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
397 // Warning, empty output!
398 return "E:".$template."<br />\n";
402 // Send mail out to an email address
403 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
404 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
406 // Compile subject line (for POINTS constant etc.)
407 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
411 if ((!eregi("@", $TO)) && ($TO > 0)) {
412 // Value detected, is the message extension installed?
413 if (EXT_IS_ACTIVE("msg")) {
414 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
417 // Load email address
418 $result_email = SQL_QUERY_ESC("SELECT email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
419 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
421 // Does the user exist?
422 if (SQL_NUMROWS($result_email)) {
423 // Load email address
424 list($TO) = SQL_FETCHROW($result_email);
431 SQL_FREERESULT($result_email);
433 } elseif ("$TO" == "0") {
437 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
439 // Check for PHPMailer or debug-mode
440 if (!CHECK_PHPMAILER_USAGE()) {
441 // Not in PHPMailer-Mode
443 // Load email header template
444 $FROM = LOAD_EMAIL_TEMPLATE("header");
447 $FROM .= LOAD_EMAIL_TEMPLATE("header");
449 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
451 // Load email header template
452 $FROM = LOAD_EMAIL_TEMPLATE("header");
455 $FROM .= LOAD_EMAIL_TEMPLATE("header");
460 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
464 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
467 // Fix HTML parameter (default is no!)
468 if (empty($HTML)) $HTML = "N";
469 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
470 // In debug mode we want to display the mail instead of sending it away so we can debug this part
472 ".htmlentities(trim($FROM))."
474 Subject : ".$SUBJECT."
477 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
478 // Send mail as HTML away
479 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
480 } elseif (!empty($TO)) {
482 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
483 } elseif ($HTML == "N") {
485 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
489 // Check if legacy or PHPMailer command
491 function CHECK_PHPMAILER_USAGE() {
492 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
496 * Send out a raw email with PHPMailer class or legacy mail() command
498 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
499 // Shall we use PHPMailer class or legacy mode?
500 if (CHECK_PHPMAILER_USAGE()) {
501 // Use PHPMailer class with SMTP enabled
502 require_once(PATH."inc/phpmailer/class.phpmailer.php");
503 require_once(PATH."inc/phpmailer/class.smtp.php");
506 $mail = new PHPMailer();
507 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
510 $mail->SMTPAuth = true;
511 $mail->Host = SMTP_HOSTNAME;
513 $mail->Username = SMTP_USER;
514 $mail->Password = SMTP_PASSWORD;
516 $mail->From = WEBMASTER;
520 $mail->FromName = MAIN_TITLE;
521 $mail->Subject = $subject;
522 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
524 $mail->AltBody = "Your mail program required HTML support to read this mail!";
525 $mail->WordWrap = 70;
528 $mail->Body = html_entity_decode($msg);
530 $mail->AddAddress($to, "");
531 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
532 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
533 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
536 // Use legacy mail() command
537 @mail($to, $subject, html_entity_decode($msg), $from);
542 // Generate a password in a specified length or use default password length
543 function GEN_PASS ($LEN = 0) {
544 // Auto-fix invalid length of zero
545 if ($LEN == 0) $LEN = getConfig('pass_len');
547 // Initialize array with all allowed chars
548 $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,-,+,_,/");
550 // Initialize randomizer
551 mt_srand((double) microtime() * 1000000);
553 // Start creating password
555 for ($i = 0; $i < $LEN; $i++) {
556 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
559 // When the size is below 40 we can also add additional security by scrambling it
560 if (strlen($PASS) <= 40) {
561 // Also scramble the password
562 $PASS = scrambleString($PASS);
565 // Return the password
569 function MAKE_DATETIME ($time, $mode="0")
573 return NEVER_HAPPENED;
575 // Filter out numbers
576 $time = bigintval($time);
579 switch (GET_LANGUAGE())
581 case "de": // German date / time format
583 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
584 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
585 case "2": $ret = date("d.m.Y|H:i", $time); break;
586 case "3": $ret = date("d.m.Y", $time); break;
588 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
593 default: // Default is the US date / time format!
595 case "0": $ret = date("r", $time); break;
596 case "1": $ret = date("Y-m-d - g:i A", $time); break;
597 case "2": $ret = date("y-m-d|H:i", $time); break;
598 case "3": $ret = date("y-m-d", $time); break;
600 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
607 // Translates the american decimal dot into a german comma
608 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
611 // Default is 3 you can change this in admin area "Misc -> Misc Options"
612 if (getConfig('max_comma') == null) $_CONFIG['max_comma'] = "3";
614 // Use from config is default
615 $maxComma = getConfig('max_comma');
617 // Use from parameter?
618 if ($max > 0) $maxComma = $max;
621 if (($cut) && ($max == 0)) {
622 // Test for commata if in cut-mode
623 $com = explode(".", $dotted);
624 if (count($com) < 2) {
625 // Don't display commatas even if there are none... ;-)
631 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
634 switch (GET_LANGUAGE()) {
636 $dotted = number_format($dotted, $maxComma, ",", ".");
640 $dotted = number_format($dotted, $maxComma, ".", ",");
644 // Return translated value
649 function DEREFERER ($URL) {
650 // Don't de-refer our own links!
651 if (substr($URL, 0, strlen(URL)) != URL) {
652 // De-refer this link
653 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
661 function TRANSLATE_GENDER ($gender) {
664 case "M": $ret = GENDER_M; break;
665 case "F": $ret = GENDER_F; break;
666 case "C": $ret = GENDER_C; break;
667 default : $ret = $gender; break;
672 function FRAMETESTER($URL) {
673 // Prepare frametester URL
674 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
676 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
678 return $frametesterUrl;
681 function SELECTION_COUNT($array) {
683 if (is_array($array)) {
684 foreach ($array as $key => $sel) {
685 if (!empty($sel)) $ret++;
691 function IMG_CODE ($code, $type, $DATA, $uid) {
692 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
695 function TRANSLATE_STATUS($status) {
699 $ret = ACCOUNT_UNCONFIRMED;
703 $ret = ACCOUNT_CONFIRMED;
707 $ret = ACCOUNT_LOCKED;
712 $ret = ACCOUNT_DELETED;
716 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
717 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
723 function GET_LANGUAGE() {
726 // Set default return value to default language from config
732 // Is the variable set
733 if (!empty($_GET['mx_lang'])) {
734 // Accept only first 2 chars
735 $lang = substr($_GET['mx_lang'], 0, 2);
736 } elseif (isset($cacheArray['language'])) {
738 $ret = $cacheArray['language'];
739 } elseif (!empty($lang)) {
740 // Check if main language file does exist
741 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
742 // Okay found, so let's update cookies
745 } elseif (!isSessionVariableSet('mx_lang')) {
746 // Return stored value from cookie
747 $ret = get_session('mx_lang');
749 // Fixes a warning before the session has the mx_lang constant
750 if (empty($ret)) $ret = DEFAULT_LANG;
754 $cacheArray['language'] = $ret;
760 function SET_LANGUAGE ($lang) {
761 // Accept only first 2 chars!
762 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
765 set_session('mx_lang', $lang);
768 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
769 global $DATA, $REPLACER, $_CONFIG;
771 // Make sure all template names are lowercase!
772 $template = strtolower($template);
774 // Default "nickname" if extension is not installed
777 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
778 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
780 // Prepare IP number and User Agent
781 $REMOTE_ADDR = GET_REMOTE_ADDR();
782 $HTTP_USER_AGENT = GET_USER_AGENT();
787 // Is the admin logged in?
790 $aid = GET_CURRENT_ADMIN_ID();
793 $ADMIN = GET_ADMIN_EMAIL($aid);
796 // Neutral email address is default
799 // Expiration in a nice output format
800 if (getConfig('auto_purge') == 0) {
801 // Will never expire!
802 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
803 } elseif (function_exists('CREATE_FANCY_TIME')) {
804 // Create nice date string
805 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
808 $EXPIRATION = round(getConfig('auto_purge')/60/60/24)." "._DAYS;
811 // Is content an array?
812 if (is_array($content)) {
813 // Add expiration to array, $EXPIRATION is now deprecated!
814 $content['expiration'] = $EXPIRATION;
818 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
819 if (($UID > 0) && (is_array($content))) {
820 // If nickname extension is installed, fetch nickname as well
821 if (EXT_IS_ACTIVE("nickname")) {
822 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
824 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
825 array(bigintval($UID)), __FILE__, __LINE__);
827 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
829 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
830 array(bigintval($UID)), __FILE__, __LINE__);
833 // Fetch and merge data
834 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
835 $content = merge_array($content, SQL_FETCHARRAY($result));
836 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
839 SQL_FREERESULT($result);
842 // Translate M to male or F to female if present
843 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
845 // Overwrite email from data if present
846 if (isset($content['email'])) $email = $content['email'];
848 // Store email for some functions in global data array
849 $DATA['email'] = $email;
852 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
854 // Check for admin/guest/member templates
855 if (strpos($template, "admin_") > -1) {
856 // Admin template found
857 $file = $BASE."admin/".$template.".tpl";
858 } elseif (strpos($template, "guest_") > -1) {
859 // Guest template found
860 $file = $BASE."guest/".$template.".tpl";
861 } elseif (strpos($template, "member_") > -1) {
862 // Member template found
863 $file = $BASE."member/".$template.".tpl";
865 // Test for extension
866 $test = substr($template, 0, strpos($template, "_"));
867 if (EXT_IS_ACTIVE($test)) {
868 // Set extra path to extension's name
869 $file = $BASE.$test."/".$template.".tpl";
871 // No special filename
872 $file = $BASE.$template.".tpl";
876 // Does the special template exists?
877 if (!FILE_READABLE($file)) {
878 // Reset to default template
879 $file = $BASE.$template.".tpl";
882 // Now does the final template exists?
884 if (FILE_READABLE($file)) {
885 // The local file does exists so we load it. :)
886 $tmpl_file = READ_FILE($file);
887 $tmpl_file = addslashes($tmpl_file);
890 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
892 } elseif (!empty($template)) {
893 // Template file not found!
894 $newContent = TEMPLATE_404.": ".$template."<br />
896 <pre>".print_r($content, true)."</pre>
898 <pre>".print_r($DATA, true)."</pre>
901 // Debug mode not active? Then remove the HTML tags
902 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
904 // No template name supplied!
905 $newContent = NO_TEMPLATE_SUPPLIED;
908 // Is there some content?
909 if (empty($newContent)) {
911 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
912 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
915 // Remove content and data
919 // Return compiled content
920 return COMPILE_CODE($newContent);
923 function MAKE_TIME($H, $M, $S, $stamp) {
924 // Extract day, month and year from given timestamp
925 $DAY = date("d", $stamp);
926 $MONTH = date("m", $stamp);
927 $YEAR = date('Y', $stamp);
929 // Create timestamp for wished time which depends on extracted date
930 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
933 function LOAD_URL($URL, $addUrlData=true) {
934 global $CSS, $footer;
936 // Compile out URI codes
937 $URL = COMPILE_CODE($URL);
939 // Check if http(s):// is there
940 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
941 // Make all URLs full-qualified
948 debug_print_backtrace();
951 $OUTPUT = ob_get_contents();
953 // Clear it only if there is content
954 if (!empty($OUTPUT)) {
958 // Add some data to URL if cookies are not accepted
959 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
961 // Probe for bot from search engine
962 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
963 // Search engine bot detected so let's rewrite many chars for the link
964 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
966 // Output new location link as anchor
967 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
968 } elseif (!headers_sent()) {
969 // Load URL when headers are not sent
972 debug_print_backtrace();
973 die("</pre>URL={$URL}");
975 @header ("Location: ".str_replace("&", "&", $URL));
977 // Output error message
978 include(PATH."inc/header.php");
979 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
980 include(PATH."inc/footer.php");
985 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
986 global $SEC_CHARS, $URL_CHARS;
987 // Is the code a string?
988 if (!is_string($code)) {
989 // Silently return it
995 // Select smaller set of chars to replace when we e.g. want to compile URLs
996 if (!$full) $ARRAY = $URL_CHARS;
1000 // BEFORE 0.2.1 : Language and data constants
1001 // WITH 0.2.1+ : Only language constants
1002 $code = str_replace('{--','".', str_replace('--}','."', $code));
1004 // BEFORE 0.2.1 : Not used
1005 // WITH 0.2.1+ : Data constants
1006 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1009 // Compile QUOT and other non-HTML codes
1010 foreach ($ARRAY['to'] as $k => $to) {
1011 // Do the reversed thing as in inc/libs/security_functions.php
1012 $code = str_replace($to, $ARRAY['from'][$k], $code);
1015 // But shall I keep simple quotes for later use?
1016 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1018 // Find $content[bla][blub] entries
1019 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1021 // Are some matches found?
1022 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1023 // Replace all matches
1024 $matchesFound = array();
1025 foreach ($matches[0] as $key => $match) {
1026 // Fuzzy look has failed by default
1027 $fuzzyFound = false;
1029 // Fuzzy look on match if already found
1030 foreach ($matchesFound as $found => $set) {
1032 $test = substr($found, 0, strlen($match));
1034 // Does this entry exist?
1035 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1036 if ($test == $match) {
1038 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1045 if ($fuzzyFound) continue;
1047 // Take all string elements
1048 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1049 // Replace it in the code
1050 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1051 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1052 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1053 $matchesFound[$key."_".$matches[4][$key]] = 1;
1054 $matchesFound[$match] = 1;
1055 } elseif (!isset($matchesFound[$match])) {
1056 // Not yet replaced!
1057 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1058 $code = str_replace($match, "\".".$match.".\"", $code);
1059 $matchesFound[$match] = 1;
1064 // Return compiled code
1068 /************************************************************************
1070 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1071 * $a_sort sortiert: *
1073 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1074 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1075 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1076 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1077 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1079 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1080 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1081 * Sie, dass es doch nicht so schwer ist! :-) *
1083 ************************************************************************/
1084 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1087 while ($primary_key < count($a_sort)) {
1088 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1089 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1092 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1093 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1094 } elseif ($key != $key2) {
1095 // Sort numbers (E.g.: 9 < 10)
1096 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1097 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1101 // We have found two different values, so let's sort whole array
1102 foreach ($dummy as $sort_key => $sort_val) {
1103 $t = $dummy[$sort_key][$key];
1104 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1105 $dummy[$sort_key][$key2] = $t;
1116 // Write back sorted array
1120 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1121 global $MONTH_DESCR;
1124 if ($type == "yn") {
1125 // This is a yes/no selection only!
1126 if ($id > 0) $prefix .= "[".$id."]";
1127 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1129 // Begin with regular selection box here
1130 if (!empty($prefix)) $prefix .= "_";
1132 if ($id > 0) $type2 .= "[".$id."]";
1133 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1138 for ($idx = 1; $idx < 32; $idx++) {
1139 $OUT .= "<OPTION value=\"".$idx."\"";
1140 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1141 $OUT .= ">".$idx."</OPTION>\n";
1145 case "month": // Month
1146 foreach ($MONTH_DESCR as $month => $descr) {
1147 $OUT .= "<OPTION value=\"".$month."\"";
1148 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1149 $OUT .= ">".$descr."</OPTION>\n";
1153 case "year": // Year
1155 $YEAR = date('Y', time());
1157 // Use configured min age or fixed?
1158 if (GET_EXT_VERSION("other") >= "0.2.1") {
1160 $startYear = $YEAR - getConfig('min_age');
1163 $startYear = $YEAR - 16;
1166 // Calculate earliest year (100 years old people can still enter Internet???)
1167 $minYear = $YEAR - 100;
1169 // Check if the default value is larger than minimum and bigger than actual year
1170 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1171 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1172 $OUT .= "<OPTION value=\"".$idx."\"";
1173 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1174 $OUT .= ">".$idx."</OPTION>\n";
1176 } elseif ($DEFAULT == -1) {
1177 // Current year minus 1
1178 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1180 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1183 // Get current year and subtract the configured minimum age
1184 $OUT .= "<OPTION value=\"".($minYear - 1)."\"><".$minYear."</OPTION>\n";
1185 // Calculate earliest year depending on extension version
1186 if (GET_EXT_VERSION("other") >= "0.2.1") {
1187 // Use configured minimum age
1188 $YEAR = date('Y', time()) - getConfig('min_age');
1190 // Use fixed 16 years age
1191 $YEAR = date('Y', time()) - 16;
1194 // Construct year selection list
1195 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1196 $OUT .= "<OPTION value=\"".$idx."\"";
1197 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1198 $OUT .= ">".$idx."</OPTION>\n";
1205 for ($idx = 0; $idx < 60; $idx+=5) {
1206 if (strlen($idx) == 1) $idx = "0".$idx;
1207 $OUT .= "<OPTION value=\"".$idx."\"";
1208 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1209 $OUT .= ">".$idx."</OPTION>\n";
1214 for ($idx = 0; $idx < 24; $idx++) {
1215 if (strlen($idx) == 1) $idx = "0".$idx;
1216 $OUT .= "<OPTION value=\"".$idx."\"";
1217 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1218 $OUT .= ">".$idx."</OPTION>\n";
1223 $OUT .= "<OPTION value=\"Y\"";
1224 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1225 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1226 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1227 $OUT .= ">".NO."</OPTION>\n";
1230 $OUT .= " </SELECT>\n";
1234 function TRANSLATE_YESNO($yn)
1238 case "Y": $yn = YES; break;
1239 case "N": $yn = NO; break;
1240 default : $yn = "??? (".$yn.")"; break;
1245 // Deprecated : $length
1248 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1249 // Fix missing _MAX constant
1250 if (!defined('_MAX')) define('_MAX', 15235);
1252 // Build server string
1253 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1256 $keys = SITE_KEY.":".DATE_KEY;
1257 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1258 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1259 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1260 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1262 // Build string from misc data
1263 $data = $code.":".$uid.":".$DATA;
1265 // Add more additional data
1266 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1267 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1268 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1269 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1270 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1272 // Calculate number for generating the code
1273 $a = $code + _ADD - 1;
1275 if (getConfig('master_hash') != null) {
1276 // Generate hash with master salt from modula of number with the prime number and other data
1277 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1279 // Create number from hash
1280 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1282 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1283 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1285 // Create number from hash
1286 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1289 // At least 10 numbers shall be secure enought!
1290 $len = getConfig('code_length');
1291 if ($len == 0) $len = $length;
1292 if ($len == 0) $len = 10;
1294 // Cut off requested counts of number
1295 $return = substr(str_replace('.', "", $rcode), 0, $len);
1297 // Done building code
1300 // Does only allow numbers
1301 function bigintval($num, $castValue = true) {
1302 // Filter all numbers out
1303 $ret = preg_replace("/[^0123456789]/", "", $num);
1306 if ($castValue) $ret = (double)$ret;
1308 // Has the whole value changed?
1309 if ("".$ret."" != "".$num."") {
1312 debug_print_backtrace();
1314 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1320 // Insert the code in $img_code into jpeg or PNG image
1321 function GENERATE_IMAGE($img_code, $header=true) {
1322 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1323 // Stop execution of function here because of over-sized code length
1325 } elseif (!$header) {
1326 // Return in an HTML code code
1327 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1331 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), getConfig('img_type'));
1332 if (FILE_READABLE($img)) {
1333 // Switch image type
1334 switch (getConfig('img_type'))
1337 // Okay, load image and hide all errors
1338 $image = @imagecreatefromjpeg($img);
1342 // Okay, load image and hide all errors
1343 $image = @imagecreatefrompng($img);
1347 // Exit function here
1351 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1352 $text_color = imagecolorallocate($image, 0, 0, 0);
1354 // Insert code into image
1355 imagestring($image, 5, 14, 2, $img_code, $text_color);
1357 // Return to browser
1358 header ("Content-Type: image/".getConfig('img_type'));
1360 // Output image with matching image factory
1361 switch (getConfig('img_type')) {
1362 case "jpg": imagejpeg($image); break;
1363 case "png": imagepng($image); break;
1366 // Remove image from memory
1367 imagedestroy($image);
1369 // Create selection box or array of splitted timestamp
1370 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1371 // Calculate 2-seconds timestamp
1372 $stamp = round($timestamp);
1373 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1375 // Do we have a leap year?
1377 $TEST = date('Y', time()) / 4;
1378 $M1 = date("m", time());
1379 $M2 = date("m", (time() + $timestamp));
1381 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1382 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1384 // First of all years...
1385 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1386 //* DEBUG: */ print("Y={$Y}<br />\n");
1388 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1389 //* DEBUG: */ print("M={$M}<br />\n");
1391 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1392 //* DEBUG: */ print("W={$W}<br />\n");
1394 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1395 //* DEBUG: */ print("D={$D}<br />\n");
1397 $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));
1398 //* DEBUG: */ print("h={$h}<br />\n");
1400 $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));
1401 //* DEBUG: */ print("m={$m}<br />\n");
1402 // And at last seconds...
1403 $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));
1404 //* DEBUG: */ print("s={$s}<br />\n");
1406 // Is seconds zero and time is < 60 seconds?
1407 if (($s == 0) && ($timestamp < 60)) {
1409 $s = round($timestamp);
1413 // Now we convert them in seconds...
1415 if ($return_array) {
1416 // Just put all data in an array for later use
1428 $OUT = "<DIV align=\"".$align."\">\n";
1429 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1432 if (ereg('Y', $display) || (empty($display))) {
1433 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1436 if (ereg("M", $display) || (empty($display))) {
1437 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1440 if (ereg("W", $display) || (empty($display))) {
1441 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1444 if (ereg("D", $display) || (empty($display))) {
1445 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1448 if (ereg("h", $display) || (empty($display))) {
1449 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1452 if (ereg("m", $display) || (empty($display))) {
1453 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1456 if (ereg("s", $display) || (empty($display))) {
1457 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1463 if (ereg('Y', $display) || (empty($display))) {
1464 // Generate year selection
1465 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1466 for ($idx = 0; $idx <= 10; $idx++) {
1467 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1468 if ($idx == $Y) $OUT .= " selected default";
1469 $OUT .= ">".$idx."</OPTION>\n";
1471 $OUT .= " </SELECT></TD>\n";
1473 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1476 if (ereg("M", $display) || (empty($display))) {
1477 // Generate month selection
1478 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1479 for ($idx = 0; $idx <= 11; $idx++)
1481 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1482 if ($idx == $M) $OUT .= " selected default";
1483 $OUT .= ">".$idx."</OPTION>\n";
1485 $OUT .= " </SELECT></TD>\n";
1487 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1490 if (ereg("W", $display) || (empty($display))) {
1491 // Generate week selection
1492 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1493 for ($idx = 0; $idx <= 4; $idx++) {
1494 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1495 if ($idx == $W) $OUT .= " selected default";
1496 $OUT .= ">".$idx."</OPTION>\n";
1498 $OUT .= " </SELECT></TD>\n";
1500 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1503 if (ereg("D", $display) || (empty($display))) {
1504 // Generate day selection
1505 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1506 for ($idx = 0; $idx <= 31; $idx++) {
1507 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1508 if ($idx == $D) $OUT .= " selected default";
1509 $OUT .= ">".$idx."</OPTION>\n";
1511 $OUT .= " </SELECT></TD>\n";
1513 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1516 if (ereg("h", $display) || (empty($display))) {
1517 // Generate hour selection
1518 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1519 for ($idx = 0; $idx <= 23; $idx++) {
1520 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1521 if ($idx == $h) $OUT .= " selected default";
1522 $OUT .= ">".$idx."</OPTION>\n";
1524 $OUT .= " </SELECT></TD>\n";
1526 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1529 if (ereg("m", $display) || (empty($display))) {
1530 // Generate minute selection
1531 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1532 for ($idx = 0; $idx <= 59; $idx++) {
1533 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1534 if ($idx == $m) $OUT .= " selected default";
1535 $OUT .= ">".$idx."</OPTION>\n";
1537 $OUT .= " </SELECT></TD>\n";
1539 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1542 if (ereg("s", $display) || (empty($display))) {
1543 // Generate second selection
1544 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1545 for ($idx = 0; $idx <= 59; $idx++) {
1546 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1547 if ($idx == $s) $OUT .= " selected default";
1548 $OUT .= ">".$idx."</OPTION>\n";
1550 $OUT .= " </SELECT></TD>\n";
1552 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1555 $OUT .= "</TABLE>\n";
1557 // Return generated HTML code
1562 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1563 // Initial return value
1566 // Do we have a leap year?
1568 $TEST = date('Y', time()) / 4;
1569 $M1 = date("m", time());
1570 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1571 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1572 // First add years...
1573 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1575 $ret += $POST[$prefix."_mo"] * 2628000;
1577 $ret += $POST[$prefix."_we"] * 604800;
1579 $ret += $POST[$prefix."_da"] * 86400;
1581 $ret += $POST[$prefix."_ho"] * 3600;
1583 $ret += $POST[$prefix."_mi"] * 60;
1584 // And at last seconds...
1585 $ret += $POST[$prefix."_se"];
1586 // Return calculated value
1589 // Sends out mail to all administrators
1590 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1591 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1592 // Trim template name
1593 $template = trim($template);
1595 // Load email template
1596 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1598 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1599 // Older version detected!
1600 return SEND_ADMIN_EMAILS($subj, $msg);
1603 // Check which admin shall receive this mail
1604 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1605 array($template), __FILE__, __LINE__);
1606 if (SQL_NUMROWS($result) == 0) {
1607 // Create new entry (to all admins)
1608 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1609 array($template), __FILE__, __LINE__);
1611 // Load admin IDs...
1613 while(list($aid) = SQL_FETCHROW($result)) {
1618 SQL_FREERESULT($result);
1620 // "implode" IDs and query string
1621 $aid = implode(",", $aids);
1623 // Add line to userlog
1624 USERLOG_ADD_LINE($subj, $msg, $UID);
1626 } elseif ($aid == "0") {
1627 // Select all email adresses
1628 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1630 // If Admin-ID is not "to-all" select
1631 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1635 // Load email addresses and send away
1636 while (list($email) = SQL_FETCHROW($result)) {
1637 SEND_EMAIL($email, $subj, $msg);
1641 SQL_FREERESULT($result);
1644 function CREATE_FANCY_TIME ($stamp) {
1645 // Get data array with years/months/weeks/days/...
1646 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1648 foreach($data as $k => $v) {
1650 // Value is greater than 0 "eval" data to return string
1651 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1657 // Do we have something there?
1658 if (strlen($ret) > 0) {
1659 // Remove leading commata and space
1660 $ret = substr($ret, 2);
1663 $ret = "0 "._SECONDS;
1666 // Return fancy time string
1670 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1671 $SEP = ""; $TOP = "";
1674 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1678 for ($page = 1; $page <= $PAGES; $page++) {
1679 // Is the page currently selected or shall we generate a link to it?
1680 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1681 // Is currently selected, so only highlight it
1682 $NAV .= "<STRONG>-";
1684 // Open anchor tag and add base URL
1685 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1687 // Add userid when we shall show all mails from a single member
1688 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1690 // Close open anchor tag
1694 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1695 // Is currently selected, so only highlight it
1696 $NAV .= "-</STRONG>";
1702 // Add seperator if we have not yet reached total pages
1703 if ($page < $PAGES) $NAV .= " | ";
1706 // Define constants only once
1707 if (!defined('__NAV_OUTPUT')) {
1708 define('__NAV_OUTPUT' , $NAV);
1709 define('__NAV_COLSPAN', $colspan);
1710 define('__NAV_TOP' , $TOP);
1711 define('__NAV_SEP' , $SEP);
1714 // Load navigation template
1715 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1718 // Return generated HTML-Code
1726 // Extract host from script name
1727 function EXTRACT_HOST (&$script) {
1728 // Use default SERVER_URL by default... ;) So?
1731 // Is this URL valid?
1732 if (substr($script, 0, 7) == "http://") {
1733 // Use the hostname from script URL as new hostname
1734 $url = substr($script, 7);
1735 $extract = explode("/", $url);
1737 // Done extracting the URL :)
1740 // Extract host name
1741 $host = str_replace("http://", "", $url);
1742 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1744 // Generate relative URL
1745 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1746 if (substr(strtolower($script), 0, 7) == "http://") {
1747 // But only if http:// is in front!
1748 $script = substr($script, (strlen($url) + 7));
1749 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1751 $script = substr($script, (strlen($url) + 8));
1754 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1755 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1761 // Send a GET request
1762 function GET_URL ($script) {
1763 // Compile the script name
1764 $script = COMPILE_CODE($script);
1766 // Extract host name from script
1767 $host = EXTRACT_HOST($script);
1769 // Generate GET request header
1770 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1771 $request .= "Host: " . $host . "\r\n";
1772 $request .= "Referer: " . URL . "/admin.php\r\n";
1773 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1774 $request .= "Content-Type: text/plain\r\n";
1775 $request .= "Cache-Control: no-cache\r\n";
1776 $request .= "Connection: Close\r\n\r\n";
1778 // Send the raw request
1779 $response = SEND_RAW_REQUEST($host, $request);
1781 // Return the result to the caller function
1785 // Send a POST request
1786 function POST_URL ($script, $postData) {
1787 // Is postData an array?
1788 if (!is_array($postData)) {
1790 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1791 return array("", "", "");
1794 // Compile the script name
1795 $script = COMPILE_CODE($script);
1797 // Extract host name from script
1798 $host = EXTRACT_HOST($script);
1800 // Construct request
1801 $data = http_build_query($postData, '','&');
1803 // Generate POST request header
1804 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1805 $request .= "Host: " . $host . "\r\n";
1806 $request .= "Referer: " . URL . "/admin.php\r\n";
1807 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1808 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1809 $request .= "Content-length: " . strlen($data) . "\r\n";
1810 $request .= "Cache-Control: no-cache\r\n";
1811 $request .= "Connection: Close\r\n\r\n";
1814 // Send the raw request
1815 $response = SEND_RAW_REQUEST($host, $request);
1817 // Return the result to the caller function
1821 // Sends a raw request to another host
1822 function SEND_RAW_REQUEST ($host, $request) {
1824 $response = array("", "", "");
1826 // Default is not to use proxy
1829 // Are proxy settins set?
1830 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1836 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1838 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1840 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1844 if (!is_resource($fp)) {
1851 // Generate CONNECT request header
1852 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1853 $proxyTunnel .= "Host: ".$host."\r\n";
1855 // Use login data to proxy? (username at least!)
1856 if (getConfig('proxy_username') != "") {
1858 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1859 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1862 // Add last new-line
1863 $proxyTunnel .= "\r\n";
1864 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1867 fputs($fp, $proxyTunnel);
1871 // No response received
1875 // Read the first line
1876 $resp = trim(fgets($fp, 10240));
1877 $respArray = explode(" ", $resp);
1878 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1879 // Invalid response!
1885 fputs($fp, $request);
1889 $response[] = trim(fgets($fp, 1024));
1895 // Skip first empty lines
1897 foreach ($resp as $idx => $line) {
1899 $line = trim($line);
1901 // Is this line empty?
1904 array_shift($response);
1906 // Abort on first non-empty line
1911 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1913 // Proxy agent found?
1914 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1915 // Proxy header detected, so remove two lines
1916 array_shift($response);
1917 array_shift($response);
1920 // Was the request successfull?
1921 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1922 // Not found / access forbidden
1923 $response = array("", "", "");
1929 // Taken from www.php.net eregi() user comments
1930 function VALIDATE_EMAIL($email) {
1932 $email = COMPILE_CODE($email);
1934 // Check first part of email address
1935 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1938 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1941 $regex = "^".$first."@".$domain."$";
1943 // Return check result
1944 return eregi($regex, $email);
1946 // Function taken from user comments on www.php.net / function eregi()
1947 function VALIDATE_URL ($URL, $compile=true) {
1948 // Trim URL a little
1949 $URL = trim(urldecode($URL));
1950 //* DEBUG: */ echo $URL."<br />";
1952 // Compile some chars out...
1953 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1954 //* DEBUG: */ echo $URL."<br />";
1956 // Check for the extension filter
1957 if (EXT_IS_ACTIVE("filter")) {
1958 // Use the extension's filter set
1959 return FILTER_VALIDATE_URL($URL, false);
1962 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1963 // https:// in front of the URLs
1964 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1967 function MEMBER_ACTION_LINKS($uid, $status="") {
1968 // Define all main targets
1969 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1971 // Begin of navigation links
1972 $eval = "\$OUT = \"[ ";
1974 foreach ($TARGETS as $tar) {
1975 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1976 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1977 if (($tar == "lock_user") && ($status == "LOCKED")) {
1978 // Locked accounts shall be unlocked
1979 $eval .= "UNLOCK_USER";
1981 // All other status is fine
1982 $eval .= strtoupper($tar);
1984 $eval .= "_TITLE.\"\\\">\".ADMIN_";
1985 if (($tar == "lock_user") && ($status == "LOCKED")) {
1986 // Locked accounts shall be unlocked
1987 $eval .= "UNLOCK_USER";
1989 // All other status is fine
1990 $eval .= strtoupper($tar);
1992 $eval .= ".\"</A></SPAN> | ";
1995 // Finish navigation link
1996 $eval = substr($eval, 0, -7)."]\";";
2002 // Function for backward-compatiblity
2003 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
2004 // Load it from the register extension
2005 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
2007 // Generate an email link
2008 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2009 // Default email link (INSECURE! Spammer can read this by harvester programs)
2010 $EMAIL = "mailto:".$email;
2012 // Check for several extensions
2013 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2014 // Create email link for contacting admin in guest area
2015 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2016 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2017 // Create email link for contacting a member within admin area (or later in other areas, too?)
2018 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2019 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2020 // Create email link to contact sponsor within admin area (or like the link above?)
2021 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2024 // Shall I close the link when there is no admin?
2025 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2027 // Return email link
2030 // Generate a hash for extra-security for all passwords
2031 function generateHash ($plainText, $salt = "") {
2034 // Is the required extension "sql_patches" there and a salt is not given?
2035 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2036 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2037 return md5($plainText);
2040 // Do we miss an arry element here?
2041 if (getConfig('file_hash') == null) {
2043 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2044 debug_print_backtrace();
2048 // When the salt is empty build a new one, else use the first x configured characters as the salt
2050 // Build server string
2051 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2054 $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');
2057 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2059 // Calculate number for generating the code
2060 $a = time() + _ADD - 1;
2062 // Generate SHA1 sum from modula of number and the prime number
2063 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2064 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2065 $sha1 = scrambleString($sha1);
2066 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2067 //* DEBUG: */ $sha1b = descrambleString($sha1);
2068 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2070 // Generate the password salt string
2071 $salt = substr($sha1, 0, getConfig('salt_length'));
2072 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2075 $salt = substr($salt, 0, getConfig('salt_length'));
2076 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2080 return $salt.sha1($salt.$plainText);
2083 function scrambleString($str) {
2087 // Final check, in case of failture it will return unscrambled string
2088 if (strlen($str) > 40) {
2089 // The string is to long
2091 } elseif (strlen($str) == 40) {
2093 $scrambleNums = explode(":", getConfig('pass_scramble'));
2095 // Generate new numbers
2096 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2099 // Scramble string here
2100 //* DEBUG: */ echo "***Original=".$str."***<br />";
2101 for ($idx = 0; $idx < strlen($str); $idx++) {
2102 // Get char on scrambled position
2103 $char = substr($str, $scrambleNums[$idx], 1);
2105 // Add it to final output string
2106 $scrambled .= $char;
2109 // Return scrambled string
2110 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2114 function descrambleString($str) {
2115 // Scramble only 40 chars long strings
2116 if (strlen($str) != 40) return $str;
2118 // Load numbers from config
2119 $scrambleNums = explode(":", getConfig('pass_scramble'));
2122 if (count($scrambleNums) != 40) return $str;
2124 // Begin descrambling
2125 $orig = str_repeat(" ", 40);
2126 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2127 for ($idx = 0; $idx < 40; $idx++) {
2128 $char = substr($str, $idx, 1);
2129 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2132 // Return scrambled string
2133 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2137 function genScrambleString($len) {
2138 // Prepare randomizer and array for the numbers
2139 mt_srand((double) microtime() * 1000000);
2140 $scrambleNumbers = array();
2142 // First we need to setup randomized numbers from 0 to 31
2143 for ($idx = 0; $idx < $len; $idx++) {
2145 $rand = mt_rand(0, ($len -1));
2147 // Check for it by creating more numbers
2148 while (array_key_exists($rand, $scrambleNumbers)) {
2149 $rand = mt_rand(0, ($len -1));
2153 $scrambleNumbers[$rand] = $rand;
2156 // So let's create the string for storing it in database
2157 $scrambleString = implode(":", $scrambleNumbers);
2158 return $scrambleString;
2160 // Append data like session ID or referal ID to the given URL which would
2161 // normally be stored in cookies
2162 function ADD_URL_DATA ($URL) {
2166 // Determine URL binder
2168 if (strpos($URL, "?") !== false) $BIND = "&";
2170 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2171 // Cookies are not accepted
2172 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2173 // Cookie found in URL
2174 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2175 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2176 // Not found! So let's set default here
2177 $ADD .= $BIND."refid=".getConfig('def_refid');
2180 // Is there already added data? Then change the binder
2181 if (!empty($ADD)) $BIND = "&";
2184 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2185 // Add session from URL
2186 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2188 // Add current session
2189 $ADD .= $BIND."PHPSESSID=".session_id();
2193 // Add all together and return it
2196 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2197 function generatePassString($passHash) {
2198 // Return vanilla password hash
2201 // Is a secret key and master salt already initialized?
2202 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2203 // Only calculate when the secret key is generated
2204 $newHash = ""; $start = 9;
2205 for ($idx = 0; $idx < 10; $idx++) {
2206 $part1 = hexdec(substr($passHash, $start, 4));
2207 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2208 $mod = dechex($idx);
2209 if ($part1 > $part2) {
2210 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2211 } elseif ($part2 > $part1) {
2212 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2214 $mod = substr(round($mod), 0, 4);
2215 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2216 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2221 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2222 $ret = generateHash($newHash, getConfig('master_salt'));
2223 //* DEBUG: */ print($ret."<br />\n");
2226 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2227 $ret = md5($passHash);
2228 //* DEBUG: */ echo "++".$ret."++<br />\n";
2235 // Fix "deleted" cookies
2236 function FIX_DELETED_COOKIES ($cookies) {
2237 // Is this an array with entries?
2238 if ((is_array($cookies)) && (count($cookies) > 0)) {
2239 // Then check all cookies if they are marked as deleted!
2240 foreach ($cookies as $cookieName) {
2241 // Is the cookie set to "deleted"?
2242 if (get_session($cookieName) == "deleted") {
2243 set_session($cookieName, "");
2249 // Output error messages in a fasioned way and die...
2250 function mxchange_die ($msg) {
2253 // Load the message template
2254 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2257 include(PATH."inc/footer.php");
2263 // Display parsing time and number of SQL queries in footer
2264 function DISPLAY_PARSING_TIME_FOOTER() {
2265 // Is the timer started?
2266 if (!isset($GLOBALS['startTime'])) {
2272 $endTime = microtime(true);
2274 // "Explode" both times
2275 $start = explode(" ", $GLOBALS['startTime']);
2276 $end = explode(" ", $endTime);
2277 $runTime = $end[0] - $start[0];
2278 if ($runTime < 0) $runTime = 0;
2279 $runTime = TRANSLATE_COMMA($runTime);
2283 'runtime' => $runTime,
2284 'numSQLs' => (getConfig('sql_count') + 1),
2285 'numTemplates' => (getConfig('num_templates') + 1)
2288 // Load the template
2289 LOAD_TEMPLATE("show_timings", false, $content);
2292 // Unset/set session variables
2293 function set_session ($var, $value) {
2296 // Abort in CSS mode here
2297 if ($CSS == 1) return true;
2299 // Trim value and session variable
2300 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2302 // Is the session variable set?
2303 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2304 // Remove the session
2305 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2306 unset($_SESSION[$var]);
2307 return session_unregister($var);
2308 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2310 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2311 $_SESSION[$var] = $value;
2312 return session_register($var);
2313 } elseif (!empty($value)) {
2315 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2316 $_SESSION[$var] = $value;
2320 // Ignored (but valid)
2321 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2325 // Check wether a boolean constant is set
2326 // Taken from user comments in PHP documentation for function constant()
2327 function isBooleanConstantAndTrue($constName) { // : Boolean
2330 // Failed by default
2334 if (isset($cacheArray['const'][$constName])) {
2336 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2337 $res = $cacheArray['const'][$constName];
2340 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2341 if (defined($constName)) $res = (constant($constName) === true);
2344 $cacheArray['const'][$constName] = $res;
2346 //* DEBUG: */ var_dump($res);
2352 // Check wether a session variable is set
2353 function isSessionVariableSet ($var) {
2354 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2355 return (isset($_SESSION[$var]));
2357 // Returns wether the value of the session variable or NULL if not set
2358 function get_session ($var) {
2361 // Default is not found! ;-)
2364 // Is the variable there or cached values?
2365 if (isset($cacheArray['session'][$var])) {
2366 // Get cached value (skips a lot SQL_ESCAPE() calles!
2367 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2368 $value = $cacheArray['session'][$var];
2369 } elseif (isSessionVariableSet($var)) {
2370 // Then get it secured!
2371 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2372 $value = SQL_ESCAPE($_SESSION[$var]);
2375 $cacheArray['session'][$var] = $value;
2382 // Send notification to admin
2383 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2384 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2386 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2388 // Send outdated way
2389 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2390 SEND_ADMIN_EMAILS($subject, $msg);
2394 // Destroy user session
2395 function destroy_user_session () {
2397 $GLOBALS['userid'] = 0;
2399 // Remove all user data from session
2400 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2403 // Merges an array together but only if both are arrays
2404 function merge_array ($array1, $array2) {
2405 // Are both an array?
2406 if ((is_array($array1)) && (is_array($array2))) {
2407 // Merge all together
2408 return array_merge($array1, $array2);
2409 } elseif (is_array($array1)) {
2410 // Return left array
2414 // Something wired happened here...
2415 print(__FUNCTION__.":<pre>");
2416 debug_print_backtrace();
2420 // Debug message logger
2421 function DEBUG_LOG ($file, $line, $message, $force=true) {
2422 // Is debug mode enabled?
2423 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2424 // Log this message away
2425 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2426 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2431 // Reads a directory with PHP files in and gets only files back
2432 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2436 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2439 while ($baseFile = readdir($dirPointer)) {
2440 // Load file only if extension is active
2442 $file = $baseDir.$baseFile;
2444 // Is this a valid reset file?
2445 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2446 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2447 // Remove both for extension name
2448 $extName = substr($baseFile, strlen($prefix), -4);
2451 $extId = GET_EXT_ID($extName);
2453 // Is the extension valid and active?
2454 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2455 // Then add this file
2457 } elseif ($extId == 0) {
2458 // Add non-extension files as well
2465 closedir($dirPointer);
2470 // Return array with include files
2473 // Load more reset scripts
2474 function RESET_ADD_INCLUDES () {
2475 // Is the reset set or old sql_patches?
2476 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2481 // Get more daily reset scripts
2482 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2485 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2487 // Create current week mark
2488 $currWeek = date("W", time());
2491 if (getConfig('last_week') != $currWeek) {
2492 // Include weekly reset scripts
2493 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2496 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2499 // Create current month mark
2500 $currMonth = date("m", time());
2503 if (getConfig('last_month') != $currMonth) {
2504 // Include monthly reset scripts
2505 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2508 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2514 // Handle extra values
2515 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2516 // Default is the value itself
2519 // Do we have a special filter function?
2520 if (!empty($filterFunction)) {
2521 // Does the filter function exist?
2522 if (function_exists($filterFunction)) {
2523 // Do we have extra parameters here?
2524 if (!empty($extraValue)) {
2525 // Put both parameters in one new array by default
2526 $args = array($value, $extraValue);
2528 // If we have an array simply use it and pre-extend it with our value
2529 if (is_array($extraValue)) {
2530 // Make the new args array
2531 $args = merge_array(array($value), $extraValue);
2534 // Call the multi-parameter call-back
2535 $ret = call_user_func_array($filterFunction, $args);
2537 // One parameter call
2538 $ret = call_user_func($filterFunction, $value);
2546 // Check if given FQFN is a readable file
2547 function FILE_READABLE($fqfn) {
2549 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2551 // Converts timestamp selections into a timestamp
2552 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2553 // Init test variable
2556 // Get last three chars
2557 $test = substr($id, -3);
2559 // Improved way of checking! :-)
2560 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2561 // Found a multi-selection for timings?
2562 $test = substr($id, 0, -3);
2563 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)) {
2564 // Generate timestamp
2565 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2566 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2568 // Remove data from array
2569 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2570 unset($POST[$test."_".$rem]);
2574 unset($id); $skip = true; $test2 = $test;
2577 // Process this entry
2578 $skip = false; $test2 = "";
2581 // Reverts the german decimal comma into Computer decimal dot
2582 function REVERT_COMMA ($str) {
2583 // Default float is not a float... ;-)
2586 // Which language is selected?
2587 switch (GET_LANGUAGE()) {
2588 case "de": // German language
2589 // Remove german thousand dots first
2590 $str = str_replace(".", "", $str);
2592 // Replace german commata with decimal dot and cast it
2593 $float = (float)str_replace(",", ".", $str);
2596 default: // US and so on
2597 // Remove thousand dots first and cast
2598 $float = (float)str_replace(",", "", $str);
2606 // Handle menu-depending failed logins and return the rendered content
2607 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2608 // Default output is empty ;-)
2611 // Is the session data set?
2612 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2613 // Ignore zero values
2614 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2615 // Non-guest has login failtures found, get both data and prepare it for template
2616 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2618 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2619 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2623 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2626 // Reset session data
2627 set_session('mxchange_'.$accessLevel.'_failtures', "");
2628 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2631 // Return rendered content
2636 function REBUILD_CACHE ($cache, $inc="") {
2637 global $cacheInstance, $CSS;
2639 // Shall I remove the cache file?
2640 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2642 if ($cacheInstance->loadCacheFile($cache)) {
2644 $cacheInstance->destroyCacheFile();
2647 // Include file given?
2650 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2652 // Is the include there?
2653 if (FILE_READABLE($fqfn)) {
2654 // And rebuild it from scratch
2655 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2658 // Include not found!
2659 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2665 // Purge admin menu cache
2666 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2667 global $cacheInstance;
2669 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2670 if (!EXT_IS_ACTIVE("cache")) {
2671 // Cache extension not active
2673 } elseif (!is_object($cacheInstance)) {
2674 // No cache instance!
2675 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2677 } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2678 // Caching disabled (currently experiemental!)
2682 // Experiemental feature!
2683 trigger_error("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2686 // Translates the "pool type" into human-readable
2687 function TRANSLATE_POOL_TYPE ($type) {
2688 // Default type is unknown
2689 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2691 // Generate constant
2692 $constName = sprintf("POOL_TYPE_%s", $type);
2695 if (defined($constName)) {
2697 $translated = constant($constName);
2700 // Return "translation"
2704 // "Getter" for remote IP number
2705 function GET_REMOTE_ADDR () {
2706 // Get remote ip from environment
2707 $remoteAddr = getenv('REMOTE_ADDR');
2709 // Is removeip installed?
2710 if (EXT_IS_ACTIVE("removeip")) {
2711 // Then anonymize it
2712 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2718 // "Getter" for remote hostname
2719 function GET_REMOTE_HOST () {
2720 // Get remote ip from environment
2721 $remoteHost = getenv('REMOTE_HOST');
2723 // Is removeip installed?
2724 if (EXT_IS_ACTIVE("removeip")) {
2725 // Then anonymize it
2726 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2732 // "Getter" for user agent
2733 function GET_USER_AGENT () {
2734 // Get remote ip from environment
2735 $userAgent = getenv('HTTP_USER_AGENT');
2737 // Is removeip installed?
2738 if (EXT_IS_ACTIVE("removeip")) {
2739 // Then anonymize it
2740 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2746 // "Getter" for referer
2747 function GET_REFERER () {
2748 // Get remote ip from environment
2749 $referer = getenv('HTTP_REFERER');
2751 // Is removeip installed?
2752 if (EXT_IS_ACTIVE("removeip")) {
2753 // Then anonymize it
2754 $referer = GET_ANONYMOUS_REFERER($referer);
2761 // Adds a bonus mail to the queue
2762 // This is a high-level function!
2763 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2764 // Use mode from data if not set and availble ;-)
2765 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2767 // Generate receiver list
2768 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2771 if (!empty($RECEIVER)) {
2772 // Add bonus mail to queue
2773 ADD_BONUS_MAIL_TO_QUEUE(
2785 // Mail inserted into bonus pool
2786 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2787 } elseif ($output) {
2788 // More entered than can be reached!
2789 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2792 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2795 // Determines referal id and sets it
2796 function DETERMINE_REFID () {
2797 global $CLICK, $_SERVER;
2799 // Check if refid is set
2800 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2801 // The variable user comes from the click-counter script click.php and we only accept this here
2802 $GLOBALS['refid'] = bigintval($_GET['user']);
2803 } elseif (!empty($_POST['refid'])) {
2804 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2805 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2806 } elseif (!empty($_GET['refid'])) {
2807 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2808 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2809 } elseif (!empty($_GET['ref'])) {
2810 // Set refid=ref (the referal link uses such variable)
2811 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2812 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2813 // Set session refid als global
2814 $GLOBALS['refid'] = bigintval(get_session('refid'));
2815 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2816 // Set default refid as refid in URL
2817 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2818 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2819 // Select a random user which has confirmed enougth mails
2820 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2822 // No default ID when sql_patches is not installed or none set
2823 $GLOBALS['refid'] = 0;
2826 // Set cookie when default refid > 0
2827 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2829 set_session('refid', $GLOBALS['refid']);
2832 // Return determined refid
2833 return $GLOBALS['refid'];
2836 // Destroys the admin session
2837 function DESTROY_ADMIN_SESSION ($destroy = true) {
2838 // Kill maybe existing session variables including array elements
2839 set_session('admin_login', "");
2840 set_session('admin_md5' , "");
2841 set_session('admin_last' , "");
2842 set_session('admin_to' , "");
2844 // Destroy session and return status
2846 return @session_destroy();
2849 // All fine if we shall not really destroy the session
2853 // Checks if a given apache module is loaded
2854 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2855 // Check it and return result
2856 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2859 // Getter for $_CONFIG entries
2860 function getConfig ($entry) {
2866 // Is the entry there?
2867 if (isset($_CONFIG[$entry])) {
2869 $value = $_CONFIG[$entry];
2876 // @TODO Rewrite all language constants to the function getLanguage().
2877 // "Getter" for language strings
2878 function getMessage ($messageId) {
2879 // Default is not found!
2880 $return = "!".$messageId."!";
2882 // Is the language string found?
2883 if (isset($GLOBALS['msg'][$messageId])) {
2884 // Language array element found
2885 $return = $GLOBALS['msg'][$messageId];
2886 } elseif (defined($messageId)) {
2887 // @DEPRECATED Deprecated constant found
2888 $return = constant($messageId);
2890 // Missing language constant
2891 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2894 // Return the string
2898 // Get current theme name
2899 function GET_CURR_THEME() {
2900 global $INC_POOL, $CSS, $cacheArray;
2902 // The default theme is 'default'... ;-)
2905 // Load default theme if not empty from configuration
2906 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2908 if (!isSessionVariableSet('mxchange_theme')) {
2909 // Set default theme
2910 set_session('mxchange_theme', $ret);
2911 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2912 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2913 // Get theme from cookie
2914 $ret = get_session('mxchange_theme');
2917 if (THEME_GET_ID($ret) == 0) {
2918 // Fix it to default
2921 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2922 // Prepare FQFN for checking
2923 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_GET['theme']));
2925 // Installation mode active
2926 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2927 // Set cookie from URL data
2928 set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
2929 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_POST['theme'])))) {
2930 // Set cookie from posted data
2931 set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
2935 $ret = get_session('mxchange_theme');
2937 // Invalid design, reset cookie
2938 set_session('mxchange_theme', $ret);
2941 // Add (maybe) found theme.php file to inclusion list
2942 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($ret));
2944 // Try to load the requested include file
2945 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2947 // Return theme value
2951 // Get id from theme
2952 function THEME_GET_ID ($name) {
2955 // Is the extension "theme" installed?
2956 if (!EXT_IS_ACTIVE("theme")) {
2964 // Is the cache entry there?
2965 if (isset($cacheArray['themes']['id'][$name])) {
2966 // Get the version from cache
2967 $id = $cacheArray['themes']['id'][$name];
2970 incrementConfigEntry('cache_hits');
2971 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2972 // Check if current theme is already imported or not
2973 $result = SQL_QUERY_ESC("SELECT id FROM `"._MYSQL_PREFIX."_themes` WHERE theme_path='%s' LIMIT 1",
2974 array($name), __FILE__, __LINE__);
2977 if (SQL_NUMROWS($result) == 1) {
2979 list($id) = SQL_FETCHROW($result);
2983 SQL_FREERESULT($result);
2990 // Increment or init with given value or 1 as default the given config entry
2991 function incrementConfigEntry ($configEntry, $value=1) {
2994 // Increment it if set or init it with 1
2995 if (getConfig($configEntry) > 0) {
2996 $_CONFIG[$configEntry] += $value;
2998 $_CONFIG[$configEntry] = $value;
3002 // Read a given file
3003 function READ_FILE ($FQFN, $sqlPrepare = false) {
3005 if (function_exists('file_get_contents')) {
3007 $content = file_get_contents($FQFN);
3009 // Fall-back to implode-file chain
3010 $content = implode("", file($FQFN));
3013 // Prepare SQL queries?
3014 if ($sqlPreppare === true) {
3015 // Remove some unwanted chars
3016 $content = str_replace("\r", "", $content);
3017 $content = str_replace("\n\n", "\n", $content);
3020 // Return the content
3024 // Generates an error code from given account status
3025 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3026 // Default error code if unknown account status
3027 $ERROR = CODE_UNKNOWN_STATUS;
3029 // Generate constant name
3030 $constantName = sprintf("CODE_ID_%s", $status);
3032 // Is the constant there?
3033 if (defined($constantName)) {
3035 $ERROR = constant($constantName);
3038 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3041 // Return error code
3045 //////////////////////////////////////////////////
3046 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3047 //////////////////////////////////////////////////
3049 if (!function_exists('html_entity_decode')) {
3050 // Taken from documentation on www.php.net
3051 function html_entity_decode ($string) {
3052 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3053 $trans_tbl = array_flip($trans_tbl);
3054 return strtr($string, $trans_tbl);