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", constant('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 // Output HTML code directly or "render" it. You addionally switch the new-line character off
63 function OUTPUT_HTML ($HTML, $newLine = true) {
64 // Some global variables
65 global $OUTPUT, $footer, $CSS;
67 // Do we have HTML-Code here?
69 // Yes, so we handle it as you have configured
70 switch (constant('OUTPUT_MODE'))
73 // That's why you don't need any \n at the end of your HTML code... :-)
74 if (constant('_OB_CACHING') == "on") {
75 // Output into PHP's internal buffer
78 // That's why you don't need any \n at the end of your HTML code... :-)
79 if ($newLine) echo "\n";
81 // Render mode for old or lame servers...
84 // That's why you don't need any \n at the end of your HTML code... :-)
85 if ($newLine) $OUTPUT .= "\n";
90 // If we are switching from render to direct output rendered code
91 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
93 // The same as above... ^
95 if ($newLine) echo "\n";
99 // Huh, something goes wrong or maybe you have edited config.php ???
100 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
101 mxchange_die("<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
104 } elseif ((constant('_OB_CACHING') == "on") && ($footer == 1)) {
105 // Headers already sent?
106 if (headers_sent()) {
108 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
110 // Trigger an user error
111 debug_report_bug("Headers are already sent!");
114 // Output cached HTML code
115 $OUTPUT = ob_get_contents();
117 // Clear output buffer for later output
121 header("HTTP/1.1 200");
124 $now = gmdate('D, d M Y H:i:s') . ' GMT';
126 // General headers for no caching
127 header("Expired: " . $now); // RFC2616 - Section 14.21
128 header("Last-Modified: " . $now);
129 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
130 header("Pragma: no-cache"); // HTTP/1.0
131 header("Connection: Close");
133 // Extension "rewrite" installed?
134 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
135 $OUTPUT = REWRITE_LINKS($OUTPUT);
138 // Compile and run finished rendered HTML code
139 while (strpos($OUTPUT, '{!') > 0) {
140 // Prepare the content and eval() it...
142 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
145 // Was that eval okay?
146 if (empty($newContent)) {
147 // Something went wrong!
148 mxchange_die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
150 $OUTPUT = $newContent;
153 // Output code here, DO NOT REMOVE! ;-)
155 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
156 // Rewrite links when rewrite extension is active
157 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
158 $OUTPUT = REWRITE_LINKS($OUTPUT);
161 // Compile and run finished rendered HTML code
162 while (strpos($OUTPUT, '{!') > 0) {
163 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
167 // Output code here, DO NOT REMOVE! ;-)
172 // Output the raw HTML code
173 function OUTPUT_RAW ($HTML) {
174 // Output stripped HTML code to avoid broken JavaScript code, etc.
175 echo stripslashes(stripslashes($HTML));
177 // Flush the output if only constant('_OB_CACHING') is not "on"
178 if (constant('_OB_CACHING') != "on") {
184 // Add a fatal error message to the queue array
185 function addFatalMessage ($message, $extra="") {
188 if (is_array($extra)) {
189 // Multiple extras for a message with masks
190 $message = call_user_func_array('sprintf', $extra);
191 } elseif (!empty($extra)) {
192 // $message is text with a mask plus extras to insert into the text
193 $message = sprintf($message, $extra);
196 // Add message to $FATAL
199 // Log fatal messages away
200 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
203 // Getter for total fatal message count
204 function getTotalFatalErrors () {
210 // Do we have at least the first entry?
211 if (!empty($FATAL[0])) {
213 $count = count($FATAL);
220 // Load a template file and return it's content (only it's name; do not use ' or ")
221 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
222 // Add more variables which you want to use in your template files
223 global $DATA, $_CONFIG, $username;
225 // Make all template names lowercase
226 $template = strtolower($template);
228 // Count the template load
229 incrementConfigEntry('num_templates');
231 // Prepare IP number and User Agent
232 $REMOTE_ADDR = GET_REMOTE_ADDR();
233 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
234 $HTTP_USER_AGENT = GET_USER_AGENT();
238 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
240 // @DEPRECATED Try to rewrite the if() condition
241 if ($template == "member_support_form") {
242 // Support request of a member
243 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
244 array($GLOBALS['userid']), __FILE__, __LINE__);
246 // Is content an array?
247 if (is_array($content)) {
249 $content = merge_array($content, SQL_FETCHARRAY($result));
252 $content['gender'] = TRANSLATE_GENDER($content['gender']);
254 // DEPRECATED: Load data in direct variables
255 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
258 $gender = TRANSLATE_GENDER($gender);
259 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
263 SQL_FREERESULT($result);
266 // Generate date/time string
267 $date_time = MAKE_DATETIME(time(), "1");
270 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
273 // Check for admin/guest/member templates
274 if (strpos($template, "admin_") > -1) {
275 // Admin template found
277 } elseif (strpos($template, "guest_") > -1) {
278 // Guest template found
280 } elseif (strpos($template, "member_") > -1) {
281 // Member template found
283 } elseif (strpos($template, "install_") > -1) {
284 // Installation template found
286 } elseif (strpos($template, "ext_") > -1) {
287 // Extension template found
289 } elseif (strpos($template, "la_") > -1) {
290 // "Logical-area" template found
293 // Test for extension
294 $test = substr($template, 0, strpos($template, "_"));
295 if (EXT_IS_ACTIVE($test)) {
296 // Set extra path to extension's name
301 ////////////////////////
302 // Generate file name //
303 ////////////////////////
304 $file = $BASE.$MODE.$template.".tpl";
306 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
307 // Select what depended header/footer template file for admin/guest/member area
308 $file2 = sprintf("%s%s%s_%s.tpl",
312 SQL_ESCAPE($GLOBALS['what'])
316 if (FILE_READABLE($file2)) $file = $file2;
318 // Remove variable from memory
322 // Does the special template exists?
323 if (!FILE_READABLE($file)) {
324 // Reset to default template
325 $file = $BASE.$template.".tpl";
328 // Now does the final template exists?
329 if (FILE_READABLE($file)) {
330 // The local file does exists so we load it. :)
331 $tmpl_file = READ_FILE($file);
333 // Replace ' to our own chars to preventing them being quoted
334 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
336 // Do we have to compile the code?
338 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
340 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
343 // Simply return loaded code
347 // Add surrounding HTML comments to help finding bugs faster
348 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
349 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
350 // Only admins shall see this warning or when installation mode is active
351 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
352 (".basename($file).")<br />
355 <pre>".print_r($content, true)."</pre>
357 <pre>".print_r($DATA, true)."</pre>
361 // Remove content and data
365 // Do we have some content to output or return?
367 // Not empty so let's put it out! ;)
369 // Return the HTML code
375 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
376 // Warning, empty output!
377 return "E:".$template."<br />\n";
381 // Send mail out to an email address
382 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
383 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
385 // Compile subject line (for POINTS constant etc.)
386 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
390 if ((!eregi("@", $TO)) && ($TO > 0)) {
391 // Value detected, is the message extension installed?
392 if (EXT_IS_ACTIVE("msg")) {
393 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
396 // Load email address
397 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
398 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
400 // Does the user exist?
401 if (SQL_NUMROWS($result_email)) {
402 // Load email address
403 list($TO) = SQL_FETCHROW($result_email);
406 $TO = constant('WEBMASTER');
410 SQL_FREERESULT($result_email);
412 } elseif ("$TO" == "0") {
414 $TO = constant('WEBMASTER');
416 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
418 // Check for PHPMailer or debug-mode
419 if (!CHECK_PHPMAILER_USAGE()) {
420 // Not in PHPMailer-Mode
422 // Load email header template
423 $FROM = LOAD_EMAIL_TEMPLATE("header");
426 $FROM .= LOAD_EMAIL_TEMPLATE("header");
428 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
430 // Load email header template
431 $FROM = LOAD_EMAIL_TEMPLATE("header");
434 $FROM .= LOAD_EMAIL_TEMPLATE("header");
439 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
443 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
446 // Fix HTML parameter (default is no!)
447 if (empty($HTML)) $HTML = "N";
448 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
449 // In debug mode we want to display the mail instead of sending it away so we can debug this part
451 ".htmlentities(trim($FROM))."
453 Subject : ".$SUBJECT."
456 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
457 // Send mail as HTML away
458 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
459 } elseif (!empty($TO)) {
461 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
462 } elseif ($HTML == "N") {
464 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
468 // Check if legacy or PHPMailer command
470 function CHECK_PHPMAILER_USAGE() {
471 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
475 * Send out a raw email with PHPMailer class or legacy mail() command
477 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
478 // Shall we use PHPMailer class or legacy mode?
479 if (CHECK_PHPMAILER_USAGE()) {
480 // Use PHPMailer class with SMTP enabled
481 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
482 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
485 $mail = new PHPMailer();
486 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
489 $mail->SMTPAuth = true;
490 $mail->Host = constant('SMTP_HOSTNAME');
492 $mail->Username = constant('SMTP_USER');
493 $mail->Password = constant('SMTP_PASSWORD');
495 $mail->From = constant('WEBMASTER');
499 $mail->FromName = constant('MAIN_TITLE');
500 $mail->Subject = $subject;
501 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
503 $mail->AltBody = "Your mail program required HTML support to read this mail!";
504 $mail->WordWrap = 70;
507 $mail->Body = html_entity_decode($msg);
509 $mail->AddAddress($to, "");
510 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
511 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
512 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
515 // Use legacy mail() command
516 @mail($to, $subject, html_entity_decode($msg), $from);
521 // Generate a password in a specified length or use default password length
522 function GEN_PASS ($LEN = 0) {
523 // Auto-fix invalid length of zero
524 if ($LEN == 0) $LEN = getConfig('pass_len');
526 // Initialize array with all allowed chars
527 $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,-,+,_,/");
529 // Start creating password
531 for ($i = 0; $i < $LEN; $i++) {
532 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
535 // When the size is below 40 we can also add additional security by scrambling it
536 if (strlen($PASS) <= 40) {
537 // Also scramble the password
538 $PASS = scrambleString($PASS);
541 // Return the password
545 function MAKE_DATETIME ($time, $mode="0")
549 return NEVER_HAPPENED;
551 // Filter out numbers
552 $time = bigintval($time);
555 switch (GET_LANGUAGE())
557 case "de": // German date / time format
559 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
560 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
561 case "2": $ret = date("d.m.Y|H:i", $time); break;
562 case "3": $ret = date("d.m.Y", $time); break;
564 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
569 default: // Default is the US date / time format!
571 case "0": $ret = date("r", $time); break;
572 case "1": $ret = date("Y-m-d - g:i A", $time); break;
573 case "2": $ret = date("y-m-d|H:i", $time); break;
574 case "3": $ret = date("y-m-d", $time); break;
576 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
583 // Translates the american decimal dot into a german comma
584 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
585 // Default is 3 you can change this in admin area "Misc -> Misc Options"
586 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
588 // Use from config is default
589 $maxComma = getConfig('max_comma');
591 // Use from parameter?
592 if ($max > 0) $maxComma = $max;
595 if (($cut) && ($max == 0)) {
596 // Test for commata if in cut-mode
597 $com = explode(".", $dotted);
598 if (count($com) < 2) {
599 // Don't display commatas even if there are none... ;-)
605 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
608 switch (GET_LANGUAGE()) {
610 $dotted = number_format($dotted, $maxComma, ",", ".");
614 $dotted = number_format($dotted, $maxComma, ".", ",");
618 // Return translated value
623 function DEREFERER ($URL) {
624 // Don't de-refer our own links!
625 if (substr($URL, 0, strlen(URL)) != URL) {
626 // De-refer this link
627 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
635 function TRANSLATE_GENDER ($gender) {
638 case "M": $ret = GENDER_M; break;
639 case "F": $ret = GENDER_F; break;
640 case "C": $ret = GENDER_C; break;
641 default : $ret = $gender; break;
646 function FRAMETESTER($URL) {
647 // Prepare frametester URL
648 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
650 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
652 return $frametesterUrl;
655 function SELECTION_COUNT($array) {
657 if (is_array($array)) {
658 foreach ($array as $key => $sel) {
659 if (!empty($sel)) $ret++;
665 function IMG_CODE ($code, $type, $DATA, $uid) {
666 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
669 function TRANSLATE_STATUS($status) {
673 $ret = ACCOUNT_UNCONFIRMED;
677 $ret = ACCOUNT_CONFIRMED;
681 $ret = ACCOUNT_LOCKED;
686 $ret = ACCOUNT_DELETED;
690 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
691 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
697 function GET_LANGUAGE() {
700 // Set default return value to default language from config
701 $ret = constant('DEFAULT_LANG');
706 // Is the variable set
707 if (!empty($_GET['mx_lang'])) {
708 // Accept only first 2 chars
709 $lang = substr($_GET['mx_lang'], 0, 2);
710 } elseif (isset($cacheArray['language'])) {
712 $ret = $cacheArray['language'];
713 } elseif (!empty($lang)) {
714 // Check if main language file does exist
715 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
716 // Okay found, so let's update cookies
719 } elseif (!isSessionVariableSet('mx_lang')) {
720 // Return stored value from cookie
721 $ret = get_session('mx_lang');
723 // Fixes a warning before the session has the mx_lang constant
724 if (empty($ret)) $ret = constant('DEFAULT_LANG');
728 $cacheArray['language'] = $ret;
734 function SET_LANGUAGE ($lang) {
735 // Accept only first 2 chars!
736 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
739 set_session('mx_lang', $lang);
742 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
743 global $DATA, $REPLACER, $_CONFIG;
745 // Make sure all template names are lowercase!
746 $template = strtolower($template);
748 // Default "nickname" if extension is not installed
751 // Prepare IP number and User Agent
752 $REMOTE_ADDR = GET_REMOTE_ADDR();
753 $HTTP_USER_AGENT = GET_USER_AGENT();
756 $ADMIN = constant('MAIN_TITLE');
758 // Is the admin logged in?
761 $aid = GET_CURRENT_ADMIN_ID();
764 $ADMIN = GET_ADMIN_EMAIL($aid);
767 // Neutral email address is default
768 $email = constant('WEBMASTER');
770 // Expiration in a nice output format
771 if (getConfig('auto_purge') == 0) {
772 // Will never expire!
773 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
775 // Create nice date string
776 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
779 // Is content an array?
780 if (is_array($content)) {
781 // Add expiration to array, $EXPIRATION is now deprecated!
782 $content['expiration'] = $EXPIRATION;
786 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
787 if (($UID > 0) && (is_array($content))) {
788 // If nickname extension is installed, fetch nickname as well
789 if (EXT_IS_ACTIVE("nickname")) {
790 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
792 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
793 array(bigintval($UID)), __FILE__, __LINE__);
795 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
797 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
798 array(bigintval($UID)), __FILE__, __LINE__);
801 // Fetch and merge data
802 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
803 $content = merge_array($content, SQL_FETCHARRAY($result));
804 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
807 SQL_FREERESULT($result);
810 // Translate M to male or F to female if present
811 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
813 // Overwrite email from data if present
814 if (isset($content['email'])) $email = $content['email'];
816 // Store email for some functions in global data array
817 $DATA['email'] = $email;
820 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
822 // Check for admin/guest/member templates
823 if (strpos($template, "admin_") > -1) {
824 // Admin template found
825 $file = $BASE."admin/".$template.".tpl";
826 } elseif (strpos($template, "guest_") > -1) {
827 // Guest template found
828 $file = $BASE."guest/".$template.".tpl";
829 } elseif (strpos($template, "member_") > -1) {
830 // Member template found
831 $file = $BASE."member/".$template.".tpl";
833 // Test for extension
834 $test = substr($template, 0, strpos($template, "_"));
835 if (EXT_IS_ACTIVE($test)) {
836 // Set extra path to extension's name
837 $file = $BASE.$test."/".$template.".tpl";
839 // No special filename
840 $file = $BASE.$template.".tpl";
844 // Does the special template exists?
845 if (!FILE_READABLE($file)) {
846 // Reset to default template
847 $file = $BASE.$template.".tpl";
850 // Now does the final template exists?
852 if (FILE_READABLE($file)) {
853 // The local file does exists so we load it. :)
854 $tmpl_file = READ_FILE($file);
855 $tmpl_file = addslashes($tmpl_file);
858 $tmpl_file = "\$newContent = html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
860 } elseif (!empty($template)) {
861 // Template file not found!
862 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
863 {--TEMPLATE_CONTENT--}
864 <pre>".print_r($content, true)."</pre>
866 <pre>".print_r($DATA, true)."</pre>
869 // Debug mode not active? Then remove the HTML tags
870 if (!isBooleanConstantAndTrue('DEBUG_MODE')) $newContent = strip_tags($newContent);
872 // No template name supplied!
873 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
876 // Is there some content?
877 if (empty($newContent)) {
879 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
880 // Add last error if the required function exists
881 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
884 // Remove content and data
888 // Return compiled content
889 return COMPILE_CODE($newContent);
892 function MAKE_TIME($H, $M, $S, $stamp) {
893 // Extract day, month and year from given timestamp
894 $DAY = date("d", $stamp);
895 $MONTH = date("m", $stamp);
896 $YEAR = date('Y', $stamp);
898 // Create timestamp for wished time which depends on extracted date
899 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
902 function LOAD_URL($URL, $addUrlData=true) {
903 global $CSS, $footer;
905 // Compile out URI codes
906 $URL = COMPILE_CODE($URL);
908 // Check if http(s):// is there
909 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
910 // Make all URLs full-qualified
915 //* DEBUG: */ debug_report_bug();
916 $OUTPUT = ob_get_contents();
918 // Clear it only if there is content
919 if (!empty($OUTPUT)) {
923 // Add some data to URL if cookies are not accepted
924 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
926 // Probe for bot from search engine
927 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
928 // Search engine bot detected so let's rewrite many chars for the link
929 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
931 // Output new location link as anchor
932 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
933 } elseif (!headers_sent()) {
934 // Load URL when headers are not sent
935 //* DEBUG: */ debug_report_bug("URL={$URL}");
936 header ("Location: ".str_replace("&", "&", $URL));
938 // Output error message
939 LOAD_INC("inc/header.php");
940 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
941 LOAD_INC("inc/footer.php");
946 // Wrapper for LOAD_URL but URL comes from a configuration entry
947 function LOAD_CONFIGURED_URL ($configEntry) {
949 $URL = getConfig($configEntry);
954 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
962 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
963 global $SEC_CHARS, $URL_CHARS;
964 // Is the code a string?
965 if (!is_string($code)) {
966 // Silently return it
972 // Select smaller set of chars to replace when we e.g. want to compile URLs
973 if (!$full) $ARRAY = $URL_CHARS;
977 // BEFORE 0.2.1 : Language and data constants
978 // WITH 0.2.1+ : Only language constants
979 $code = str_replace('{--','".', str_replace('--}','."', $code));
981 // BEFORE 0.2.1 : Not used
982 // WITH 0.2.1+ : Data constants
983 $code = str_replace('{!','".', str_replace("!}", '."', $code));
986 // Compile QUOT and other non-HTML codes
987 foreach ($ARRAY['to'] as $k => $to) {
988 // Do the reversed thing as in inc/libs/security_functions.php
989 $code = str_replace($to, $ARRAY['from'][$k], $code);
992 // But shall I keep simple quotes for later use?
993 if ($simple) $code = str_replace("'", '{QUOT}', $code);
995 // Find $content[bla][blub] entries
996 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
998 // Are some matches found?
999 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1000 // Replace all matches
1001 $matchesFound = array();
1002 foreach ($matches[0] as $key => $match) {
1003 // Fuzzy look has failed by default
1004 $fuzzyFound = false;
1006 // Fuzzy look on match if already found
1007 foreach ($matchesFound as $found => $set) {
1009 $test = substr($found, 0, strlen($match));
1011 // Does this entry exist?
1012 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1013 if ($test == $match) {
1015 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1022 if ($fuzzyFound) continue;
1024 // Take all string elements
1025 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1026 // Replace it in the code
1027 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1028 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1029 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1030 $matchesFound[$key."_".$matches[4][$key]] = 1;
1031 $matchesFound[$match] = 1;
1032 } elseif (!isset($matchesFound[$match])) {
1033 // Not yet replaced!
1034 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1035 $code = str_replace($match, "\".".$match.".\"", $code);
1036 $matchesFound[$match] = 1;
1041 // Return compiled code
1045 /************************************************************************
1047 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1048 * $a_sort sortiert: *
1050 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1051 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1052 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1053 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1054 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1056 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1057 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1058 * Sie, dass es doch nicht so schwer ist! :-) *
1060 ************************************************************************/
1061 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1064 while ($primary_key < count($a_sort)) {
1065 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1066 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1069 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1070 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1071 } elseif ($key != $key2) {
1072 // Sort numbers (E.g.: 9 < 10)
1073 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1074 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1078 // We have found two different values, so let's sort whole array
1079 foreach ($dummy as $sort_key => $sort_val) {
1080 $t = $dummy[$sort_key][$key];
1081 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1082 $dummy[$sort_key][$key2] = $t;
1093 // Write back sorted array
1097 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1098 global $MONTH_DESCR;
1101 if ($type == "yn") {
1102 // This is a yes/no selection only!
1103 if ($id > 0) $prefix .= "[".$id."]";
1104 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1106 // Begin with regular selection box here
1107 if (!empty($prefix)) $prefix .= "_";
1109 if ($id > 0) $type2 .= "[".$id."]";
1110 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1115 for ($idx = 1; $idx < 32; $idx++) {
1116 $OUT .= "<option value=\"".$idx."\"";
1117 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1118 $OUT .= ">".$idx."</option>\n";
1122 case "month": // Month
1123 foreach ($MONTH_DESCR as $month => $descr) {
1124 $OUT .= "<option value=\"".$month."\"";
1125 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1126 $OUT .= ">".$descr."</option>\n";
1130 case "year": // Year
1132 $YEAR = date('Y', time());
1134 // Use configured min age or fixed?
1135 if (GET_EXT_VERSION("other") >= "0.2.1") {
1137 $startYear = $YEAR - getConfig('min_age');
1140 $startYear = $YEAR - 16;
1143 // Calculate earliest year (100 years old people can still enter Internet???)
1144 $minYear = $YEAR - 100;
1146 // Check if the default value is larger than minimum and bigger than actual year
1147 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1148 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1149 $OUT .= "<option value=\"".$idx."\"";
1150 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1151 $OUT .= ">".$idx."</option>\n";
1153 } elseif ($DEFAULT == -1) {
1154 // Current year minus 1
1155 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1157 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1160 // Get current year and subtract the configured minimum age
1161 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1162 // Calculate earliest year depending on extension version
1163 if (GET_EXT_VERSION("other") >= "0.2.1") {
1164 // Use configured minimum age
1165 $YEAR = date('Y', time()) - getConfig('min_age');
1167 // Use fixed 16 years age
1168 $YEAR = date('Y', time()) - 16;
1171 // Construct year selection list
1172 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1173 $OUT .= "<option value=\"".$idx."\"";
1174 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1175 $OUT .= ">".$idx."</option>\n";
1182 for ($idx = 0; $idx < 60; $idx+=5) {
1183 if (strlen($idx) == 1) $idx = "0".$idx;
1184 $OUT .= "<option value=\"".$idx."\"";
1185 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1186 $OUT .= ">".$idx."</option>\n";
1191 for ($idx = 0; $idx < 24; $idx++) {
1192 if (strlen($idx) == 1) $idx = "0".$idx;
1193 $OUT .= "<option value=\"".$idx."\"";
1194 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1195 $OUT .= ">".$idx."</option>\n";
1200 $OUT .= "<option value=\"Y\"";
1201 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1202 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1203 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1204 $OUT .= ">{--NO--}</option>\n";
1207 $OUT .= " </select>\n";
1211 function TRANSLATE_YESNO($yn)
1215 case "Y": $yn = YES; break;
1216 case "N": $yn = NO; break;
1217 default : $yn = "??? (".$yn.")"; break;
1222 // Deprecated : $length
1225 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1226 // Fix missing _MAX constant
1227 if (!defined('_MAX')) define('_MAX', 15235);
1229 // Build server string
1230 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1233 $keys = SITE_KEY.":".DATE_KEY;
1234 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1235 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1236 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1237 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1239 // Build string from misc data
1240 $data = $code.":".$uid.":".$DATA;
1242 // Add more additional data
1243 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1244 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1245 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1246 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1247 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1249 // Calculate number for generating the code
1250 $a = $code + constant('_ADD') - 1;
1252 if (getConfig('master_hash') != null) {
1253 // Generate hash with master salt from modula of number with the prime number and other data
1254 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1256 // Create number from hash
1257 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1259 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1260 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1262 // Create number from hash
1263 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1266 // At least 10 numbers shall be secure enought!
1267 $len = getConfig('code_length');
1268 if ($len == 0) $len = $length;
1269 if ($len == 0) $len = 10;
1271 // Cut off requested counts of number
1272 $return = substr(str_replace('.', "", $rcode), 0, $len);
1274 // Done building code
1277 // Does only allow numbers
1278 function bigintval($num, $castValue = true) {
1279 // Filter all numbers out
1280 $ret = preg_replace("/[^0123456789]/", "", $num);
1283 if ($castValue) $ret = (double)$ret;
1285 // Has the whole value changed?
1286 // @TODO Remove this if() block if all is working fine
1287 if ("".$ret."" != "".$num."") {
1295 // Insert the code in $img_code into jpeg or PNG image
1296 function GENERATE_IMAGE($img_code, $header=true) {
1297 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1298 // Stop execution of function here because of over-sized code length
1300 } elseif (!$header) {
1301 // Return in an HTML code code
1302 return "<IMG src=\"{!URL!}/img.php?code=".$img_code."\">\n";
1306 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1307 if (FILE_READABLE($img)) {
1308 // Switch image type
1309 switch (getConfig('img_type'))
1312 // Okay, load image and hide all errors
1313 $image = @imagecreatefromjpeg($img);
1317 // Okay, load image and hide all errors
1318 $image = @imagecreatefrompng($img);
1322 // Exit function here
1326 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1327 $text_color = imagecolorallocate($image, 0, 0, 0);
1329 // Insert code into image
1330 imagestring($image, 5, 14, 2, $img_code, $text_color);
1332 // Return to browser
1333 header ("Content-Type: image/".getConfig('img_type'));
1335 // Output image with matching image factory
1336 switch (getConfig('img_type')) {
1337 case "jpg": imagejpeg($image); break;
1338 case "png": imagepng($image); break;
1341 // Remove image from memory
1342 imagedestroy($image);
1344 // Create selection box or array of splitted timestamp
1345 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1346 // Calculate 2-seconds timestamp
1347 $stamp = round($timestamp);
1348 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1350 // Do we have a leap year?
1352 $TEST = date('Y', time()) / 4;
1353 $M1 = date("m", time());
1354 $M2 = date("m", (time() + $timestamp));
1356 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1357 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1359 // First of all years...
1360 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1361 //* DEBUG: */ print("Y={$Y}<br />\n");
1363 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1364 //* DEBUG: */ print("M={$M}<br />\n");
1366 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1367 //* DEBUG: */ print("W={$W}<br />\n");
1369 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1370 //* DEBUG: */ print("D={$D}<br />\n");
1372 $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));
1373 //* DEBUG: */ print("h={$h}<br />\n");
1375 $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));
1376 //* DEBUG: */ print("m={$m}<br />\n");
1377 // And at last seconds...
1378 $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));
1379 //* DEBUG: */ print("s={$s}<br />\n");
1381 // Is seconds zero and time is < 60 seconds?
1382 if (($s == 0) && ($timestamp < 60)) {
1384 $s = round($timestamp);
1388 // Now we convert them in seconds...
1390 if ($return_array) {
1391 // Just put all data in an array for later use
1403 $OUT = "<div align=\"".$align."\">\n";
1404 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1407 if (ereg('Y', $display) || (empty($display))) {
1408 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1411 if (ereg("M", $display) || (empty($display))) {
1412 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1415 if (ereg("W", $display) || (empty($display))) {
1416 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1419 if (ereg("D", $display) || (empty($display))) {
1420 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1423 if (ereg("h", $display) || (empty($display))) {
1424 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1427 if (ereg("m", $display) || (empty($display))) {
1428 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1431 if (ereg("s", $display) || (empty($display))) {
1432 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1438 if (ereg('Y', $display) || (empty($display))) {
1439 // Generate year selection
1440 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1441 for ($idx = 0; $idx <= 10; $idx++) {
1442 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1443 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1444 $OUT .= ">".$idx."</option>\n";
1446 $OUT .= " </select></td>\n";
1448 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1451 if (ereg("M", $display) || (empty($display))) {
1452 // Generate month selection
1453 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1454 for ($idx = 0; $idx <= 11; $idx++)
1456 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1457 if ($idx == $M) $OUT .= " selected=\"selected\"";
1458 $OUT .= ">".$idx."</option>\n";
1460 $OUT .= " </select></td>\n";
1462 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1465 if (ereg("W", $display) || (empty($display))) {
1466 // Generate week selection
1467 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1468 for ($idx = 0; $idx <= 4; $idx++) {
1469 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1470 if ($idx == $W) $OUT .= " selected=\"selected\"";
1471 $OUT .= ">".$idx."</option>\n";
1473 $OUT .= " </select></td>\n";
1475 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1478 if (ereg("D", $display) || (empty($display))) {
1479 // Generate day selection
1480 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1481 for ($idx = 0; $idx <= 31; $idx++) {
1482 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1483 if ($idx == $D) $OUT .= " selected=\"selected\"";
1484 $OUT .= ">".$idx."</option>\n";
1486 $OUT .= " </select></td>\n";
1488 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1491 if (ereg("h", $display) || (empty($display))) {
1492 // Generate hour selection
1493 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1494 for ($idx = 0; $idx <= 23; $idx++) {
1495 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1496 if ($idx == $h) $OUT .= " selected=\"selected\"";
1497 $OUT .= ">".$idx."</option>\n";
1499 $OUT .= " </select></td>\n";
1501 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1504 if (ereg("m", $display) || (empty($display))) {
1505 // Generate minute selection
1506 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1507 for ($idx = 0; $idx <= 59; $idx++) {
1508 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1509 if ($idx == $m) $OUT .= " selected=\"selected\"";
1510 $OUT .= ">".$idx."</option>\n";
1512 $OUT .= " </select></td>\n";
1514 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1517 if (ereg("s", $display) || (empty($display))) {
1518 // Generate second selection
1519 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1520 for ($idx = 0; $idx <= 59; $idx++) {
1521 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1522 if ($idx == $s) $OUT .= " selected=\"selected\"";
1523 $OUT .= ">".$idx."</option>\n";
1525 $OUT .= " </select></td>\n";
1527 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1530 $OUT .= "</table>\n";
1532 // Return generated HTML code
1537 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1538 // Initial return value
1541 // Do we have a leap year?
1543 $TEST = date('Y', time()) / 4;
1544 $M1 = date("m", time());
1545 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1546 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1547 // First add years...
1548 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1550 $ret += $POST[$prefix."_mo"] * 2628000;
1552 $ret += $POST[$prefix."_we"] * 604800;
1554 $ret += $POST[$prefix."_da"] * 86400;
1556 $ret += $POST[$prefix."_ho"] * 3600;
1558 $ret += $POST[$prefix."_mi"] * 60;
1559 // And at last seconds...
1560 $ret += $POST[$prefix."_se"];
1561 // Return calculated value
1565 // Sends out mail to all administrators
1566 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1567 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1568 // Trim template name
1569 $template = trim($template);
1571 // Load email template
1572 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1574 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1575 // Older version detected!
1576 return SEND_ADMIN_EMAILS($subj, $msg);
1579 // Check which admin shall receive this mail
1580 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1581 array($template), __FILE__, __LINE__);
1582 if (SQL_NUMROWS($result) == 0) {
1583 // Create new entry (to all admins)
1584 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1585 array($template), __FILE__, __LINE__);
1587 // Load admin IDs...
1589 while (list($aid) = SQL_FETCHROW($result)) {
1594 SQL_FREERESULT($result);
1599 // "implode" IDs and query string
1600 $aid = implode(",", $aids);
1602 if (EXT_IS_ACTIVE("events")) {
1603 // Add line to user events
1604 EVENTS_ADD_LINE($subj, $msg, $UID);
1606 // Log error for debug
1607 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1613 } elseif ($aid == "0") {
1614 // Select all email adresses
1615 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`", __FILE__, __LINE__);
1617 // If Admin-ID is not "to-all" select
1618 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`", array($aid), __FILE__, __LINE__);
1622 // Load email addresses and send away
1623 while (list($email) = SQL_FETCHROW($result)) {
1624 SEND_EMAIL($email, $subj, $msg);
1628 SQL_FREERESULT($result);
1631 function CREATE_FANCY_TIME ($stamp) {
1632 // Get data array with years/months/weeks/days/...
1633 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1635 foreach($data as $k => $v) {
1637 // Value is greater than 0 "eval" data to return string
1638 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1644 // Do we have something there?
1645 if (strlen($ret) > 0) {
1646 // Remove leading commata and space
1647 $ret = substr($ret, 2);
1650 $ret = "0 "._SECONDS;
1653 // Return fancy time string
1657 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1658 $SEP = ""; $TOP = "";
1661 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1665 for ($page = 1; $page <= $PAGES; $page++) {
1666 // Is the page currently selected or shall we generate a link to it?
1667 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1668 // Is currently selected, so only highlight it
1669 $NAV .= "<strong>-";
1671 // Open anchor tag and add base URL
1672 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1674 // Add userid when we shall show all mails from a single member
1675 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1677 // Close open anchor tag
1681 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1682 // Is currently selected, so only highlight it
1683 $NAV .= "-</strong>";
1689 // Add seperator if we have not yet reached total pages
1690 if ($page < $PAGES) $NAV .= " | ";
1693 // Define constants only once
1694 if (!defined('__NAV_OUTPUT')) {
1695 define('__NAV_OUTPUT' , $NAV);
1696 define('__NAV_COLSPAN', $colspan);
1697 define('__NAV_TOP' , $TOP);
1698 define('__NAV_SEP' , $SEP);
1701 // Load navigation template
1702 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1705 // Return generated HTML-Code
1713 // Extract host from script name
1714 function EXTRACT_HOST (&$script) {
1715 // Use default SERVER_URL by default... ;) So?
1718 // Is this URL valid?
1719 if (substr($script, 0, 7) == "http://") {
1720 // Use the hostname from script URL as new hostname
1721 $url = substr($script, 7);
1722 $extract = explode("/", $url);
1724 // Done extracting the URL :)
1727 // Extract host name
1728 $host = str_replace("http://", "", $url);
1729 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1731 // Generate relative URL
1732 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1733 if (substr(strtolower($script), 0, 7) == "http://") {
1734 // But only if http:// is in front!
1735 $script = substr($script, (strlen($url) + 7));
1736 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1738 $script = substr($script, (strlen($url) + 8));
1741 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1742 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1748 // Send a GET request
1749 function GET_URL ($script) {
1750 // Compile the script name
1751 $script = COMPILE_CODE($script);
1753 // Extract host name from script
1754 $host = EXTRACT_HOST($script);
1756 // Generate GET request header
1757 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1758 $request .= "Host: " . $host . "\r\n";
1759 $request .= "Referer: " . URL . "/admin.php\r\n";
1760 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1761 $request .= "Content-Type: text/plain\r\n";
1762 $request .= "Cache-Control: no-cache\r\n";
1763 $request .= "Connection: Close\r\n\r\n";
1765 // Send the raw request
1766 $response = SEND_RAW_REQUEST($host, $request);
1768 // Return the result to the caller function
1772 // Send a POST request
1773 function POST_URL ($script, $postData) {
1774 // Is postData an array?
1775 if (!is_array($postData)) {
1777 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1778 return array("", "", "");
1781 // Compile the script name
1782 $script = COMPILE_CODE($script);
1784 // Extract host name from script
1785 $host = EXTRACT_HOST($script);
1787 // Construct request
1788 $data = http_build_query($postData, '','&');
1790 // Generate POST request header
1791 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1792 $request .= "Host: " . $host . "\r\n";
1793 $request .= "Referer: " . URL . "/admin.php\r\n";
1794 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1795 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1796 $request .= "Content-length: " . strlen($data) . "\r\n";
1797 $request .= "Cache-Control: no-cache\r\n";
1798 $request .= "Connection: Close\r\n\r\n";
1801 // Send the raw request
1802 $response = SEND_RAW_REQUEST($host, $request);
1804 // Return the result to the caller function
1808 // Sends a raw request to another host
1809 function SEND_RAW_REQUEST ($host, $request) {
1811 $response = array("", "", "");
1813 // Default is not to use proxy
1816 // Are proxy settins set?
1817 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1823 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1825 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1827 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1831 if (!is_resource($fp)) {
1838 // Generate CONNECT request header
1839 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1840 $proxyTunnel .= "Host: ".$host."\r\n";
1842 // Use login data to proxy? (username at least!)
1843 if (getConfig('proxy_username') != "") {
1845 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1846 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1849 // Add last new-line
1850 $proxyTunnel .= "\r\n";
1851 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1854 fputs($fp, $proxyTunnel);
1858 // No response received
1862 // Read the first line
1863 $resp = trim(fgets($fp, 10240));
1864 $respArray = explode(" ", $resp);
1865 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1866 // Invalid response!
1872 fputs($fp, $request);
1876 $response[] = trim(fgets($fp, 1024));
1882 // Skip first empty lines
1884 foreach ($resp as $idx => $line) {
1886 $line = trim($line);
1888 // Is this line empty?
1891 array_shift($response);
1893 // Abort on first non-empty line
1898 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1900 // Proxy agent found?
1901 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1902 // Proxy header detected, so remove two lines
1903 array_shift($response);
1904 array_shift($response);
1907 // Was the request successfull?
1908 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1909 // Not found / access forbidden
1910 $response = array("", "", "");
1916 // Taken from www.php.net eregi() user comments
1917 function VALIDATE_EMAIL($email) {
1919 $email = COMPILE_CODE($email);
1921 // Check first part of email address
1922 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1925 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1928 $regex = "^".$first."@".$domain."$";
1930 // Return check result
1931 return eregi($regex, $email);
1933 // Function taken from user comments on www.php.net / function eregi()
1934 function VALIDATE_URL ($URL, $compile=true) {
1935 // Trim URL a little
1936 $URL = trim(urldecode($URL));
1937 //* DEBUG: */ echo $URL."<br />";
1939 // Compile some chars out...
1940 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1941 //* DEBUG: */ echo $URL."<br />";
1943 // Check for the extension filter
1944 if (EXT_IS_ACTIVE("filter")) {
1945 // Use the extension's filter set
1946 return FILTER_VALIDATE_URL($URL, false);
1949 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1950 // https:// in front of the URLs
1951 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1954 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1955 // Define all main targets
1956 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1958 // Begin of navigation links
1959 $eval = "\$OUT = \"[ ";
1961 foreach ($TARGETS as $tar) {
1962 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1963 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1964 if (($tar == "lock_user") && ($status == "LOCKED")) {
1965 // Locked accounts shall be unlocked
1966 $eval .= "UNLOCK_USER";
1968 // All other status is fine
1969 $eval .= strtoupper($tar);
1971 $eval .= "_TITLE--}\\\">{--ADMIN_";
1972 if (($tar == "lock_user") && ($status == "LOCKED")) {
1973 // Locked accounts shall be unlocked
1974 $eval .= "UNLOCK_USER";
1976 // All other status is fine
1977 $eval .= strtoupper($tar);
1979 $eval .= "--}</a></span> | ";
1982 // Finish navigation link
1983 $eval = substr($eval, 0, -7)."]\";";
1989 // Function for backward-compatiblity
1990 function ADD_CATEGORY_table ($MODE, $return=false) {
1991 // Load it from the register extension
1992 return REGISTER_ADD_CATEGORY_table ($MODE, $return);
1994 // Generate an email link
1995 function CREATE_EMAIL_LINK ($email, $table = "admins") {
1996 // Default email link (INSECURE! Spammer can read this by harvester programs)
1997 $EMAIL = "mailto:".$email;
1999 // Check for several extensions
2000 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2001 // Create email link for contacting admin in guest area
2002 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2003 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2004 // Create email link for contacting a member within admin area (or later in other areas, too?)
2005 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2006 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2007 // Create email link to contact sponsor within admin area (or like the link above?)
2008 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2011 // Shall I close the link when there is no admin?
2012 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2014 // Return email link
2017 // Generate a hash for extra-security for all passwords
2018 function generateHash ($plainText, $salt = "") {
2021 // Is the required extension "sql_patches" there and a salt is not given?
2022 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2023 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2024 return md5($plainText);
2027 // Do we miss an arry element here?
2028 if (!isConfigEntrySet('file_hash')) {
2030 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2033 // When the salt is empty build a new one, else use the first x configured characters as the salt
2035 // Build server string
2036 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2039 $keys = constant('SITE_KEY').":".constant('DATE_KEY').":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime'))).":".getConfig('master_salt');
2042 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2044 // Calculate number for generating the code
2045 $a = time() + constant('_ADD') - 1;
2047 // Generate SHA1 sum from modula of number and the prime number
2048 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2049 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2050 $sha1 = scrambleString($sha1);
2051 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2052 //* DEBUG: */ $sha1b = descrambleString($sha1);
2053 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2055 // Generate the password salt string
2056 $salt = substr($sha1, 0, getConfig('salt_length'));
2057 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2060 $salt = substr($salt, 0, getConfig('salt_length'));
2061 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2065 return $salt.sha1($salt.$plainText);
2068 function scrambleString($str) {
2072 // Final check, in case of failture it will return unscrambled string
2073 if (strlen($str) > 40) {
2074 // The string is to long
2076 } elseif (strlen($str) == 40) {
2078 $scrambleNums = explode(":", getConfig('pass_scramble'));
2080 // Generate new numbers
2081 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2084 // Scramble string here
2085 //* DEBUG: */ echo "***Original=".$str."***<br />";
2086 for ($idx = 0; $idx < strlen($str); $idx++) {
2087 // Get char on scrambled position
2088 $char = substr($str, $scrambleNums[$idx], 1);
2090 // Add it to final output string
2091 $scrambled .= $char;
2094 // Return scrambled string
2095 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2099 function descrambleString($str) {
2100 // Scramble only 40 chars long strings
2101 if (strlen($str) != 40) return $str;
2103 // Load numbers from config
2104 $scrambleNums = explode(":", getConfig('pass_scramble'));
2107 if (count($scrambleNums) != 40) return $str;
2109 // Begin descrambling
2110 $orig = str_repeat(" ", 40);
2111 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2112 for ($idx = 0; $idx < 40; $idx++) {
2113 $char = substr($str, $idx, 1);
2114 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2117 // Return scrambled string
2118 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2122 function genScrambleString ($len) {
2123 // Prepare array for the numbers
2124 $scrambleNumbers = array();
2126 // First we need to setup randomized numbers from 0 to 31
2127 for ($idx = 0; $idx < $len; $idx++) {
2129 $rand = mt_rand(0, ($len -1));
2131 // Check for it by creating more numbers
2132 while (array_key_exists($rand, $scrambleNumbers)) {
2133 $rand = mt_rand(0, ($len -1));
2137 $scrambleNumbers[$rand] = $rand;
2140 // So let's create the string for storing it in database
2141 $scrambleString = implode(":", $scrambleNumbers);
2142 return $scrambleString;
2145 // Append data like session ID or referal ID to the given URL which would
2146 // normally be stored in cookies
2147 function ADD_URL_DATA ($URL) {
2151 // Determine URL binder
2153 if (strpos($URL, "?") !== false) $BIND = "&";
2155 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2156 // Cookies are not accepted
2157 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2158 // Cookie found in URL
2159 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2160 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2161 // Not found! So let's set default here
2162 $ADD .= $BIND."refid=".getConfig('def_refid');
2166 // Add all together and return it
2170 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2171 function generatePassString ($passHash) {
2172 // Return vanilla password hash
2175 // Is a secret key and master salt already initialized?
2176 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2177 // Only calculate when the secret key is generated
2178 $newHash = ""; $start = 9;
2179 for ($idx = 0; $idx < 10; $idx++) {
2180 $part1 = hexdec(substr($passHash, $start, 4));
2181 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2182 $mod = dechex($idx);
2183 if ($part1 > $part2) {
2184 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2185 } elseif ($part2 > $part1) {
2186 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2188 $mod = substr(round($mod), 0, 4);
2189 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2190 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2195 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2196 $ret = generateHash($newHash, getConfig('master_salt'));
2197 //* DEBUG: */ print($ret."<br />\n");
2200 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2201 $ret = md5($passHash);
2202 //* DEBUG: */ echo "++".$ret."++<br />\n";
2209 // Fix "deleted" cookies
2210 function FIX_DELETED_COOKIES ($cookies) {
2211 // Is this an array with entries?
2212 if ((is_array($cookies)) && (count($cookies) > 0)) {
2213 // Then check all cookies if they are marked as deleted!
2214 foreach ($cookies as $cookieName) {
2215 // Is the cookie set to "deleted"?
2216 if (get_session($cookieName) == "deleted") {
2217 set_session($cookieName, "");
2223 // Output error messages in a fasioned way and die...
2224 function mxchange_die ($msg) {
2226 LOAD_INC_ONCE("inc/header.php");
2228 // Load the message template
2229 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2232 LOAD_INC_ONCE("inc/footer.php");
2238 // Display parsing time and number of SQL queries in footer
2239 function DISPLAY_PARSING_TIME_FOOTER() {
2240 // Is the timer started?
2241 if (!isset($GLOBALS['startTime'])) {
2247 $endTime = microtime(true);
2249 // "Explode" both times
2250 $start = explode(" ", $GLOBALS['startTime']);
2251 $end = explode(" ", $endTime);
2252 $runTime = $end[0] - $start[0];
2253 if ($runTime < 0) $runTime = 0;
2254 $runTime = TRANSLATE_COMMA($runTime);
2258 'runtime' => $runTime,
2259 'numSQLs' => (getConfig('sql_count') + 1),
2260 'numTemplates' => (getConfig('num_templates') + 1)
2263 // Load the template
2264 LOAD_TEMPLATE("show_timings", false, $content);
2267 // Unset/set session variables
2268 function set_session ($var, $value) {
2271 // Abort in CSS mode here
2272 if ($CSS == 1) return true;
2274 // Trim value and session variable
2275 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2277 // Is the session variable set?
2278 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2279 // Remove the session
2280 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2281 unset($_SESSION[$var]);
2282 return session_unregister($var);
2283 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2285 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2286 $_SESSION[$var] = $value;
2287 return session_register($var);
2288 } elseif (!empty($value)) {
2290 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2291 $_SESSION[$var] = $value;
2295 // Ignored (but valid)
2296 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2300 // Check wether a boolean constant is set
2301 // Taken from user comments in PHP documentation for function constant()
2302 function isBooleanConstantAndTrue($constName) { // : Boolean
2305 // Failed by default
2309 if (isset($cacheArray['const'][$constName])) {
2311 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2312 $res = $cacheArray['const'][$constName];
2315 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2316 if (defined($constName)) $res = (constant($constName) === true);
2319 $cacheArray['const'][$constName] = $res;
2321 //* DEBUG: */ var_dump($res);
2327 // Check wether a session variable is set
2328 function isSessionVariableSet ($var) {
2329 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2330 return (isset($_SESSION[$var]));
2332 // Returns wether the value of the session variable or NULL if not set
2333 function get_session ($var) {
2336 // Default is not found! ;-)
2339 // Is the variable there or cached values?
2340 if (isset($cacheArray['session'][$var])) {
2341 // Get cached value (skips a lot SQL_ESCAPE() calles!
2342 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2343 $value = $cacheArray['session'][$var];
2344 } elseif (isSessionVariableSet($var)) {
2345 // Then get it secured!
2346 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2347 $value = SQL_ESCAPE($_SESSION[$var]);
2350 $cacheArray['session'][$var] = $value;
2357 // Send notification to admin
2358 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2359 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2361 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2363 // Send outdated way
2364 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2365 SEND_ADMIN_EMAILS($subject, $msg);
2369 // Destroy user session
2370 function destroy_user_session () {
2372 $GLOBALS['userid'] = 0;
2374 // Remove all user data from session
2375 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2378 // Merges an array together but only if both are arrays
2379 function merge_array ($array1, $array2) {
2380 // Are both an array?
2381 if ((is_array($array1)) && (is_array($array2))) {
2382 // Merge all together
2383 return array_merge($array1, $array2);
2384 } elseif (is_array($array1)) {
2385 // Return left array
2386 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
2388 } elseif (is_array($array2)) {
2389 // Return right array
2390 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
2394 // Both are not arrays
2395 debug_report_bug(__FUNCTION__.": No arrays provided!");
2398 // Debug message logger
2399 function DEBUG_LOG ($file, $line, $message, $force=true) {
2400 // Is debug mode enabled?
2401 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force === true)) {
2402 // Log this message away
2403 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2404 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2409 // Reads a directory with PHP files in and gets only files back
2410 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2414 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2417 while ($baseFile = readdir($dirPointer)) {
2418 // Load file only if extension is active
2420 $file = $baseDir.$baseFile;
2422 // Is this a valid reset file?
2423 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2424 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2425 // Remove both for extension name
2426 $extName = substr($baseFile, strlen($prefix), -4);
2429 $extId = GET_EXT_ID($extName);
2431 // Is the extension valid and active?
2432 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2433 // Then add this file
2435 } elseif ($extId == 0) {
2436 // Add non-extension files as well
2443 closedir($dirPointer);
2448 // Return array with include files
2451 // Load more reset scripts
2452 function RESET_ADD_INCLUDES () {
2453 // Is the reset set or old sql_patches?
2454 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2459 // Get more daily reset scripts
2460 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2463 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2465 // Create current week mark
2466 $currWeek = date("W", time());
2469 if (getConfig('last_week') != $currWeek) {
2470 // Include weekly reset scripts
2471 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2474 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2477 // Create current month mark
2478 $currMonth = date("m", time());
2481 if (getConfig('last_month') != $currMonth) {
2482 // Include monthly reset scripts
2483 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2486 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2492 // Handle extra values
2493 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2494 // Default is the value itself
2497 // Do we have a special filter function?
2498 if (!empty($filterFunction)) {
2499 // Does the filter function exist?
2500 if (function_exists($filterFunction)) {
2501 // Do we have extra parameters here?
2502 if (!empty($extraValue)) {
2503 // Put both parameters in one new array by default
2504 $args = array($value, $extraValue);
2506 // If we have an array simply use it and pre-extend it with our value
2507 if (is_array($extraValue)) {
2508 // Make the new args array
2509 $args = merge_array(array($value), $extraValue);
2512 // Call the multi-parameter call-back
2513 $ret = call_user_func_array($filterFunction, $args);
2515 // One parameter call
2516 $ret = call_user_func($filterFunction, $value);
2524 // Check if given FQFN is a readable file
2525 function FILE_READABLE($fqfn) {
2527 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2529 // Converts timestamp selections into a timestamp
2530 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2531 // Init test variable
2534 // Get last three chars
2535 $test = substr($id, -3);
2537 // Improved way of checking! :-)
2538 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2539 // Found a multi-selection for timings?
2540 $test = substr($id, 0, -3);
2541 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)) {
2542 // Generate timestamp
2543 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2544 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2546 // Remove data from array
2547 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2548 unset($POST[$test."_".$rem]);
2552 unset($id); $skip = true; $test2 = $test;
2555 // Process this entry
2556 $skip = false; $test2 = "";
2559 // Reverts the german decimal comma into Computer decimal dot
2560 function REVERT_COMMA ($str) {
2561 // Default float is not a float... ;-)
2564 // Which language is selected?
2565 switch (GET_LANGUAGE()) {
2566 case "de": // German language
2567 // Remove german thousand dots first
2568 $str = str_replace(".", "", $str);
2570 // Replace german commata with decimal dot and cast it
2571 $float = (float)str_replace(",", ".", $str);
2574 default: // US and so on
2575 // Remove thousand dots first and cast
2576 $float = (float)str_replace(",", "", $str);
2584 // Handle menu-depending failed logins and return the rendered content
2585 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2586 // Default output is empty ;-)
2589 // Is the session data set?
2590 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2591 // Ignore zero values
2592 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
2593 // Non-guest has login failures found, get both data and prepare it for template
2594 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2596 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
2597 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2601 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
2604 // Reset session data
2605 set_session('mxchange_'.$accessLevel.'_failures', "");
2606 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2609 // Return rendered content
2614 function REBUILD_CACHE ($cache, $inc="") {
2615 global $cacheInstance, $CSS;
2617 // Shall I remove the cache file?
2618 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2620 if ($cacheInstance->loadCacheFile($cache)) {
2622 $cacheInstance->destroyCacheFile();
2625 // Include file given?
2628 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
2630 // Is the include there?
2631 if (INCLUDE_READABLE($INC)) {
2632 // And rebuild it from scratch
2633 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2636 // Include not found!
2637 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2643 // Purge admin menu cache
2644 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2645 global $cacheInstance;
2647 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2648 if (!EXT_IS_ACTIVE("cache")) {
2649 // Cache extension not active
2651 } elseif (!is_object($cacheInstance)) {
2652 // No cache instance!
2653 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2655 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
2656 // Caching disabled (currently experiemental!)
2660 // Experiemental feature!
2661 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2664 // Translates the "pool type" into human-readable
2665 function TRANSLATE_POOL_TYPE ($type) {
2666 // Default type is unknown
2667 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
2669 // Generate constant
2670 $constName = sprintf("POOL_TYPE_%s", $type);
2673 if (defined($constName)) {
2675 $translated = getMessage($constName);
2678 // Return "translation"
2682 // "Getter" for remote IP number
2683 function GET_REMOTE_ADDR () {
2684 // Get remote ip from environment
2685 $remoteAddr = getenv('REMOTE_ADDR');
2687 // Is removeip installed?
2688 if (EXT_IS_ACTIVE("removeip")) {
2689 // Then anonymize it
2690 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2696 // "Getter" for remote hostname
2697 function GET_REMOTE_HOST () {
2698 // Get remote ip from environment
2699 $remoteHost = getenv('REMOTE_HOST');
2701 // Is removeip installed?
2702 if (EXT_IS_ACTIVE("removeip")) {
2703 // Then anonymize it
2704 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2710 // "Getter" for user agent
2711 function GET_USER_AGENT () {
2712 // Get remote ip from environment
2713 $userAgent = getenv('HTTP_USER_AGENT');
2715 // Is removeip installed?
2716 if (EXT_IS_ACTIVE("removeip")) {
2717 // Then anonymize it
2718 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2724 // "Getter" for referer
2725 function GET_REFERER () {
2726 // Get remote ip from environment
2727 $referer = getenv('HTTP_REFERER');
2729 // Is removeip installed?
2730 if (EXT_IS_ACTIVE("removeip")) {
2731 // Then anonymize it
2732 $referer = GET_ANONYMOUS_REFERER($referer);
2739 // Adds a bonus mail to the queue
2740 // This is a high-level function!
2741 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2742 // Use mode from data if not set and availble ;-)
2743 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2745 // Generate receiver list
2746 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2749 if (!empty($RECEIVER)) {
2750 // Add bonus mail to queue
2751 ADD_BONUS_MAIL_TO_QUEUE(
2763 // Mail inserted into bonus pool
2764 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
2765 } elseif ($output) {
2766 // More entered than can be reached!
2767 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
2770 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2774 // Determines referal id and sets it
2775 function DETERMINE_REFID () {
2776 global $CLICK, $_SERVER;
2778 // Check if refid is set
2779 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2780 // The variable user comes from the click-counter script click.php and we only accept this here
2781 $GLOBALS['refid'] = bigintval($_GET['user']);
2782 } elseif (!empty($_POST['refid'])) {
2783 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2784 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2785 } elseif (!empty($_GET['refid'])) {
2786 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2787 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2788 } elseif (!empty($_GET['ref'])) {
2789 // Set refid=ref (the referal link uses such variable)
2790 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2791 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2792 // Set session refid als global
2793 $GLOBALS['refid'] = bigintval(get_session('refid'));
2794 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2795 // Set default refid as refid in URL
2796 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2797 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2798 // Select a random user which has confirmed enougth mails
2799 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2801 // No default ID when sql_patches is not installed or none set
2802 $GLOBALS['refid'] = 0;
2805 // Set cookie when default refid > 0
2806 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2808 set_session('refid', $GLOBALS['refid']);
2811 // Return determined refid
2812 return $GLOBALS['refid'];
2815 // Destroys the admin session
2816 function destroyAdminSession ($destroy = true) {
2817 // Kill maybe existing session variables including array elements
2818 set_session('admin_login', "");
2819 set_session('admin_md5' , "");
2820 set_session('admin_last' , "");
2821 set_session('admin_to' , "");
2823 // Destroy session and return status
2825 return session_destroy();
2828 // All fine if we shall not really destroy the session
2832 // Checks if a given apache module is loaded
2833 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2834 // Check it and return result
2835 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2838 // Merges $_CONFIG with data in given array
2839 function mergeConfig ($newConfig) {
2841 $_CONFIG = merge_array($_CONFIG, $newConfig);
2844 // Getter for $_CONFIG entries
2845 function getConfig ($entry) {
2851 // Is the entry there?
2852 if (isConfigEntrySet($entry)) {
2854 $value = $_CONFIG[$entry];
2861 // Setter for $_CONFIG entries
2862 function setConfigEntry ($entry, $value) {
2865 // Secure the entry name
2866 $entry = SQL_ESCAPE($entry);
2869 $_CONFIG[$entry] = $value;
2872 // Checks wether the given config entry is set
2873 function isConfigEntrySet ($entry) {
2875 return (isset($_CONFIG[$entry]));
2878 // Increment or init with given value or 1 as default the given config entry
2879 function incrementConfigEntry ($configEntry, $value=1) {
2882 // Increment it if set or init it with 1
2883 if (getConfig($configEntry) > 0) {
2884 $_CONFIG[$configEntry] += $value;
2886 $_CONFIG[$configEntry] = $value;
2890 // "Getter" for language strings
2891 // @TODO Rewrite all language constants to this function.
2892 function getMessage ($messageId) {
2893 // Default is not found!
2894 $return = "!".$messageId."!";
2896 // Is the language string found?
2897 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2898 // Language array element found in small_letters
2899 $return = $GLOBALS['msg'][$messageId];
2900 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2901 // @DEPRECATED Language array element found in BIG_LETTERS
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", constant('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", constant('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", constant('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 // Read a given file
3008 function READ_FILE ($FQFN, $sqlPrepare = false) {
3010 if (function_exists('file_get_contents')) {
3012 $content = file_get_contents($FQFN);
3014 // Fall-back to implode-file chain
3015 $content = implode("", file($FQFN));
3018 // Prepare SQL queries?
3019 if ($sqlPrepare === true) {
3020 // Remove some unwanted chars
3021 $content = str_replace("\r", "", $content);
3022 $content = str_replace("\n\n", "\n", $content);
3025 // Return the content
3029 // Writes content to a file
3030 function WRITE_FILE ($FQFN, $content) {
3031 // Is the function there?
3032 if (function_exists('file_put_contents')) {
3033 // Write it directly
3034 file_put_contents($FQFN, $content);
3036 // Write it with fopen
3037 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
3038 fwrite($fp, $content);
3046 // Generates an error code from given account status
3047 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3048 // Default error code if unknown account status
3049 $ERROR = constant('CODE_UNKNOWN_STATUS');
3051 // Generate constant name
3052 $constantName = sprintf("CODE_ID_%s", $status);
3054 // Is the constant there?
3055 if (defined($constantName)) {
3057 $ERROR = constant($constantName);
3060 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3063 // Return error code
3067 // Clears the output buffer. This function does *NOT* backup sent content.
3068 function clearOutputBuffer () {
3069 // Trigger an error on failure
3070 if (!ob_end_clean()) {
3072 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
3076 // "Getter" for revision/version data
3077 function getActualVersion ($type = 0) {
3078 // By default nothing is new... ;-)
3081 // FQFN of revision file
3082 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
3084 // Check for revision file
3085 if (!FILE_READABLE($FQFN)) {
3086 // Not found, so we need to create it
3089 // Revision file found
3090 $ins_vers = explode("\n", READ_FILE($FQFN));
3092 // Is the content valid?
3093 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
3094 // File needs update!
3097 // Revision-File has valid Data and isn't 'new' so return the Rev-Number
3098 return trim($ins_vers[$type]);
3102 // Has it been updated?
3103 if ($new === true) {
3104 // No Revision-File or has no valid Data so read the Revision from the Server.
3105 $version = GET_URL("check-updates3.php");
3108 $akt_vers[] = trim($version[10]);
3109 $akt_vers[] = trim($version[9]);
3110 $akt_vers[] = trim($version[8]);
3113 WRITE_FILE($FQFN, implode("\n", $akt_vers));
3115 // Return requested content
3116 return trim($akt_vers[$type]);
3120 // Loads an include file and logs any missing files for debug purposes
3121 function LOAD_INC ($INC) {
3122 // Get constant path
3123 $PATH = constant('PATH');
3125 // Use the include file name directly
3126 // @TODO Try to find all locations where an FQFN is given to these two
3127 // @TODO functions and avoid it.
3130 // Check if PATH is in $INC
3131 if (substr($INC, 0, $PATH) != $PATH) {
3132 // Add it. This is why we need a trailing slash in config.php
3133 $FQFN = $PATH . $INC;
3136 // Is the include file there?
3137 if (!FILE_READABLE($FQFN)) {
3138 // Not there so log it
3139 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Include file %s not found.", basename($INC)));
3147 // Loads an include file once
3148 function LOAD_INC_ONCE ($INC) {
3151 // Is it not loaded?
3152 if (!isset($cacheArray['load_once'][$INC])) {
3153 // Then try to load it
3156 // And mark it as loaded
3157 $cacheArray['load_once'][$INC] = true;
3161 // Back-ported from the new ship-simu engine. :-)
3162 function debug_get_printable_backtrace () {
3164 $backtrace = "<ol>\n";
3166 // Get and prepare backtrace for output
3167 $backtraceArray = debug_backtrace();
3168 foreach ($backtraceArray as $key => $trace) {
3169 if (!isset($trace['file'])) $trace['file'] = __FILE__;
3170 if (!isset($trace['line'])) $trace['line'] = __LINE__;
3171 if (!isset($trace['args'])) $trace['args'] = array();
3172 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span></li>\n";
3176 $backtrace .= "</ol>\n";
3178 // Return the backtrace
3182 // Output a debug backtrace to the user
3183 function debug_report_bug ($message = "") {
3186 // Is the optional message set?
3187 if (!empty($message)) {
3189 $debug = sprintf("Note: %s<br />\n",
3193 // @TODO Add a little more infos here
3194 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
3198 $debug .= ("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
3199 $debug .= (debug_get_printable_backtrace());
3200 $debug .= ("</pre>Thank you for your help finding bugs.");
3206 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
3207 function generateSeed () {
3208 list($usec, $sec) = explode(" ", microtime());
3209 return ((float)$sec + (float)$usec);
3212 // Converts a message code to a human-readable message
3213 function convertCodeToMessage ($code) {
3216 case constant('CODE_LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
3217 case constant('CODE_LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
3218 case constant('CODE_DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
3219 case constant('CODE_POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
3220 case constant('CODE_ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
3221 case constant('CODE_USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
3222 case constant('CODE_STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
3223 case constant('CODE_ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
3225 case constant('CODE_ERROR_MAILID'):
3226 if (EXT_IS_ACTIVE($ext, true)) {
3227 $msg = getMessage('ERROR_CONFIRMING_MAIL');
3229 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
3233 case constant('CODE_EXTENSION_PROBLEM'):
3234 if (isset($_GET['ext'])) {
3235 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), SQL_ESCAPE($_GET['ext']));
3237 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
3241 case constant('CODE_COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
3242 case constant('CODE_BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
3243 case constant('CODE_LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
3244 default : $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code); break;
3247 // Return the message
3251 // Checks wether the given extension is currently not installed
3252 // and redirects if so.
3253 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
3254 // Is the extension uninstalled/inactive?
3255 if (!EXT_IS_ACTIVE($ext_name)) {
3256 // Redirect to index
3257 LOAD_URL("modules.php?module=index&msg=".constant('CODE_EXTENSION_PROBLEM')."&ext=".$ext_name);
3261 // Generate a "link" for the given admin id (aid)
3262 function GENERATE_AID_LINK ($aid) {
3263 // No assigned admin is default
3264 $admin = "<div class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</div>";
3266 // Zero? = Not assigned
3268 // Load admin's login
3269 $login = GET_ADMIN_LOGIN($aid);
3270 if ($login != "***") {
3271 // Is the extension there?
3272 if (EXT_IS_ACTIVE("admins")) {
3274 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
3276 // Extension not found
3277 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
3281 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
3289 // Checks wether an include file (non-FQFN better) is readable
3290 function INCLUDE_READABLE ($INC) {
3292 $FQFN = constant('PATH') . $INC;
3295 return FILE_READABLE($FQFN);
3298 //////////////////////////////////////////////////
3299 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3300 //////////////////////////////////////////////////
3302 if (!function_exists('html_entity_decode')) {
3303 // Taken from documentation on www.php.net
3304 function html_entity_decode ($string) {
3305 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3306 $trans_tbl = array_flip($trans_tbl);
3307 return strtr($string, $trans_tbl);