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 addFatalMessage ($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 // Getter for total fatal message count
242 function getTotalFatalMessages () {
248 // Do we have at least the first entry?
249 if (!empty($FATAL[0])) {
251 $count = count($FATAL);
258 // Load a template file and return it's content (only it's name; do not use ' or ")
259 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
260 // Add more variables which you want to use in your template files
261 global $DATA, $_CONFIG, $username;
263 // Make all template names lowercase
264 $template = strtolower($template);
266 // Count the template load
267 incrementConfigEntry('num_templates');
269 // Prepare IP number and User Agent
270 $REMOTE_ADDR = GET_REMOTE_ADDR();
271 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
272 $HTTP_USER_AGENT = GET_USER_AGENT();
276 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
278 // @DEPRECATED Try to rewrite the if() condition
279 if ($template == "member_support_form") {
280 // Support request of a member
281 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
282 array($GLOBALS['userid']), __FILE__, __LINE__);
284 // Is content an array?
285 if (is_array($content)) {
287 $content = merge_array($content, SQL_FETCHARRAY($result));
290 $content['gender'] = TRANSLATE_GENDER($content['gender']);
292 // DEPRECATED: Load data in direct variables
293 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
296 $gender = TRANSLATE_GENDER($gender);
297 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
301 SQL_FREERESULT($result);
304 // Generate date/time string
305 $date_time = MAKE_DATETIME(time(), "1");
308 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
311 // Check for admin/guest/member templates
312 if (strpos($template, "admin_") > -1) {
313 // Admin template found
315 } elseif (strpos($template, "guest_") > -1) {
316 // Guest template found
318 } elseif (strpos($template, "member_") > -1) {
319 // Member template found
321 } elseif (strpos($template, "install_") > -1) {
322 // Installation template found
324 } elseif (strpos($template, "ext_") > -1) {
325 // Extension template found
327 } elseif (strpos($template, "la_") > -1) {
328 // "Logical-area" template found
331 // Test for extension
332 $test = substr($template, 0, strpos($template, "_"));
333 if (EXT_IS_ACTIVE($test)) {
334 // Set extra path to extension's name
339 ////////////////////////
340 // Generate file name //
341 ////////////////////////
342 $file = $BASE.$MODE.$template.".tpl";
344 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
345 // Select what depended header/footer template file for admin/guest/member area
346 $file2 = sprintf("%s%s%s_%s.tpl",
350 SQL_ESCAPE($GLOBALS['what'])
354 if (FILE_READABLE($file2)) $file = $file2;
356 // Remove variable from memory
360 // Does the special template exists?
361 if (!FILE_READABLE($file)) {
362 // Reset to default template
363 $file = $BASE.$template.".tpl";
366 // Now does the final template exists?
367 if (FILE_READABLE($file)) {
368 // The local file does exists so we load it. :)
369 $tmpl_file = READ_FILE($file);
371 // Replace ' to our own chars to preventing them being quoted
372 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
374 // Do we have to compile the code?
376 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
378 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
381 // Simply return loaded code
385 // Add surrounding HTML comments to help finding bugs faster
386 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
387 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
388 // Only admins shall see this warning or when installation mode is active
389 $ret = "<br /><SPAN class=\"guest_failed\">".TEMPLATE_404."</SPAN><br />
390 (".basename($file).")<br />
393 <pre>".print_r($content, true)."</pre>
395 <pre>".print_r($DATA, true)."</pre>
399 // Remove content and data
403 // Do we have some content to output or return?
405 // Not empty so let's put it out! ;)
407 // Return the HTML code
413 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
414 // Warning, empty output!
415 return "E:".$template."<br />\n";
419 // Send mail out to an email address
420 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
421 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
423 // Compile subject line (for POINTS constant etc.)
424 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
428 if ((!eregi("@", $TO)) && ($TO > 0)) {
429 // Value detected, is the message extension installed?
430 if (EXT_IS_ACTIVE("msg")) {
431 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
434 // Load email address
435 $result_email = SQL_QUERY_ESC("SELECT email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
436 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
438 // Does the user exist?
439 if (SQL_NUMROWS($result_email)) {
440 // Load email address
441 list($TO) = SQL_FETCHROW($result_email);
448 SQL_FREERESULT($result_email);
450 } elseif ("$TO" == "0") {
454 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
456 // Check for PHPMailer or debug-mode
457 if (!CHECK_PHPMAILER_USAGE()) {
458 // Not in PHPMailer-Mode
460 // Load email header template
461 $FROM = LOAD_EMAIL_TEMPLATE("header");
464 $FROM .= LOAD_EMAIL_TEMPLATE("header");
466 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
468 // Load email header template
469 $FROM = LOAD_EMAIL_TEMPLATE("header");
472 $FROM .= LOAD_EMAIL_TEMPLATE("header");
477 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
481 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
484 // Fix HTML parameter (default is no!)
485 if (empty($HTML)) $HTML = "N";
486 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
487 // In debug mode we want to display the mail instead of sending it away so we can debug this part
489 ".htmlentities(trim($FROM))."
491 Subject : ".$SUBJECT."
494 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
495 // Send mail as HTML away
496 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
497 } elseif (!empty($TO)) {
499 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
500 } elseif ($HTML == "N") {
502 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
506 // Check if legacy or PHPMailer command
508 function CHECK_PHPMAILER_USAGE() {
509 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
513 * Send out a raw email with PHPMailer class or legacy mail() command
515 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
516 // Shall we use PHPMailer class or legacy mode?
517 if (CHECK_PHPMAILER_USAGE()) {
518 // Use PHPMailer class with SMTP enabled
519 require_once(PATH."inc/phpmailer/class.phpmailer.php");
520 require_once(PATH."inc/phpmailer/class.smtp.php");
523 $mail = new PHPMailer();
524 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
527 $mail->SMTPAuth = true;
528 $mail->Host = SMTP_HOSTNAME;
530 $mail->Username = SMTP_USER;
531 $mail->Password = SMTP_PASSWORD;
533 $mail->From = WEBMASTER;
537 $mail->FromName = MAIN_TITLE;
538 $mail->Subject = $subject;
539 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
541 $mail->AltBody = "Your mail program required HTML support to read this mail!";
542 $mail->WordWrap = 70;
545 $mail->Body = html_entity_decode($msg);
547 $mail->AddAddress($to, "");
548 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
549 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
550 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
553 // Use legacy mail() command
554 @mail($to, $subject, html_entity_decode($msg), $from);
559 // Generate a password in a specified length or use default password length
560 function GEN_PASS ($LEN = 0) {
561 // Auto-fix invalid length of zero
562 if ($LEN == 0) $LEN = getConfig('pass_len');
564 // Initialize array with all allowed chars
565 $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,-,+,_,/");
567 // Initialize randomizer
568 mt_srand((double) microtime() * 1000000);
570 // Start creating password
572 for ($i = 0; $i < $LEN; $i++) {
573 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
576 // When the size is below 40 we can also add additional security by scrambling it
577 if (strlen($PASS) <= 40) {
578 // Also scramble the password
579 $PASS = scrambleString($PASS);
582 // Return the password
586 function MAKE_DATETIME ($time, $mode="0")
590 return NEVER_HAPPENED;
592 // Filter out numbers
593 $time = bigintval($time);
596 switch (GET_LANGUAGE())
598 case "de": // German date / time format
600 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
601 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
602 case "2": $ret = date("d.m.Y|H:i", $time); break;
603 case "3": $ret = date("d.m.Y", $time); break;
605 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
610 default: // Default is the US date / time format!
612 case "0": $ret = date("r", $time); break;
613 case "1": $ret = date("Y-m-d - g:i A", $time); break;
614 case "2": $ret = date("y-m-d|H:i", $time); break;
615 case "3": $ret = date("y-m-d", $time); break;
617 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
624 // Translates the american decimal dot into a german comma
625 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
628 // Default is 3 you can change this in admin area "Misc -> Misc Options"
629 if (getConfig('max_comma') == null) $_CONFIG['max_comma'] = "3";
631 // Use from config is default
632 $maxComma = getConfig('max_comma');
634 // Use from parameter?
635 if ($max > 0) $maxComma = $max;
638 if (($cut) && ($max == 0)) {
639 // Test for commata if in cut-mode
640 $com = explode(".", $dotted);
641 if (count($com) < 2) {
642 // Don't display commatas even if there are none... ;-)
648 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
651 switch (GET_LANGUAGE()) {
653 $dotted = number_format($dotted, $maxComma, ",", ".");
657 $dotted = number_format($dotted, $maxComma, ".", ",");
661 // Return translated value
666 function DEREFERER ($URL) {
667 // Don't de-refer our own links!
668 if (substr($URL, 0, strlen(URL)) != URL) {
669 // De-refer this link
670 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
678 function TRANSLATE_GENDER ($gender) {
681 case "M": $ret = GENDER_M; break;
682 case "F": $ret = GENDER_F; break;
683 case "C": $ret = GENDER_C; break;
684 default : $ret = $gender; break;
689 function FRAMETESTER($URL) {
690 // Prepare frametester URL
691 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
693 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
695 return $frametesterUrl;
698 function SELECTION_COUNT($array) {
700 if (is_array($array)) {
701 foreach ($array as $key => $sel) {
702 if (!empty($sel)) $ret++;
708 function IMG_CODE ($code, $type, $DATA, $uid) {
709 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
712 function TRANSLATE_STATUS($status) {
716 $ret = ACCOUNT_UNCONFIRMED;
720 $ret = ACCOUNT_CONFIRMED;
724 $ret = ACCOUNT_LOCKED;
729 $ret = ACCOUNT_DELETED;
733 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
734 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
740 function GET_LANGUAGE() {
743 // Set default return value to default language from config
749 // Is the variable set
750 if (!empty($_GET['mx_lang'])) {
751 // Accept only first 2 chars
752 $lang = substr($_GET['mx_lang'], 0, 2);
753 } elseif (isset($cacheArray['language'])) {
755 $ret = $cacheArray['language'];
756 } elseif (!empty($lang)) {
757 // Check if main language file does exist
758 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
759 // Okay found, so let's update cookies
762 } elseif (!isSessionVariableSet('mx_lang')) {
763 // Return stored value from cookie
764 $ret = get_session('mx_lang');
766 // Fixes a warning before the session has the mx_lang constant
767 if (empty($ret)) $ret = DEFAULT_LANG;
771 $cacheArray['language'] = $ret;
777 function SET_LANGUAGE ($lang) {
778 // Accept only first 2 chars!
779 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
782 set_session('mx_lang', $lang);
785 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
786 global $DATA, $REPLACER, $_CONFIG;
788 // Make sure all template names are lowercase!
789 $template = strtolower($template);
791 // Default "nickname" if extension is not installed
794 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
795 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
797 // Prepare IP number and User Agent
798 $REMOTE_ADDR = GET_REMOTE_ADDR();
799 $HTTP_USER_AGENT = GET_USER_AGENT();
804 // Is the admin logged in?
807 $aid = GET_CURRENT_ADMIN_ID();
810 $ADMIN = GET_ADMIN_EMAIL($aid);
813 // Neutral email address is default
816 // Expiration in a nice output format
817 if (getConfig('auto_purge') == 0) {
818 // Will never expire!
819 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
820 } elseif (function_exists('CREATE_FANCY_TIME')) {
821 // Create nice date string
822 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
825 $EXPIRATION = round(getConfig('auto_purge')/60/60/24)." "._DAYS;
828 // Is content an array?
829 if (is_array($content)) {
830 // Add expiration to array, $EXPIRATION is now deprecated!
831 $content['expiration'] = $EXPIRATION;
835 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
836 if (($UID > 0) && (is_array($content))) {
837 // If nickname extension is installed, fetch nickname as well
838 if (EXT_IS_ACTIVE("nickname")) {
839 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
841 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
842 array(bigintval($UID)), __FILE__, __LINE__);
844 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
846 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
847 array(bigintval($UID)), __FILE__, __LINE__);
850 // Fetch and merge data
851 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
852 $content = merge_array($content, SQL_FETCHARRAY($result));
853 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
856 SQL_FREERESULT($result);
859 // Translate M to male or F to female if present
860 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
862 // Overwrite email from data if present
863 if (isset($content['email'])) $email = $content['email'];
865 // Store email for some functions in global data array
866 $DATA['email'] = $email;
869 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
871 // Check for admin/guest/member templates
872 if (strpos($template, "admin_") > -1) {
873 // Admin template found
874 $file = $BASE."admin/".$template.".tpl";
875 } elseif (strpos($template, "guest_") > -1) {
876 // Guest template found
877 $file = $BASE."guest/".$template.".tpl";
878 } elseif (strpos($template, "member_") > -1) {
879 // Member template found
880 $file = $BASE."member/".$template.".tpl";
882 // Test for extension
883 $test = substr($template, 0, strpos($template, "_"));
884 if (EXT_IS_ACTIVE($test)) {
885 // Set extra path to extension's name
886 $file = $BASE.$test."/".$template.".tpl";
888 // No special filename
889 $file = $BASE.$template.".tpl";
893 // Does the special template exists?
894 if (!FILE_READABLE($file)) {
895 // Reset to default template
896 $file = $BASE.$template.".tpl";
899 // Now does the final template exists?
901 if (FILE_READABLE($file)) {
902 // The local file does exists so we load it. :)
903 $tmpl_file = READ_FILE($file);
904 $tmpl_file = addslashes($tmpl_file);
907 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
909 } elseif (!empty($template)) {
910 // Template file not found!
911 $newContent = TEMPLATE_404.": ".$template."<br />
913 <pre>".print_r($content, true)."</pre>
915 <pre>".print_r($DATA, true)."</pre>
918 // Debug mode not active? Then remove the HTML tags
919 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
921 // No template name supplied!
922 $newContent = NO_TEMPLATE_SUPPLIED;
925 // Is there some content?
926 if (empty($newContent)) {
928 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
929 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
932 // Remove content and data
936 // Return compiled content
937 return COMPILE_CODE($newContent);
940 function MAKE_TIME($H, $M, $S, $stamp) {
941 // Extract day, month and year from given timestamp
942 $DAY = date("d", $stamp);
943 $MONTH = date("m", $stamp);
944 $YEAR = date('Y', $stamp);
946 // Create timestamp for wished time which depends on extracted date
947 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
950 function LOAD_URL($URL, $addUrlData=true) {
951 global $CSS, $footer;
953 // Compile out URI codes
954 $URL = COMPILE_CODE($URL);
956 // Check if http(s):// is there
957 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
958 // Make all URLs full-qualified
965 debug_print_backtrace();
968 $OUTPUT = ob_get_contents();
970 // Clear it only if there is content
971 if (!empty($OUTPUT)) {
975 // Add some data to URL if cookies are not accepted
976 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
978 // Probe for bot from search engine
979 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
980 // Search engine bot detected so let's rewrite many chars for the link
981 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
983 // Output new location link as anchor
984 OUTPUT_HTML("<A href=\"".$URL."\">".$URL."</A>");
985 } elseif (!headers_sent()) {
986 // Load URL when headers are not sent
989 debug_print_backtrace();
990 die("</pre>URL={$URL}");
992 @header ("Location: ".str_replace("&", "&", $URL));
994 // Output error message
995 include(PATH."inc/header.php");
996 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
997 include(PATH."inc/footer.php");
1002 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
1003 global $SEC_CHARS, $URL_CHARS;
1004 // Is the code a string?
1005 if (!is_string($code)) {
1006 // Silently return it
1010 $ARRAY = $SEC_CHARS;
1012 // Select smaller set of chars to replace when we e.g. want to compile URLs
1013 if (!$full) $ARRAY = $URL_CHARS;
1015 // Compile constants
1017 // BEFORE 0.2.1 : Language and data constants
1018 // WITH 0.2.1+ : Only language constants
1019 $code = str_replace('{--','".', str_replace('--}','."', $code));
1021 // BEFORE 0.2.1 : Not used
1022 // WITH 0.2.1+ : Data constants
1023 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1026 // Compile QUOT and other non-HTML codes
1027 foreach ($ARRAY['to'] as $k => $to) {
1028 // Do the reversed thing as in inc/libs/security_functions.php
1029 $code = str_replace($to, $ARRAY['from'][$k], $code);
1032 // But shall I keep simple quotes for later use?
1033 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1035 // Find $content[bla][blub] entries
1036 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1038 // Are some matches found?
1039 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1040 // Replace all matches
1041 $matchesFound = array();
1042 foreach ($matches[0] as $key => $match) {
1043 // Fuzzy look has failed by default
1044 $fuzzyFound = false;
1046 // Fuzzy look on match if already found
1047 foreach ($matchesFound as $found => $set) {
1049 $test = substr($found, 0, strlen($match));
1051 // Does this entry exist?
1052 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1053 if ($test == $match) {
1055 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1062 if ($fuzzyFound) continue;
1064 // Take all string elements
1065 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1066 // Replace it in the code
1067 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1068 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1069 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1070 $matchesFound[$key."_".$matches[4][$key]] = 1;
1071 $matchesFound[$match] = 1;
1072 } elseif (!isset($matchesFound[$match])) {
1073 // Not yet replaced!
1074 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1075 $code = str_replace($match, "\".".$match.".\"", $code);
1076 $matchesFound[$match] = 1;
1081 // Return compiled code
1085 /************************************************************************
1087 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1088 * $a_sort sortiert: *
1090 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1091 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1092 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1093 * $order - Sortiereihenfolge: -1 = A-Z, 0 = keine, 1 = Z-A *
1094 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1096 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1097 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1098 * Sie, dass es doch nicht so schwer ist! :-) *
1100 ************************************************************************/
1101 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1104 while ($primary_key < count($a_sort)) {
1105 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1106 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1109 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1110 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1111 } elseif ($key != $key2) {
1112 // Sort numbers (E.g.: 9 < 10)
1113 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1114 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1118 // We have found two different values, so let's sort whole array
1119 foreach ($dummy as $sort_key => $sort_val) {
1120 $t = $dummy[$sort_key][$key];
1121 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1122 $dummy[$sort_key][$key2] = $t;
1133 // Write back sorted array
1137 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1138 global $MONTH_DESCR;
1141 if ($type == "yn") {
1142 // This is a yes/no selection only!
1143 if ($id > 0) $prefix .= "[".$id."]";
1144 $OUT .= " <SELECT name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1146 // Begin with regular selection box here
1147 if (!empty($prefix)) $prefix .= "_";
1149 if ($id > 0) $type2 .= "[".$id."]";
1150 $OUT .= " <SELECT name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1155 for ($idx = 1; $idx < 32; $idx++) {
1156 $OUT .= "<OPTION value=\"".$idx."\"";
1157 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1158 $OUT .= ">".$idx."</OPTION>\n";
1162 case "month": // Month
1163 foreach ($MONTH_DESCR as $month => $descr) {
1164 $OUT .= "<OPTION value=\"".$month."\"";
1165 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1166 $OUT .= ">".$descr."</OPTION>\n";
1170 case "year": // Year
1172 $YEAR = date('Y', time());
1174 // Use configured min age or fixed?
1175 if (GET_EXT_VERSION("other") >= "0.2.1") {
1177 $startYear = $YEAR - getConfig('min_age');
1180 $startYear = $YEAR - 16;
1183 // Calculate earliest year (100 years old people can still enter Internet???)
1184 $minYear = $YEAR - 100;
1186 // Check if the default value is larger than minimum and bigger than actual year
1187 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1188 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1189 $OUT .= "<OPTION value=\"".$idx."\"";
1190 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1191 $OUT .= ">".$idx."</OPTION>\n";
1193 } elseif ($DEFAULT == -1) {
1194 // Current year minus 1
1195 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1197 $OUT .= "<OPTION value=\"".$idx."\">".$idx."</OPTION>\n";
1200 // Get current year and subtract the configured minimum age
1201 $OUT .= "<OPTION value=\"".($minYear - 1)."\"><".$minYear."</OPTION>\n";
1202 // Calculate earliest year depending on extension version
1203 if (GET_EXT_VERSION("other") >= "0.2.1") {
1204 // Use configured minimum age
1205 $YEAR = date('Y', time()) - getConfig('min_age');
1207 // Use fixed 16 years age
1208 $YEAR = date('Y', time()) - 16;
1211 // Construct year selection list
1212 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1213 $OUT .= "<OPTION value=\"".$idx."\"";
1214 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1215 $OUT .= ">".$idx."</OPTION>\n";
1222 for ($idx = 0; $idx < 60; $idx+=5) {
1223 if (strlen($idx) == 1) $idx = "0".$idx;
1224 $OUT .= "<OPTION value=\"".$idx."\"";
1225 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1226 $OUT .= ">".$idx."</OPTION>\n";
1231 for ($idx = 0; $idx < 24; $idx++) {
1232 if (strlen($idx) == 1) $idx = "0".$idx;
1233 $OUT .= "<OPTION value=\"".$idx."\"";
1234 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1235 $OUT .= ">".$idx."</OPTION>\n";
1240 $OUT .= "<OPTION value=\"Y\"";
1241 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1242 $OUT .= ">".YES."</OPTION>\n<OPTION value=\"N\"";
1243 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1244 $OUT .= ">".NO."</OPTION>\n";
1247 $OUT .= " </SELECT>\n";
1251 function TRANSLATE_YESNO($yn)
1255 case "Y": $yn = YES; break;
1256 case "N": $yn = NO; break;
1257 default : $yn = "??? (".$yn.")"; break;
1262 // Deprecated : $length
1265 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1266 // Fix missing _MAX constant
1267 if (!defined('_MAX')) define('_MAX', 15235);
1269 // Build server string
1270 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1273 $keys = SITE_KEY.":".DATE_KEY;
1274 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1275 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1276 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1277 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1279 // Build string from misc data
1280 $data = $code.":".$uid.":".$DATA;
1282 // Add more additional data
1283 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1284 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1285 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1286 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1287 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1289 // Calculate number for generating the code
1290 $a = $code + _ADD - 1;
1292 if (getConfig('master_hash') != null) {
1293 // Generate hash with master salt from modula of number with the prime number and other data
1294 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1296 // Create number from hash
1297 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1299 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1300 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1302 // Create number from hash
1303 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1306 // At least 10 numbers shall be secure enought!
1307 $len = getConfig('code_length');
1308 if ($len == 0) $len = $length;
1309 if ($len == 0) $len = 10;
1311 // Cut off requested counts of number
1312 $return = substr(str_replace('.', "", $rcode), 0, $len);
1314 // Done building code
1317 // Does only allow numbers
1318 function bigintval($num, $castValue = true) {
1319 // Filter all numbers out
1320 $ret = preg_replace("/[^0123456789]/", "", $num);
1323 if ($castValue) $ret = (double)$ret;
1325 // Has the whole value changed?
1326 if ("".$ret."" != "".$num."") {
1329 debug_print_backtrace();
1331 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1337 // Insert the code in $img_code into jpeg or PNG image
1338 function GENERATE_IMAGE($img_code, $header=true) {
1339 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1340 // Stop execution of function here because of over-sized code length
1342 } elseif (!$header) {
1343 // Return in an HTML code code
1344 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1348 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), getConfig('img_type'));
1349 if (FILE_READABLE($img)) {
1350 // Switch image type
1351 switch (getConfig('img_type'))
1354 // Okay, load image and hide all errors
1355 $image = @imagecreatefromjpeg($img);
1359 // Okay, load image and hide all errors
1360 $image = @imagecreatefrompng($img);
1364 // Exit function here
1368 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1369 $text_color = imagecolorallocate($image, 0, 0, 0);
1371 // Insert code into image
1372 imagestring($image, 5, 14, 2, $img_code, $text_color);
1374 // Return to browser
1375 header ("Content-Type: image/".getConfig('img_type'));
1377 // Output image with matching image factory
1378 switch (getConfig('img_type')) {
1379 case "jpg": imagejpeg($image); break;
1380 case "png": imagepng($image); break;
1383 // Remove image from memory
1384 imagedestroy($image);
1386 // Create selection box or array of splitted timestamp
1387 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1388 // Calculate 2-seconds timestamp
1389 $stamp = round($timestamp);
1390 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1392 // Do we have a leap year?
1394 $TEST = date('Y', time()) / 4;
1395 $M1 = date("m", time());
1396 $M2 = date("m", (time() + $timestamp));
1398 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1399 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1401 // First of all years...
1402 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1403 //* DEBUG: */ print("Y={$Y}<br />\n");
1405 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1406 //* DEBUG: */ print("M={$M}<br />\n");
1408 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1409 //* DEBUG: */ print("W={$W}<br />\n");
1411 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1412 //* DEBUG: */ print("D={$D}<br />\n");
1414 $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));
1415 //* DEBUG: */ print("h={$h}<br />\n");
1417 $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));
1418 //* DEBUG: */ print("m={$m}<br />\n");
1419 // And at last seconds...
1420 $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));
1421 //* DEBUG: */ print("s={$s}<br />\n");
1423 // Is seconds zero and time is < 60 seconds?
1424 if (($s == 0) && ($timestamp < 60)) {
1426 $s = round($timestamp);
1430 // Now we convert them in seconds...
1432 if ($return_array) {
1433 // Just put all data in an array for later use
1445 $OUT = "<DIV align=\"".$align."\">\n";
1446 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1449 if (ereg('Y', $display) || (empty($display))) {
1450 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._YEARS."</STRONG></TD>\n";
1453 if (ereg("M", $display) || (empty($display))) {
1454 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MONTHS."</STRONG></TD>\n";
1457 if (ereg("W", $display) || (empty($display))) {
1458 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._WEEKS."</STRONG></TD>\n";
1461 if (ereg("D", $display) || (empty($display))) {
1462 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._DAYS."</STRONG></TD>\n";
1465 if (ereg("h", $display) || (empty($display))) {
1466 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._HOURS."</STRONG></TD>\n";
1469 if (ereg("m", $display) || (empty($display))) {
1470 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._MINUTES."</STRONG></TD>\n";
1473 if (ereg("s", $display) || (empty($display))) {
1474 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><STRONG class=\"tiny\">"._SECONDS."</STRONG></TD>\n";
1480 if (ereg('Y', $display) || (empty($display))) {
1481 // Generate year selection
1482 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1483 for ($idx = 0; $idx <= 10; $idx++) {
1484 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1485 if ($idx == $Y) $OUT .= " selected default";
1486 $OUT .= ">".$idx."</OPTION>\n";
1488 $OUT .= " </SELECT></TD>\n";
1490 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\">\n";
1493 if (ereg("M", $display) || (empty($display))) {
1494 // Generate month selection
1495 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1496 for ($idx = 0; $idx <= 11; $idx++)
1498 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1499 if ($idx == $M) $OUT .= " selected default";
1500 $OUT .= ">".$idx."</OPTION>\n";
1502 $OUT .= " </SELECT></TD>\n";
1504 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\">\n";
1507 if (ereg("W", $display) || (empty($display))) {
1508 // Generate week selection
1509 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1510 for ($idx = 0; $idx <= 4; $idx++) {
1511 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1512 if ($idx == $W) $OUT .= " selected default";
1513 $OUT .= ">".$idx."</OPTION>\n";
1515 $OUT .= " </SELECT></TD>\n";
1517 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\">\n";
1520 if (ereg("D", $display) || (empty($display))) {
1521 // Generate day selection
1522 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1523 for ($idx = 0; $idx <= 31; $idx++) {
1524 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1525 if ($idx == $D) $OUT .= " selected default";
1526 $OUT .= ">".$idx."</OPTION>\n";
1528 $OUT .= " </SELECT></TD>\n";
1530 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1533 if (ereg("h", $display) || (empty($display))) {
1534 // Generate hour selection
1535 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1536 for ($idx = 0; $idx <= 23; $idx++) {
1537 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1538 if ($idx == $h) $OUT .= " selected default";
1539 $OUT .= ">".$idx."</OPTION>\n";
1541 $OUT .= " </SELECT></TD>\n";
1543 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1546 if (ereg("m", $display) || (empty($display))) {
1547 // Generate minute selection
1548 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1549 for ($idx = 0; $idx <= 59; $idx++) {
1550 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1551 if ($idx == $m) $OUT .= " selected default";
1552 $OUT .= ">".$idx."</OPTION>\n";
1554 $OUT .= " </SELECT></TD>\n";
1556 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1559 if (ereg("s", $display) || (empty($display))) {
1560 // Generate second selection
1561 $OUT .= " <TD align=\"center\"><SELECT class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1562 for ($idx = 0; $idx <= 59; $idx++) {
1563 $OUT .= " <OPTION class=\"mini_select\" value=\"".$idx."\"";
1564 if ($idx == $s) $OUT .= " selected default";
1565 $OUT .= ">".$idx."</OPTION>\n";
1567 $OUT .= " </SELECT></TD>\n";
1569 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1572 $OUT .= "</TABLE>\n";
1574 // Return generated HTML code
1579 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1580 // Initial return value
1583 // Do we have a leap year?
1585 $TEST = date('Y', time()) / 4;
1586 $M1 = date("m", time());
1587 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1588 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1589 // First add years...
1590 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1592 $ret += $POST[$prefix."_mo"] * 2628000;
1594 $ret += $POST[$prefix."_we"] * 604800;
1596 $ret += $POST[$prefix."_da"] * 86400;
1598 $ret += $POST[$prefix."_ho"] * 3600;
1600 $ret += $POST[$prefix."_mi"] * 60;
1601 // And at last seconds...
1602 $ret += $POST[$prefix."_se"];
1603 // Return calculated value
1606 // Sends out mail to all administrators
1607 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1608 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1609 // Trim template name
1610 $template = trim($template);
1612 // Load email template
1613 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1615 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1616 // Older version detected!
1617 return SEND_ADMIN_EMAILS($subj, $msg);
1620 // Check which admin shall receive this mail
1621 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1622 array($template), __FILE__, __LINE__);
1623 if (SQL_NUMROWS($result) == 0) {
1624 // Create new entry (to all admins)
1625 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1626 array($template), __FILE__, __LINE__);
1628 // Load admin IDs...
1630 while(list($aid) = SQL_FETCHROW($result)) {
1635 SQL_FREERESULT($result);
1637 // "implode" IDs and query string
1638 $aid = implode(",", $aids);
1640 // Add line to userlog
1641 USERLOG_ADD_LINE($subj, $msg, $UID);
1643 } elseif ($aid == "0") {
1644 // Select all email adresses
1645 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1647 // If Admin-ID is not "to-all" select
1648 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1652 // Load email addresses and send away
1653 while (list($email) = SQL_FETCHROW($result)) {
1654 SEND_EMAIL($email, $subj, $msg);
1658 SQL_FREERESULT($result);
1661 function CREATE_FANCY_TIME ($stamp) {
1662 // Get data array with years/months/weeks/days/...
1663 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1665 foreach($data as $k => $v) {
1667 // Value is greater than 0 "eval" data to return string
1668 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1674 // Do we have something there?
1675 if (strlen($ret) > 0) {
1676 // Remove leading commata and space
1677 $ret = substr($ret, 2);
1680 $ret = "0 "._SECONDS;
1683 // Return fancy time string
1687 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1688 $SEP = ""; $TOP = "";
1691 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1695 for ($page = 1; $page <= $PAGES; $page++) {
1696 // Is the page currently selected or shall we generate a link to it?
1697 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1698 // Is currently selected, so only highlight it
1699 $NAV .= "<STRONG>-";
1701 // Open anchor tag and add base URL
1702 $NAV .= "<A href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1704 // Add userid when we shall show all mails from a single member
1705 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1707 // Close open anchor tag
1711 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1712 // Is currently selected, so only highlight it
1713 $NAV .= "-</STRONG>";
1719 // Add seperator if we have not yet reached total pages
1720 if ($page < $PAGES) $NAV .= " | ";
1723 // Define constants only once
1724 if (!defined('__NAV_OUTPUT')) {
1725 define('__NAV_OUTPUT' , $NAV);
1726 define('__NAV_COLSPAN', $colspan);
1727 define('__NAV_TOP' , $TOP);
1728 define('__NAV_SEP' , $SEP);
1731 // Load navigation template
1732 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1735 // Return generated HTML-Code
1743 // Extract host from script name
1744 function EXTRACT_HOST (&$script) {
1745 // Use default SERVER_URL by default... ;) So?
1748 // Is this URL valid?
1749 if (substr($script, 0, 7) == "http://") {
1750 // Use the hostname from script URL as new hostname
1751 $url = substr($script, 7);
1752 $extract = explode("/", $url);
1754 // Done extracting the URL :)
1757 // Extract host name
1758 $host = str_replace("http://", "", $url);
1759 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1761 // Generate relative URL
1762 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1763 if (substr(strtolower($script), 0, 7) == "http://") {
1764 // But only if http:// is in front!
1765 $script = substr($script, (strlen($url) + 7));
1766 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1768 $script = substr($script, (strlen($url) + 8));
1771 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1772 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1778 // Send a GET request
1779 function GET_URL ($script) {
1780 // Compile the script name
1781 $script = COMPILE_CODE($script);
1783 // Extract host name from script
1784 $host = EXTRACT_HOST($script);
1786 // Generate GET request header
1787 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1788 $request .= "Host: " . $host . "\r\n";
1789 $request .= "Referer: " . URL . "/admin.php\r\n";
1790 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1791 $request .= "Content-Type: text/plain\r\n";
1792 $request .= "Cache-Control: no-cache\r\n";
1793 $request .= "Connection: Close\r\n\r\n";
1795 // Send the raw request
1796 $response = SEND_RAW_REQUEST($host, $request);
1798 // Return the result to the caller function
1802 // Send a POST request
1803 function POST_URL ($script, $postData) {
1804 // Is postData an array?
1805 if (!is_array($postData)) {
1807 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1808 return array("", "", "");
1811 // Compile the script name
1812 $script = COMPILE_CODE($script);
1814 // Extract host name from script
1815 $host = EXTRACT_HOST($script);
1817 // Construct request
1818 $data = http_build_query($postData, '','&');
1820 // Generate POST request header
1821 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1822 $request .= "Host: " . $host . "\r\n";
1823 $request .= "Referer: " . URL . "/admin.php\r\n";
1824 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1825 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1826 $request .= "Content-length: " . strlen($data) . "\r\n";
1827 $request .= "Cache-Control: no-cache\r\n";
1828 $request .= "Connection: Close\r\n\r\n";
1831 // Send the raw request
1832 $response = SEND_RAW_REQUEST($host, $request);
1834 // Return the result to the caller function
1838 // Sends a raw request to another host
1839 function SEND_RAW_REQUEST ($host, $request) {
1841 $response = array("", "", "");
1843 // Default is not to use proxy
1846 // Are proxy settins set?
1847 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1853 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1855 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1857 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1861 if (!is_resource($fp)) {
1868 // Generate CONNECT request header
1869 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1870 $proxyTunnel .= "Host: ".$host."\r\n";
1872 // Use login data to proxy? (username at least!)
1873 if (getConfig('proxy_username') != "") {
1875 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1876 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1879 // Add last new-line
1880 $proxyTunnel .= "\r\n";
1881 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1884 fputs($fp, $proxyTunnel);
1888 // No response received
1892 // Read the first line
1893 $resp = trim(fgets($fp, 10240));
1894 $respArray = explode(" ", $resp);
1895 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1896 // Invalid response!
1902 fputs($fp, $request);
1906 $response[] = trim(fgets($fp, 1024));
1912 // Skip first empty lines
1914 foreach ($resp as $idx => $line) {
1916 $line = trim($line);
1918 // Is this line empty?
1921 array_shift($response);
1923 // Abort on first non-empty line
1928 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1930 // Proxy agent found?
1931 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1932 // Proxy header detected, so remove two lines
1933 array_shift($response);
1934 array_shift($response);
1937 // Was the request successfull?
1938 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1939 // Not found / access forbidden
1940 $response = array("", "", "");
1946 // Taken from www.php.net eregi() user comments
1947 function VALIDATE_EMAIL($email) {
1949 $email = COMPILE_CODE($email);
1951 // Check first part of email address
1952 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1955 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1958 $regex = "^".$first."@".$domain."$";
1960 // Return check result
1961 return eregi($regex, $email);
1963 // Function taken from user comments on www.php.net / function eregi()
1964 function VALIDATE_URL ($URL, $compile=true) {
1965 // Trim URL a little
1966 $URL = trim(urldecode($URL));
1967 //* DEBUG: */ echo $URL."<br />";
1969 // Compile some chars out...
1970 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1971 //* DEBUG: */ echo $URL."<br />";
1973 // Check for the extension filter
1974 if (EXT_IS_ACTIVE("filter")) {
1975 // Use the extension's filter set
1976 return FILTER_VALIDATE_URL($URL, false);
1979 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1980 // https:// in front of the URLs
1981 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1984 function MEMBER_ACTION_LINKS($uid, $status="") {
1985 // Define all main targets
1986 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1988 // Begin of navigation links
1989 $eval = "\$OUT = \"[ ";
1991 foreach ($TARGETS as $tar) {
1992 $eval .= "<SPAN class=\\\"admin_user_link\\\"><A href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
1993 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1994 if (($tar == "lock_user") && ($status == "LOCKED")) {
1995 // Locked accounts shall be unlocked
1996 $eval .= "UNLOCK_USER";
1998 // All other status is fine
1999 $eval .= strtoupper($tar);
2001 $eval .= "_TITLE.\"\\\">\".ADMIN_";
2002 if (($tar == "lock_user") && ($status == "LOCKED")) {
2003 // Locked accounts shall be unlocked
2004 $eval .= "UNLOCK_USER";
2006 // All other status is fine
2007 $eval .= strtoupper($tar);
2009 $eval .= ".\"</A></SPAN> | ";
2012 // Finish navigation link
2013 $eval = substr($eval, 0, -7)."]\";";
2019 // Function for backward-compatiblity
2020 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
2021 // Load it from the register extension
2022 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
2024 // Generate an email link
2025 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2026 // Default email link (INSECURE! Spammer can read this by harvester programs)
2027 $EMAIL = "mailto:".$email;
2029 // Check for several extensions
2030 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2031 // Create email link for contacting admin in guest area
2032 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2033 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2034 // Create email link for contacting a member within admin area (or later in other areas, too?)
2035 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2036 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2037 // Create email link to contact sponsor within admin area (or like the link above?)
2038 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2041 // Shall I close the link when there is no admin?
2042 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2044 // Return email link
2047 // Generate a hash for extra-security for all passwords
2048 function generateHash ($plainText, $salt = "") {
2051 // Is the required extension "sql_patches" there and a salt is not given?
2052 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2053 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2054 return md5($plainText);
2057 // Do we miss an arry element here?
2058 if (getConfig('file_hash') == null) {
2060 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2061 debug_print_backtrace();
2065 // When the salt is empty build a new one, else use the first x configured characters as the salt
2067 // Build server string
2068 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2071 $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');
2074 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2076 // Calculate number for generating the code
2077 $a = time() + _ADD - 1;
2079 // Generate SHA1 sum from modula of number and the prime number
2080 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2081 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2082 $sha1 = scrambleString($sha1);
2083 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2084 //* DEBUG: */ $sha1b = descrambleString($sha1);
2085 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2087 // Generate the password salt string
2088 $salt = substr($sha1, 0, getConfig('salt_length'));
2089 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2092 $salt = substr($salt, 0, getConfig('salt_length'));
2093 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2097 return $salt.sha1($salt.$plainText);
2100 function scrambleString($str) {
2104 // Final check, in case of failture it will return unscrambled string
2105 if (strlen($str) > 40) {
2106 // The string is to long
2108 } elseif (strlen($str) == 40) {
2110 $scrambleNums = explode(":", getConfig('pass_scramble'));
2112 // Generate new numbers
2113 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2116 // Scramble string here
2117 //* DEBUG: */ echo "***Original=".$str."***<br />";
2118 for ($idx = 0; $idx < strlen($str); $idx++) {
2119 // Get char on scrambled position
2120 $char = substr($str, $scrambleNums[$idx], 1);
2122 // Add it to final output string
2123 $scrambled .= $char;
2126 // Return scrambled string
2127 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2131 function descrambleString($str) {
2132 // Scramble only 40 chars long strings
2133 if (strlen($str) != 40) return $str;
2135 // Load numbers from config
2136 $scrambleNums = explode(":", getConfig('pass_scramble'));
2139 if (count($scrambleNums) != 40) return $str;
2141 // Begin descrambling
2142 $orig = str_repeat(" ", 40);
2143 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2144 for ($idx = 0; $idx < 40; $idx++) {
2145 $char = substr($str, $idx, 1);
2146 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2149 // Return scrambled string
2150 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2154 function genScrambleString($len) {
2155 // Prepare randomizer and array for the numbers
2156 mt_srand((double) microtime() * 1000000);
2157 $scrambleNumbers = array();
2159 // First we need to setup randomized numbers from 0 to 31
2160 for ($idx = 0; $idx < $len; $idx++) {
2162 $rand = mt_rand(0, ($len -1));
2164 // Check for it by creating more numbers
2165 while (array_key_exists($rand, $scrambleNumbers)) {
2166 $rand = mt_rand(0, ($len -1));
2170 $scrambleNumbers[$rand] = $rand;
2173 // So let's create the string for storing it in database
2174 $scrambleString = implode(":", $scrambleNumbers);
2175 return $scrambleString;
2177 // Append data like session ID or referal ID to the given URL which would
2178 // normally be stored in cookies
2179 function ADD_URL_DATA ($URL) {
2183 // Determine URL binder
2185 if (strpos($URL, "?") !== false) $BIND = "&";
2187 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2188 // Cookies are not accepted
2189 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2190 // Cookie found in URL
2191 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2192 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2193 // Not found! So let's set default here
2194 $ADD .= $BIND."refid=".getConfig('def_refid');
2197 // Is there already added data? Then change the binder
2198 if (!empty($ADD)) $BIND = "&";
2201 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2202 // Add session from URL
2203 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2205 // Add current session
2206 $ADD .= $BIND."PHPSESSID=".session_id();
2210 // Add all together and return it
2213 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2214 function generatePassString($passHash) {
2215 // Return vanilla password hash
2218 // Is a secret key and master salt already initialized?
2219 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2220 // Only calculate when the secret key is generated
2221 $newHash = ""; $start = 9;
2222 for ($idx = 0; $idx < 10; $idx++) {
2223 $part1 = hexdec(substr($passHash, $start, 4));
2224 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2225 $mod = dechex($idx);
2226 if ($part1 > $part2) {
2227 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2228 } elseif ($part2 > $part1) {
2229 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2231 $mod = substr(round($mod), 0, 4);
2232 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2233 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2238 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2239 $ret = generateHash($newHash, getConfig('master_salt'));
2240 //* DEBUG: */ print($ret."<br />\n");
2243 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2244 $ret = md5($passHash);
2245 //* DEBUG: */ echo "++".$ret."++<br />\n";
2252 // Fix "deleted" cookies
2253 function FIX_DELETED_COOKIES ($cookies) {
2254 // Is this an array with entries?
2255 if ((is_array($cookies)) && (count($cookies) > 0)) {
2256 // Then check all cookies if they are marked as deleted!
2257 foreach ($cookies as $cookieName) {
2258 // Is the cookie set to "deleted"?
2259 if (get_session($cookieName) == "deleted") {
2260 set_session($cookieName, "");
2266 // Output error messages in a fasioned way and die...
2267 function mxchange_die ($msg) {
2270 // Load the message template
2271 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2274 include(PATH."inc/footer.php");
2280 // Display parsing time and number of SQL queries in footer
2281 function DISPLAY_PARSING_TIME_FOOTER() {
2282 // Is the timer started?
2283 if (!isset($GLOBALS['startTime'])) {
2289 $endTime = microtime(true);
2291 // "Explode" both times
2292 $start = explode(" ", $GLOBALS['startTime']);
2293 $end = explode(" ", $endTime);
2294 $runTime = $end[0] - $start[0];
2295 if ($runTime < 0) $runTime = 0;
2296 $runTime = TRANSLATE_COMMA($runTime);
2300 'runtime' => $runTime,
2301 'numSQLs' => (getConfig('sql_count') + 1),
2302 'numTemplates' => (getConfig('num_templates') + 1)
2305 // Load the template
2306 LOAD_TEMPLATE("show_timings", false, $content);
2309 // Unset/set session variables
2310 function set_session ($var, $value) {
2313 // Abort in CSS mode here
2314 if ($CSS == 1) return true;
2316 // Trim value and session variable
2317 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2319 // Is the session variable set?
2320 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2321 // Remove the session
2322 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2323 unset($_SESSION[$var]);
2324 return session_unregister($var);
2325 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2327 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2328 $_SESSION[$var] = $value;
2329 return session_register($var);
2330 } elseif (!empty($value)) {
2332 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2333 $_SESSION[$var] = $value;
2337 // Ignored (but valid)
2338 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2342 // Check wether a boolean constant is set
2343 // Taken from user comments in PHP documentation for function constant()
2344 function isBooleanConstantAndTrue($constName) { // : Boolean
2347 // Failed by default
2351 if (isset($cacheArray['const'][$constName])) {
2353 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2354 $res = $cacheArray['const'][$constName];
2357 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2358 if (defined($constName)) $res = (constant($constName) === true);
2361 $cacheArray['const'][$constName] = $res;
2363 //* DEBUG: */ var_dump($res);
2369 // Check wether a session variable is set
2370 function isSessionVariableSet ($var) {
2371 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2372 return (isset($_SESSION[$var]));
2374 // Returns wether the value of the session variable or NULL if not set
2375 function get_session ($var) {
2378 // Default is not found! ;-)
2381 // Is the variable there or cached values?
2382 if (isset($cacheArray['session'][$var])) {
2383 // Get cached value (skips a lot SQL_ESCAPE() calles!
2384 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2385 $value = $cacheArray['session'][$var];
2386 } elseif (isSessionVariableSet($var)) {
2387 // Then get it secured!
2388 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2389 $value = SQL_ESCAPE($_SESSION[$var]);
2392 $cacheArray['session'][$var] = $value;
2399 // Send notification to admin
2400 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2401 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2403 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2405 // Send outdated way
2406 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2407 SEND_ADMIN_EMAILS($subject, $msg);
2411 // Destroy user session
2412 function destroy_user_session () {
2414 $GLOBALS['userid'] = 0;
2416 // Remove all user data from session
2417 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2420 // Merges an array together but only if both are arrays
2421 function merge_array ($array1, $array2) {
2422 // Are both an array?
2423 if ((is_array($array1)) && (is_array($array2))) {
2424 // Merge all together
2425 return array_merge($array1, $array2);
2426 } elseif (is_array($array1)) {
2427 // Return left array
2431 // Something wired happened here...
2432 print(__FUNCTION__.":<pre>");
2433 debug_print_backtrace();
2437 // Debug message logger
2438 function DEBUG_LOG ($file, $line, $message, $force=true) {
2439 // Is debug mode enabled?
2440 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2441 // Log this message away
2442 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2443 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2448 // Reads a directory with PHP files in and gets only files back
2449 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2453 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2456 while ($baseFile = readdir($dirPointer)) {
2457 // Load file only if extension is active
2459 $file = $baseDir.$baseFile;
2461 // Is this a valid reset file?
2462 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2463 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2464 // Remove both for extension name
2465 $extName = substr($baseFile, strlen($prefix), -4);
2468 $extId = GET_EXT_ID($extName);
2470 // Is the extension valid and active?
2471 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2472 // Then add this file
2474 } elseif ($extId == 0) {
2475 // Add non-extension files as well
2482 closedir($dirPointer);
2487 // Return array with include files
2490 // Load more reset scripts
2491 function RESET_ADD_INCLUDES () {
2492 // Is the reset set or old sql_patches?
2493 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2498 // Get more daily reset scripts
2499 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2502 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2504 // Create current week mark
2505 $currWeek = date("W", time());
2508 if (getConfig('last_week') != $currWeek) {
2509 // Include weekly reset scripts
2510 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2513 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2516 // Create current month mark
2517 $currMonth = date("m", time());
2520 if (getConfig('last_month') != $currMonth) {
2521 // Include monthly reset scripts
2522 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2525 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2531 // Handle extra values
2532 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2533 // Default is the value itself
2536 // Do we have a special filter function?
2537 if (!empty($filterFunction)) {
2538 // Does the filter function exist?
2539 if (function_exists($filterFunction)) {
2540 // Do we have extra parameters here?
2541 if (!empty($extraValue)) {
2542 // Put both parameters in one new array by default
2543 $args = array($value, $extraValue);
2545 // If we have an array simply use it and pre-extend it with our value
2546 if (is_array($extraValue)) {
2547 // Make the new args array
2548 $args = merge_array(array($value), $extraValue);
2551 // Call the multi-parameter call-back
2552 $ret = call_user_func_array($filterFunction, $args);
2554 // One parameter call
2555 $ret = call_user_func($filterFunction, $value);
2563 // Check if given FQFN is a readable file
2564 function FILE_READABLE($fqfn) {
2566 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2568 // Converts timestamp selections into a timestamp
2569 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2570 // Init test variable
2573 // Get last three chars
2574 $test = substr($id, -3);
2576 // Improved way of checking! :-)
2577 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2578 // Found a multi-selection for timings?
2579 $test = substr($id, 0, -3);
2580 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)) {
2581 // Generate timestamp
2582 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2583 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2585 // Remove data from array
2586 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2587 unset($POST[$test."_".$rem]);
2591 unset($id); $skip = true; $test2 = $test;
2594 // Process this entry
2595 $skip = false; $test2 = "";
2598 // Reverts the german decimal comma into Computer decimal dot
2599 function REVERT_COMMA ($str) {
2600 // Default float is not a float... ;-)
2603 // Which language is selected?
2604 switch (GET_LANGUAGE()) {
2605 case "de": // German language
2606 // Remove german thousand dots first
2607 $str = str_replace(".", "", $str);
2609 // Replace german commata with decimal dot and cast it
2610 $float = (float)str_replace(",", ".", $str);
2613 default: // US and so on
2614 // Remove thousand dots first and cast
2615 $float = (float)str_replace(",", "", $str);
2623 // Handle menu-depending failed logins and return the rendered content
2624 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2625 // Default output is empty ;-)
2628 // Is the session data set?
2629 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2630 // Ignore zero values
2631 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2632 // Non-guest has login failtures found, get both data and prepare it for template
2633 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2635 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2636 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2640 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2643 // Reset session data
2644 set_session('mxchange_'.$accessLevel.'_failtures', "");
2645 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2648 // Return rendered content
2653 function REBUILD_CACHE ($cache, $inc="") {
2654 global $cacheInstance, $CSS;
2656 // Shall I remove the cache file?
2657 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2659 if ($cacheInstance->loadCacheFile($cache)) {
2661 $cacheInstance->destroyCacheFile();
2664 // Include file given?
2667 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2669 // Is the include there?
2670 if (FILE_READABLE($fqfn)) {
2671 // And rebuild it from scratch
2672 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2675 // Include not found!
2676 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2682 // Purge admin menu cache
2683 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2684 global $cacheInstance;
2686 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2687 if (!EXT_IS_ACTIVE("cache")) {
2688 // Cache extension not active
2690 } elseif (!is_object($cacheInstance)) {
2691 // No cache instance!
2692 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2694 } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2695 // Caching disabled (currently experiemental!)
2699 // Experiemental feature!
2700 trigger_error("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2703 // Translates the "pool type" into human-readable
2704 function TRANSLATE_POOL_TYPE ($type) {
2705 // Default type is unknown
2706 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2708 // Generate constant
2709 $constName = sprintf("POOL_TYPE_%s", $type);
2712 if (defined($constName)) {
2714 $translated = constant($constName);
2717 // Return "translation"
2721 // "Getter" for remote IP number
2722 function GET_REMOTE_ADDR () {
2723 // Get remote ip from environment
2724 $remoteAddr = getenv('REMOTE_ADDR');
2726 // Is removeip installed?
2727 if (EXT_IS_ACTIVE("removeip")) {
2728 // Then anonymize it
2729 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2735 // "Getter" for remote hostname
2736 function GET_REMOTE_HOST () {
2737 // Get remote ip from environment
2738 $remoteHost = getenv('REMOTE_HOST');
2740 // Is removeip installed?
2741 if (EXT_IS_ACTIVE("removeip")) {
2742 // Then anonymize it
2743 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2749 // "Getter" for user agent
2750 function GET_USER_AGENT () {
2751 // Get remote ip from environment
2752 $userAgent = getenv('HTTP_USER_AGENT');
2754 // Is removeip installed?
2755 if (EXT_IS_ACTIVE("removeip")) {
2756 // Then anonymize it
2757 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2763 // "Getter" for referer
2764 function GET_REFERER () {
2765 // Get remote ip from environment
2766 $referer = getenv('HTTP_REFERER');
2768 // Is removeip installed?
2769 if (EXT_IS_ACTIVE("removeip")) {
2770 // Then anonymize it
2771 $referer = GET_ANONYMOUS_REFERER($referer);
2778 // Adds a bonus mail to the queue
2779 // This is a high-level function!
2780 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2781 // Use mode from data if not set and availble ;-)
2782 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2784 // Generate receiver list
2785 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2788 if (!empty($RECEIVER)) {
2789 // Add bonus mail to queue
2790 ADD_BONUS_MAIL_TO_QUEUE(
2802 // Mail inserted into bonus pool
2803 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2804 } elseif ($output) {
2805 // More entered than can be reached!
2806 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2809 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2812 // Determines referal id and sets it
2813 function DETERMINE_REFID () {
2814 global $CLICK, $_SERVER;
2816 // Check if refid is set
2817 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2818 // The variable user comes from the click-counter script click.php and we only accept this here
2819 $GLOBALS['refid'] = bigintval($_GET['user']);
2820 } elseif (!empty($_POST['refid'])) {
2821 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2822 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2823 } elseif (!empty($_GET['refid'])) {
2824 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2825 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2826 } elseif (!empty($_GET['ref'])) {
2827 // Set refid=ref (the referal link uses such variable)
2828 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2829 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2830 // Set session refid als global
2831 $GLOBALS['refid'] = bigintval(get_session('refid'));
2832 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2833 // Set default refid as refid in URL
2834 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2835 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2836 // Select a random user which has confirmed enougth mails
2837 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2839 // No default ID when sql_patches is not installed or none set
2840 $GLOBALS['refid'] = 0;
2843 // Set cookie when default refid > 0
2844 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2846 set_session('refid', $GLOBALS['refid']);
2849 // Return determined refid
2850 return $GLOBALS['refid'];
2853 // Destroys the admin session
2854 function DESTROY_ADMIN_SESSION ($destroy = true) {
2855 // Kill maybe existing session variables including array elements
2856 set_session('admin_login', "");
2857 set_session('admin_md5' , "");
2858 set_session('admin_last' , "");
2859 set_session('admin_to' , "");
2861 // Destroy session and return status
2863 return @session_destroy();
2866 // All fine if we shall not really destroy the session
2870 // Checks if a given apache module is loaded
2871 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2872 // Check it and return result
2873 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2876 // Getter for $_CONFIG entries
2877 function getConfig ($entry) {
2883 // Is the entry there?
2884 if (isset($_CONFIG[$entry])) {
2886 $value = $_CONFIG[$entry];
2893 // @TODO Rewrite all language constants to the function getLanguage().
2894 // "Getter" for language strings
2895 function getMessage ($messageId) {
2896 // Default is not found!
2897 $return = "!".$messageId."!";
2899 // Is the language string found?
2900 if (isset($GLOBALS['msg'][$messageId])) {
2901 // Language array element found
2902 $return = $GLOBALS['msg'][$messageId];
2903 } elseif (defined($messageId)) {
2904 // @DEPRECATED Deprecated constant found
2905 $return = constant($messageId);
2907 // Missing language constant
2908 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2911 // Return the string
2915 // Get current theme name
2916 function GET_CURR_THEME() {
2917 global $INC_POOL, $CSS, $cacheArray;
2919 // The default theme is 'default'... ;-)
2922 // Load default theme if not empty from configuration
2923 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2925 if (!isSessionVariableSet('mxchange_theme')) {
2926 // Set default theme
2927 set_session('mxchange_theme', $ret);
2928 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2929 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2930 // Get theme from cookie
2931 $ret = get_session('mxchange_theme');
2934 if (THEME_GET_ID($ret) == 0) {
2935 // Fix it to default
2938 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2939 // Prepare FQFN for checking
2940 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_GET['theme']));
2942 // Installation mode active
2943 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2944 // Set cookie from URL data
2945 set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
2946 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_POST['theme'])))) {
2947 // Set cookie from posted data
2948 set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
2952 $ret = get_session('mxchange_theme');
2954 // Invalid design, reset cookie
2955 set_session('mxchange_theme', $ret);
2958 // Add (maybe) found theme.php file to inclusion list
2959 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($ret));
2961 // Try to load the requested include file
2962 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2964 // Return theme value
2968 // Get id from theme
2969 function THEME_GET_ID ($name) {
2972 // Is the extension "theme" installed?
2973 if (!EXT_IS_ACTIVE("theme")) {
2981 // Is the cache entry there?
2982 if (isset($cacheArray['themes']['id'][$name])) {
2983 // Get the version from cache
2984 $id = $cacheArray['themes']['id'][$name];
2987 incrementConfigEntry('cache_hits');
2988 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2989 // Check if current theme is already imported or not
2990 $result = SQL_QUERY_ESC("SELECT id FROM `"._MYSQL_PREFIX."_themes` WHERE theme_path='%s' LIMIT 1",
2991 array($name), __FILE__, __LINE__);
2994 if (SQL_NUMROWS($result) == 1) {
2996 list($id) = SQL_FETCHROW($result);
3000 SQL_FREERESULT($result);
3007 // Increment or init with given value or 1 as default the given config entry
3008 function incrementConfigEntry ($configEntry, $value=1) {
3011 // Increment it if set or init it with 1
3012 if (getConfig($configEntry) > 0) {
3013 $_CONFIG[$configEntry] += $value;
3015 $_CONFIG[$configEntry] = $value;
3019 // Read a given file
3020 function READ_FILE ($FQFN, $sqlPrepare = false) {
3022 if (function_exists('file_get_contents')) {
3024 $content = file_get_contents($FQFN);
3026 // Fall-back to implode-file chain
3027 $content = implode("", file($FQFN));
3030 // Prepare SQL queries?
3031 if ($sqlPrepare === true) {
3032 // Remove some unwanted chars
3033 $content = str_replace("\r", "", $content);
3034 $content = str_replace("\n\n", "\n", $content);
3037 // Return the content
3041 // Generates an error code from given account status
3042 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3043 // Default error code if unknown account status
3044 $ERROR = CODE_UNKNOWN_STATUS;
3046 // Generate constant name
3047 $constantName = sprintf("CODE_ID_%s", $status);
3049 // Is the constant there?
3050 if (defined($constantName)) {
3052 $ERROR = constant($constantName);
3055 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3058 // Return error code
3062 //////////////////////////////////////////////////
3063 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3064 //////////////////////////////////////////////////
3066 if (!function_exists('html_entity_decode')) {
3067 // Taken from documentation on www.php.net
3068 function html_entity_decode ($string) {
3069 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3070 $trans_tbl = array_flip($trans_tbl);
3071 return strtr($string, $trans_tbl);