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="") {
189 // Regular text message to add to $FATAL
192 // $message is text with a mask plus extras to insert into the text
193 $message = sprintf($message, $extra);
197 // Log fatal messages away
198 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
201 // Getter for total fatal message count
202 function getTotalFatalErrors () {
208 // Do we have at least the first entry?
209 if (!empty($FATAL[0])) {
211 $count = count($FATAL);
218 // Load a template file and return it's content (only it's name; do not use ' or ")
219 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
220 // Add more variables which you want to use in your template files
221 global $DATA, $_CONFIG, $username;
223 // Make all template names lowercase
224 $template = strtolower($template);
226 // Count the template load
227 incrementConfigEntry('num_templates');
229 // Prepare IP number and User Agent
230 $REMOTE_ADDR = GET_REMOTE_ADDR();
231 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
232 $HTTP_USER_AGENT = GET_USER_AGENT();
236 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
238 // @DEPRECATED Try to rewrite the if() condition
239 if ($template == "member_support_form") {
240 // Support request of a member
241 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
242 array($GLOBALS['userid']), __FILE__, __LINE__);
244 // Is content an array?
245 if (is_array($content)) {
247 $content = merge_array($content, SQL_FETCHARRAY($result));
250 $content['gender'] = TRANSLATE_GENDER($content['gender']);
252 // DEPRECATED: Load data in direct variables
253 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
256 $gender = TRANSLATE_GENDER($gender);
257 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
261 SQL_FREERESULT($result);
264 // Generate date/time string
265 $date_time = MAKE_DATETIME(time(), "1");
268 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
271 // Check for admin/guest/member templates
272 if (strpos($template, "admin_") > -1) {
273 // Admin template found
275 } elseif (strpos($template, "guest_") > -1) {
276 // Guest template found
278 } elseif (strpos($template, "member_") > -1) {
279 // Member template found
281 } elseif (strpos($template, "install_") > -1) {
282 // Installation template found
284 } elseif (strpos($template, "ext_") > -1) {
285 // Extension template found
287 } elseif (strpos($template, "la_") > -1) {
288 // "Logical-area" template found
291 // Test for extension
292 $test = substr($template, 0, strpos($template, "_"));
293 if (EXT_IS_ACTIVE($test)) {
294 // Set extra path to extension's name
299 ////////////////////////
300 // Generate file name //
301 ////////////////////////
302 $file = $BASE.$MODE.$template.".tpl";
304 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
305 // Select what depended header/footer template file for admin/guest/member area
306 $file2 = sprintf("%s%s%s_%s.tpl",
310 SQL_ESCAPE($GLOBALS['what'])
314 if (FILE_READABLE($file2)) $file = $file2;
316 // Remove variable from memory
320 // Does the special template exists?
321 if (!FILE_READABLE($file)) {
322 // Reset to default template
323 $file = $BASE.$template.".tpl";
326 // Now does the final template exists?
327 if (FILE_READABLE($file)) {
328 // The local file does exists so we load it. :)
329 $tmpl_file = READ_FILE($file);
331 // Replace ' to our own chars to preventing them being quoted
332 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
334 // Do we have to compile the code?
336 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
338 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
341 // Simply return loaded code
345 // Add surrounding HTML comments to help finding bugs faster
346 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
347 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
348 // Only admins shall see this warning or when installation mode is active
349 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
350 (".basename($file).")<br />
353 <pre>".print_r($content, true)."</pre>
355 <pre>".print_r($DATA, true)."</pre>
359 // Remove content and data
363 // Do we have some content to output or return?
365 // Not empty so let's put it out! ;)
367 // Return the HTML code
373 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
374 // Warning, empty output!
375 return "E:".$template."<br />\n";
379 // Send mail out to an email address
380 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
381 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
383 // Compile subject line (for POINTS constant etc.)
384 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
388 if ((!eregi("@", $TO)) && ($TO > 0)) {
389 // Value detected, is the message extension installed?
390 if (EXT_IS_ACTIVE("msg")) {
391 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
394 // Load email address
395 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
396 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
398 // Does the user exist?
399 if (SQL_NUMROWS($result_email)) {
400 // Load email address
401 list($TO) = SQL_FETCHROW($result_email);
404 $TO = constant('WEBMASTER');
408 SQL_FREERESULT($result_email);
410 } elseif ("$TO" == "0") {
412 $TO = constant('WEBMASTER');
414 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
416 // Check for PHPMailer or debug-mode
417 if (!CHECK_PHPMAILER_USAGE()) {
418 // Not in PHPMailer-Mode
420 // Load email header template
421 $FROM = LOAD_EMAIL_TEMPLATE("header");
424 $FROM .= LOAD_EMAIL_TEMPLATE("header");
426 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
428 // Load email header template
429 $FROM = LOAD_EMAIL_TEMPLATE("header");
432 $FROM .= LOAD_EMAIL_TEMPLATE("header");
437 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
441 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
444 // Fix HTML parameter (default is no!)
445 if (empty($HTML)) $HTML = "N";
446 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
447 // In debug mode we want to display the mail instead of sending it away so we can debug this part
449 ".htmlentities(trim($FROM))."
451 Subject : ".$SUBJECT."
454 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
455 // Send mail as HTML away
456 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
457 } elseif (!empty($TO)) {
459 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
460 } elseif ($HTML == "N") {
462 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
466 // Check if legacy or PHPMailer command
468 function CHECK_PHPMAILER_USAGE() {
469 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
473 * Send out a raw email with PHPMailer class or legacy mail() command
475 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
476 // Shall we use PHPMailer class or legacy mode?
477 if (CHECK_PHPMAILER_USAGE()) {
478 // Use PHPMailer class with SMTP enabled
479 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
480 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
483 $mail = new PHPMailer();
484 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
487 $mail->SMTPAuth = true;
488 $mail->Host = constant('SMTP_HOSTNAME');
490 $mail->Username = constant('SMTP_USER');
491 $mail->Password = constant('SMTP_PASSWORD');
493 $mail->From = constant('WEBMASTER');
497 $mail->FromName = constant('MAIN_TITLE');
498 $mail->Subject = $subject;
499 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
501 $mail->AltBody = "Your mail program required HTML support to read this mail!";
502 $mail->WordWrap = 70;
505 $mail->Body = html_entity_decode($msg);
507 $mail->AddAddress($to, "");
508 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
509 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
510 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
513 // Use legacy mail() command
514 @mail($to, $subject, html_entity_decode($msg), $from);
519 // Generate a password in a specified length or use default password length
520 function GEN_PASS ($LEN = 0) {
521 // Auto-fix invalid length of zero
522 if ($LEN == 0) $LEN = getConfig('pass_len');
524 // Initialize array with all allowed chars
525 $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,-,+,_,/");
527 // Start creating password
529 for ($i = 0; $i < $LEN; $i++) {
530 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
533 // When the size is below 40 we can also add additional security by scrambling it
534 if (strlen($PASS) <= 40) {
535 // Also scramble the password
536 $PASS = scrambleString($PASS);
539 // Return the password
543 function MAKE_DATETIME ($time, $mode="0")
547 return NEVER_HAPPENED;
549 // Filter out numbers
550 $time = bigintval($time);
553 switch (GET_LANGUAGE())
555 case "de": // German date / time format
557 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
558 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
559 case "2": $ret = date("d.m.Y|H:i", $time); break;
560 case "3": $ret = date("d.m.Y", $time); break;
562 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
567 default: // Default is the US date / time format!
569 case "0": $ret = date("r", $time); break;
570 case "1": $ret = date("Y-m-d - g:i A", $time); break;
571 case "2": $ret = date("y-m-d|H:i", $time); break;
572 case "3": $ret = date("y-m-d", $time); break;
574 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
581 // Translates the american decimal dot into a german comma
582 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
583 // Default is 3 you can change this in admin area "Misc -> Misc Options"
584 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
586 // Use from config is default
587 $maxComma = getConfig('max_comma');
589 // Use from parameter?
590 if ($max > 0) $maxComma = $max;
593 if (($cut) && ($max == 0)) {
594 // Test for commata if in cut-mode
595 $com = explode(".", $dotted);
596 if (count($com) < 2) {
597 // Don't display commatas even if there are none... ;-)
603 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
606 switch (GET_LANGUAGE()) {
608 $dotted = number_format($dotted, $maxComma, ",", ".");
612 $dotted = number_format($dotted, $maxComma, ".", ",");
616 // Return translated value
621 function DEREFERER ($URL) {
622 // Don't de-refer our own links!
623 if (substr($URL, 0, strlen(URL)) != URL) {
624 // De-refer this link
625 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
633 function TRANSLATE_GENDER ($gender) {
636 case "M": $ret = GENDER_M; break;
637 case "F": $ret = GENDER_F; break;
638 case "C": $ret = GENDER_C; break;
639 default : $ret = $gender; break;
644 function FRAMETESTER($URL) {
645 // Prepare frametester URL
646 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
648 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
650 return $frametesterUrl;
653 function SELECTION_COUNT($array) {
655 if (is_array($array)) {
656 foreach ($array as $key => $sel) {
657 if (!empty($sel)) $ret++;
663 function IMG_CODE ($code, $type, $DATA, $uid) {
664 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
667 function TRANSLATE_STATUS($status) {
671 $ret = ACCOUNT_UNCONFIRMED;
675 $ret = ACCOUNT_CONFIRMED;
679 $ret = ACCOUNT_LOCKED;
684 $ret = ACCOUNT_DELETED;
688 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
689 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
695 function GET_LANGUAGE() {
698 // Set default return value to default language from config
699 $ret = constant('DEFAULT_LANG');
704 // Is the variable set
705 if (!empty($_GET['mx_lang'])) {
706 // Accept only first 2 chars
707 $lang = substr($_GET['mx_lang'], 0, 2);
708 } elseif (isset($cacheArray['language'])) {
710 $ret = $cacheArray['language'];
711 } elseif (!empty($lang)) {
712 // Check if main language file does exist
713 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
714 // Okay found, so let's update cookies
717 } elseif (!isSessionVariableSet('mx_lang')) {
718 // Return stored value from cookie
719 $ret = get_session('mx_lang');
721 // Fixes a warning before the session has the mx_lang constant
722 if (empty($ret)) $ret = constant('DEFAULT_LANG');
726 $cacheArray['language'] = $ret;
732 function SET_LANGUAGE ($lang) {
733 // Accept only first 2 chars!
734 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
737 set_session('mx_lang', $lang);
740 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
741 global $DATA, $REPLACER, $_CONFIG;
743 // Make sure all template names are lowercase!
744 $template = strtolower($template);
746 // Default "nickname" if extension is not installed
749 // Prepare IP number and User Agent
750 $REMOTE_ADDR = GET_REMOTE_ADDR();
751 $HTTP_USER_AGENT = GET_USER_AGENT();
754 $ADMIN = constant('MAIN_TITLE');
756 // Is the admin logged in?
759 $aid = GET_CURRENT_ADMIN_ID();
762 $ADMIN = GET_ADMIN_EMAIL($aid);
765 // Neutral email address is default
766 $email = constant('WEBMASTER');
768 // Expiration in a nice output format
769 if (getConfig('auto_purge') == 0) {
770 // Will never expire!
771 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
773 // Create nice date string
774 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
777 // Is content an array?
778 if (is_array($content)) {
779 // Add expiration to array, $EXPIRATION is now deprecated!
780 $content['expiration'] = $EXPIRATION;
784 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
785 if (($UID > 0) && (is_array($content))) {
786 // If nickname extension is installed, fetch nickname as well
787 if (EXT_IS_ACTIVE("nickname")) {
788 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
790 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
791 array(bigintval($UID)), __FILE__, __LINE__);
793 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
795 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
796 array(bigintval($UID)), __FILE__, __LINE__);
799 // Fetch and merge data
800 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
801 $content = merge_array($content, SQL_FETCHARRAY($result));
802 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
805 SQL_FREERESULT($result);
808 // Translate M to male or F to female if present
809 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
811 // Overwrite email from data if present
812 if (isset($content['email'])) $email = $content['email'];
814 // Store email for some functions in global data array
815 $DATA['email'] = $email;
818 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
820 // Check for admin/guest/member templates
821 if (strpos($template, "admin_") > -1) {
822 // Admin template found
823 $file = $BASE."admin/".$template.".tpl";
824 } elseif (strpos($template, "guest_") > -1) {
825 // Guest template found
826 $file = $BASE."guest/".$template.".tpl";
827 } elseif (strpos($template, "member_") > -1) {
828 // Member template found
829 $file = $BASE."member/".$template.".tpl";
831 // Test for extension
832 $test = substr($template, 0, strpos($template, "_"));
833 if (EXT_IS_ACTIVE($test)) {
834 // Set extra path to extension's name
835 $file = $BASE.$test."/".$template.".tpl";
837 // No special filename
838 $file = $BASE.$template.".tpl";
842 // Does the special template exists?
843 if (!FILE_READABLE($file)) {
844 // Reset to default template
845 $file = $BASE.$template.".tpl";
848 // Now does the final template exists?
850 if (FILE_READABLE($file)) {
851 // The local file does exists so we load it. :)
852 $tmpl_file = READ_FILE($file);
853 $tmpl_file = addslashes($tmpl_file);
856 $tmpl_file = "\$newContent = html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
858 } elseif (!empty($template)) {
859 // Template file not found!
860 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
861 {--TEMPLATE_CONTENT--}
862 <pre>".print_r($content, true)."</pre>
864 <pre>".print_r($DATA, true)."</pre>
867 // Debug mode not active? Then remove the HTML tags
868 if (!isBooleanConstantAndTrue('DEBUG_MODE')) $newContent = strip_tags($newContent);
870 // No template name supplied!
871 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
874 // Is there some content?
875 if (empty($newContent)) {
877 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
878 // Add last error if the required function exists
879 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
882 // Remove content and data
886 // Return compiled content
887 return COMPILE_CODE($newContent);
890 function MAKE_TIME($H, $M, $S, $stamp) {
891 // Extract day, month and year from given timestamp
892 $DAY = date("d", $stamp);
893 $MONTH = date("m", $stamp);
894 $YEAR = date('Y', $stamp);
896 // Create timestamp for wished time which depends on extracted date
897 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
900 function LOAD_URL($URL, $addUrlData=true) {
901 global $CSS, $footer;
903 // Compile out URI codes
904 $URL = COMPILE_CODE($URL);
906 // Check if http(s):// is there
907 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
908 // Make all URLs full-qualified
913 //* DEBUG: */ debug_report_bug();
914 $OUTPUT = ob_get_contents();
916 // Clear it only if there is content
917 if (!empty($OUTPUT)) {
921 // Add some data to URL if cookies are not accepted
922 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
924 // Probe for bot from search engine
925 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
926 // Search engine bot detected so let's rewrite many chars for the link
927 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
929 // Output new location link as anchor
930 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
931 } elseif (!headers_sent()) {
932 // Load URL when headers are not sent
933 //* DEBUG: */ debug_report_bug("URL={$URL}");
934 header ("Location: ".str_replace("&", "&", $URL));
936 // Output error message
937 LOAD_INC("inc/header.php");
938 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
939 LOAD_INC("inc/footer.php");
944 // Wrapper for LOAD_URL but URL comes from a configuration entry
945 function LOAD_CONFIGURED_URL ($configEntry) {
947 $URL = getConfig($configEntry);
952 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
960 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
961 global $SEC_CHARS, $URL_CHARS;
962 // Is the code a string?
963 if (!is_string($code)) {
964 // Silently return it
970 // Select smaller set of chars to replace when we e.g. want to compile URLs
971 if (!$full) $ARRAY = $URL_CHARS;
975 // BEFORE 0.2.1 : Language and data constants
976 // WITH 0.2.1+ : Only language constants
977 $code = str_replace('{--','".', str_replace('--}','."', $code));
979 // BEFORE 0.2.1 : Not used
980 // WITH 0.2.1+ : Data constants
981 $code = str_replace('{!','".', str_replace("!}", '."', $code));
984 // Compile QUOT and other non-HTML codes
985 foreach ($ARRAY['to'] as $k => $to) {
986 // Do the reversed thing as in inc/libs/security_functions.php
987 $code = str_replace($to, $ARRAY['from'][$k], $code);
990 // But shall I keep simple quotes for later use?
991 if ($simple) $code = str_replace("'", '{QUOT}', $code);
993 // Find $content[bla][blub] entries
994 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
996 // Are some matches found?
997 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
998 // Replace all matches
999 $matchesFound = array();
1000 foreach ($matches[0] as $key => $match) {
1001 // Fuzzy look has failed by default
1002 $fuzzyFound = false;
1004 // Fuzzy look on match if already found
1005 foreach ($matchesFound as $found => $set) {
1007 $test = substr($found, 0, strlen($match));
1009 // Does this entry exist?
1010 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1011 if ($test == $match) {
1013 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1020 if ($fuzzyFound) continue;
1022 // Take all string elements
1023 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1024 // Replace it in the code
1025 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1026 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1027 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1028 $matchesFound[$key."_".$matches[4][$key]] = 1;
1029 $matchesFound[$match] = 1;
1030 } elseif (!isset($matchesFound[$match])) {
1031 // Not yet replaced!
1032 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1033 $code = str_replace($match, "\".".$match.".\"", $code);
1034 $matchesFound[$match] = 1;
1039 // Return compiled code
1043 /************************************************************************
1045 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1046 * $a_sort sortiert: *
1048 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1049 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1050 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1051 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1052 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1054 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1055 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1056 * Sie, dass es doch nicht so schwer ist! :-) *
1058 ************************************************************************/
1059 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1062 while ($primary_key < count($a_sort)) {
1063 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1064 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1067 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1068 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1069 } elseif ($key != $key2) {
1070 // Sort numbers (E.g.: 9 < 10)
1071 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1072 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1076 // We have found two different values, so let's sort whole array
1077 foreach ($dummy as $sort_key => $sort_val) {
1078 $t = $dummy[$sort_key][$key];
1079 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1080 $dummy[$sort_key][$key2] = $t;
1091 // Write back sorted array
1095 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1096 global $MONTH_DESCR;
1099 if ($type == "yn") {
1100 // This is a yes/no selection only!
1101 if ($id > 0) $prefix .= "[".$id."]";
1102 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1104 // Begin with regular selection box here
1105 if (!empty($prefix)) $prefix .= "_";
1107 if ($id > 0) $type2 .= "[".$id."]";
1108 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1113 for ($idx = 1; $idx < 32; $idx++) {
1114 $OUT .= "<option value=\"".$idx."\"";
1115 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1116 $OUT .= ">".$idx."</option>\n";
1120 case "month": // Month
1121 foreach ($MONTH_DESCR as $month => $descr) {
1122 $OUT .= "<option value=\"".$month."\"";
1123 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1124 $OUT .= ">".$descr."</option>\n";
1128 case "year": // Year
1130 $YEAR = date('Y', time());
1132 // Use configured min age or fixed?
1133 if (GET_EXT_VERSION("other") >= "0.2.1") {
1135 $startYear = $YEAR - getConfig('min_age');
1138 $startYear = $YEAR - 16;
1141 // Calculate earliest year (100 years old people can still enter Internet???)
1142 $minYear = $YEAR - 100;
1144 // Check if the default value is larger than minimum and bigger than actual year
1145 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1146 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1147 $OUT .= "<option value=\"".$idx."\"";
1148 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1149 $OUT .= ">".$idx."</option>\n";
1151 } elseif ($DEFAULT == -1) {
1152 // Current year minus 1
1153 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1155 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1158 // Get current year and subtract the configured minimum age
1159 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1160 // Calculate earliest year depending on extension version
1161 if (GET_EXT_VERSION("other") >= "0.2.1") {
1162 // Use configured minimum age
1163 $YEAR = date('Y', time()) - getConfig('min_age');
1165 // Use fixed 16 years age
1166 $YEAR = date('Y', time()) - 16;
1169 // Construct year selection list
1170 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1171 $OUT .= "<option value=\"".$idx."\"";
1172 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1173 $OUT .= ">".$idx."</option>\n";
1180 for ($idx = 0; $idx < 60; $idx+=5) {
1181 if (strlen($idx) == 1) $idx = "0".$idx;
1182 $OUT .= "<option value=\"".$idx."\"";
1183 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1184 $OUT .= ">".$idx."</option>\n";
1189 for ($idx = 0; $idx < 24; $idx++) {
1190 if (strlen($idx) == 1) $idx = "0".$idx;
1191 $OUT .= "<option value=\"".$idx."\"";
1192 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1193 $OUT .= ">".$idx."</option>\n";
1198 $OUT .= "<option value=\"Y\"";
1199 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1200 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1201 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1202 $OUT .= ">{--NO--}</option>\n";
1205 $OUT .= " </select>\n";
1209 function TRANSLATE_YESNO($yn)
1213 case "Y": $yn = YES; break;
1214 case "N": $yn = NO; break;
1215 default : $yn = "??? (".$yn.")"; break;
1220 // Deprecated : $length
1223 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1224 // Fix missing _MAX constant
1225 if (!defined('_MAX')) define('_MAX', 15235);
1227 // Build server string
1228 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1231 $keys = SITE_KEY.":".DATE_KEY;
1232 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1233 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1234 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1235 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1237 // Build string from misc data
1238 $data = $code.":".$uid.":".$DATA;
1240 // Add more additional data
1241 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1242 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1243 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1244 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1245 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1247 // Calculate number for generating the code
1248 $a = $code + constant('_ADD') - 1;
1250 if (getConfig('master_hash') != null) {
1251 // Generate hash with master salt from modula of number with the prime number and other data
1252 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1254 // Create number from hash
1255 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1257 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1258 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1260 // Create number from hash
1261 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1264 // At least 10 numbers shall be secure enought!
1265 $len = getConfig('code_length');
1266 if ($len == 0) $len = $length;
1267 if ($len == 0) $len = 10;
1269 // Cut off requested counts of number
1270 $return = substr(str_replace('.', "", $rcode), 0, $len);
1272 // Done building code
1275 // Does only allow numbers
1276 function bigintval($num, $castValue = true) {
1277 // Filter all numbers out
1278 $ret = preg_replace("/[^0123456789]/", "", $num);
1281 if ($castValue) $ret = (double)$ret;
1283 // Has the whole value changed?
1284 // @TODO Remove this if() block if all is working fine
1285 if ("".$ret."" != "".$num."") {
1293 // Insert the code in $img_code into jpeg or PNG image
1294 function GENERATE_IMAGE($img_code, $header=true) {
1295 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1296 // Stop execution of function here because of over-sized code length
1298 } elseif (!$header) {
1299 // Return in an HTML code code
1300 return "<IMG src=\"{!URL!}/img.php?code=".$img_code."\">\n";
1304 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1305 if (FILE_READABLE($img)) {
1306 // Switch image type
1307 switch (getConfig('img_type'))
1310 // Okay, load image and hide all errors
1311 $image = @imagecreatefromjpeg($img);
1315 // Okay, load image and hide all errors
1316 $image = @imagecreatefrompng($img);
1320 // Exit function here
1324 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1325 $text_color = imagecolorallocate($image, 0, 0, 0);
1327 // Insert code into image
1328 imagestring($image, 5, 14, 2, $img_code, $text_color);
1330 // Return to browser
1331 header ("Content-Type: image/".getConfig('img_type'));
1333 // Output image with matching image factory
1334 switch (getConfig('img_type')) {
1335 case "jpg": imagejpeg($image); break;
1336 case "png": imagepng($image); break;
1339 // Remove image from memory
1340 imagedestroy($image);
1342 // Create selection box or array of splitted timestamp
1343 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1344 // Calculate 2-seconds timestamp
1345 $stamp = round($timestamp);
1346 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1348 // Do we have a leap year?
1350 $TEST = date('Y', time()) / 4;
1351 $M1 = date("m", time());
1352 $M2 = date("m", (time() + $timestamp));
1354 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1355 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1357 // First of all years...
1358 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1359 //* DEBUG: */ print("Y={$Y}<br />\n");
1361 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1362 //* DEBUG: */ print("M={$M}<br />\n");
1364 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1365 //* DEBUG: */ print("W={$W}<br />\n");
1367 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1368 //* DEBUG: */ print("D={$D}<br />\n");
1370 $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));
1371 //* DEBUG: */ print("h={$h}<br />\n");
1373 $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));
1374 //* DEBUG: */ print("m={$m}<br />\n");
1375 // And at last seconds...
1376 $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));
1377 //* DEBUG: */ print("s={$s}<br />\n");
1379 // Is seconds zero and time is < 60 seconds?
1380 if (($s == 0) && ($timestamp < 60)) {
1382 $s = round($timestamp);
1386 // Now we convert them in seconds...
1388 if ($return_array) {
1389 // Just put all data in an array for later use
1401 $OUT = "<div align=\"".$align."\">\n";
1402 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1405 if (ereg('Y', $display) || (empty($display))) {
1406 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1409 if (ereg("M", $display) || (empty($display))) {
1410 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1413 if (ereg("W", $display) || (empty($display))) {
1414 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1417 if (ereg("D", $display) || (empty($display))) {
1418 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1421 if (ereg("h", $display) || (empty($display))) {
1422 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1425 if (ereg("m", $display) || (empty($display))) {
1426 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1429 if (ereg("s", $display) || (empty($display))) {
1430 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1436 if (ereg('Y', $display) || (empty($display))) {
1437 // Generate year selection
1438 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1439 for ($idx = 0; $idx <= 10; $idx++) {
1440 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1441 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1442 $OUT .= ">".$idx."</option>\n";
1444 $OUT .= " </select></td>\n";
1446 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1449 if (ereg("M", $display) || (empty($display))) {
1450 // Generate month selection
1451 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1452 for ($idx = 0; $idx <= 11; $idx++)
1454 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1455 if ($idx == $M) $OUT .= " selected=\"selected\"";
1456 $OUT .= ">".$idx."</option>\n";
1458 $OUT .= " </select></td>\n";
1460 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1463 if (ereg("W", $display) || (empty($display))) {
1464 // Generate week selection
1465 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1466 for ($idx = 0; $idx <= 4; $idx++) {
1467 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1468 if ($idx == $W) $OUT .= " selected=\"selected\"";
1469 $OUT .= ">".$idx."</option>\n";
1471 $OUT .= " </select></td>\n";
1473 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1476 if (ereg("D", $display) || (empty($display))) {
1477 // Generate day selection
1478 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1479 for ($idx = 0; $idx <= 31; $idx++) {
1480 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1481 if ($idx == $D) $OUT .= " selected=\"selected\"";
1482 $OUT .= ">".$idx."</option>\n";
1484 $OUT .= " </select></td>\n";
1486 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1489 if (ereg("h", $display) || (empty($display))) {
1490 // Generate hour selection
1491 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1492 for ($idx = 0; $idx <= 23; $idx++) {
1493 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1494 if ($idx == $h) $OUT .= " selected=\"selected\"";
1495 $OUT .= ">".$idx."</option>\n";
1497 $OUT .= " </select></td>\n";
1499 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1502 if (ereg("m", $display) || (empty($display))) {
1503 // Generate minute selection
1504 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1505 for ($idx = 0; $idx <= 59; $idx++) {
1506 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1507 if ($idx == $m) $OUT .= " selected=\"selected\"";
1508 $OUT .= ">".$idx."</option>\n";
1510 $OUT .= " </select></td>\n";
1512 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1515 if (ereg("s", $display) || (empty($display))) {
1516 // Generate second selection
1517 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1518 for ($idx = 0; $idx <= 59; $idx++) {
1519 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1520 if ($idx == $s) $OUT .= " selected=\"selected\"";
1521 $OUT .= ">".$idx."</option>\n";
1523 $OUT .= " </select></td>\n";
1525 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1528 $OUT .= "</table>\n";
1530 // Return generated HTML code
1535 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1536 // Initial return value
1539 // Do we have a leap year?
1541 $TEST = date('Y', time()) / 4;
1542 $M1 = date("m", time());
1543 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1544 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1545 // First add years...
1546 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1548 $ret += $POST[$prefix."_mo"] * 2628000;
1550 $ret += $POST[$prefix."_we"] * 604800;
1552 $ret += $POST[$prefix."_da"] * 86400;
1554 $ret += $POST[$prefix."_ho"] * 3600;
1556 $ret += $POST[$prefix."_mi"] * 60;
1557 // And at last seconds...
1558 $ret += $POST[$prefix."_se"];
1559 // Return calculated value
1563 // Sends out mail to all administrators
1564 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1565 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1566 // Trim template name
1567 $template = trim($template);
1569 // Load email template
1570 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1572 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1573 // Older version detected!
1574 return SEND_ADMIN_EMAILS($subj, $msg);
1577 // Check which admin shall receive this mail
1578 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1579 array($template), __FILE__, __LINE__);
1580 if (SQL_NUMROWS($result) == 0) {
1581 // Create new entry (to all admins)
1582 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1583 array($template), __FILE__, __LINE__);
1585 // Load admin IDs...
1587 while (list($aid) = SQL_FETCHROW($result)) {
1592 SQL_FREERESULT($result);
1597 // "implode" IDs and query string
1598 $aid = implode(",", $aids);
1600 if (EXT_IS_ACTIVE("events")) {
1601 // Add line to user events
1602 USERLOG_ADD_LINE($subj, $msg, $UID);
1604 // Log error for debug
1605 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1611 } elseif ($aid == "0") {
1612 // Select all email adresses
1613 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`", __FILE__, __LINE__);
1615 // If Admin-ID is not "to-all" select
1616 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`", array($aid), __FILE__, __LINE__);
1620 // Load email addresses and send away
1621 while (list($email) = SQL_FETCHROW($result)) {
1622 SEND_EMAIL($email, $subj, $msg);
1626 SQL_FREERESULT($result);
1629 function CREATE_FANCY_TIME ($stamp) {
1630 // Get data array with years/months/weeks/days/...
1631 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1633 foreach($data as $k => $v) {
1635 // Value is greater than 0 "eval" data to return string
1636 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1642 // Do we have something there?
1643 if (strlen($ret) > 0) {
1644 // Remove leading commata and space
1645 $ret = substr($ret, 2);
1648 $ret = "0 "._SECONDS;
1651 // Return fancy time string
1655 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1656 $SEP = ""; $TOP = "";
1659 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1663 for ($page = 1; $page <= $PAGES; $page++) {
1664 // Is the page currently selected or shall we generate a link to it?
1665 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1666 // Is currently selected, so only highlight it
1667 $NAV .= "<strong>-";
1669 // Open anchor tag and add base URL
1670 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1672 // Add userid when we shall show all mails from a single member
1673 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1675 // Close open anchor tag
1679 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1680 // Is currently selected, so only highlight it
1681 $NAV .= "-</strong>";
1687 // Add seperator if we have not yet reached total pages
1688 if ($page < $PAGES) $NAV .= " | ";
1691 // Define constants only once
1692 if (!defined('__NAV_OUTPUT')) {
1693 define('__NAV_OUTPUT' , $NAV);
1694 define('__NAV_COLSPAN', $colspan);
1695 define('__NAV_TOP' , $TOP);
1696 define('__NAV_SEP' , $SEP);
1699 // Load navigation template
1700 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1703 // Return generated HTML-Code
1711 // Extract host from script name
1712 function EXTRACT_HOST (&$script) {
1713 // Use default SERVER_URL by default... ;) So?
1716 // Is this URL valid?
1717 if (substr($script, 0, 7) == "http://") {
1718 // Use the hostname from script URL as new hostname
1719 $url = substr($script, 7);
1720 $extract = explode("/", $url);
1722 // Done extracting the URL :)
1725 // Extract host name
1726 $host = str_replace("http://", "", $url);
1727 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1729 // Generate relative URL
1730 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1731 if (substr(strtolower($script), 0, 7) == "http://") {
1732 // But only if http:// is in front!
1733 $script = substr($script, (strlen($url) + 7));
1734 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1736 $script = substr($script, (strlen($url) + 8));
1739 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1740 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1746 // Send a GET request
1747 function GET_URL ($script) {
1748 // Compile the script name
1749 $script = COMPILE_CODE($script);
1751 // Extract host name from script
1752 $host = EXTRACT_HOST($script);
1754 // Generate GET request header
1755 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1756 $request .= "Host: " . $host . "\r\n";
1757 $request .= "Referer: " . URL . "/admin.php\r\n";
1758 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1759 $request .= "Content-Type: text/plain\r\n";
1760 $request .= "Cache-Control: no-cache\r\n";
1761 $request .= "Connection: Close\r\n\r\n";
1763 // Send the raw request
1764 $response = SEND_RAW_REQUEST($host, $request);
1766 // Return the result to the caller function
1770 // Send a POST request
1771 function POST_URL ($script, $postData) {
1772 // Is postData an array?
1773 if (!is_array($postData)) {
1775 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1776 return array("", "", "");
1779 // Compile the script name
1780 $script = COMPILE_CODE($script);
1782 // Extract host name from script
1783 $host = EXTRACT_HOST($script);
1785 // Construct request
1786 $data = http_build_query($postData, '','&');
1788 // Generate POST request header
1789 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1790 $request .= "Host: " . $host . "\r\n";
1791 $request .= "Referer: " . URL . "/admin.php\r\n";
1792 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1793 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1794 $request .= "Content-length: " . strlen($data) . "\r\n";
1795 $request .= "Cache-Control: no-cache\r\n";
1796 $request .= "Connection: Close\r\n\r\n";
1799 // Send the raw request
1800 $response = SEND_RAW_REQUEST($host, $request);
1802 // Return the result to the caller function
1806 // Sends a raw request to another host
1807 function SEND_RAW_REQUEST ($host, $request) {
1809 $response = array("", "", "");
1811 // Default is not to use proxy
1814 // Are proxy settins set?
1815 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1821 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1823 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1825 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1829 if (!is_resource($fp)) {
1836 // Generate CONNECT request header
1837 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1838 $proxyTunnel .= "Host: ".$host."\r\n";
1840 // Use login data to proxy? (username at least!)
1841 if (getConfig('proxy_username') != "") {
1843 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1844 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1847 // Add last new-line
1848 $proxyTunnel .= "\r\n";
1849 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1852 fputs($fp, $proxyTunnel);
1856 // No response received
1860 // Read the first line
1861 $resp = trim(fgets($fp, 10240));
1862 $respArray = explode(" ", $resp);
1863 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1864 // Invalid response!
1870 fputs($fp, $request);
1874 $response[] = trim(fgets($fp, 1024));
1880 // Skip first empty lines
1882 foreach ($resp as $idx => $line) {
1884 $line = trim($line);
1886 // Is this line empty?
1889 array_shift($response);
1891 // Abort on first non-empty line
1896 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1898 // Proxy agent found?
1899 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1900 // Proxy header detected, so remove two lines
1901 array_shift($response);
1902 array_shift($response);
1905 // Was the request successfull?
1906 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1907 // Not found / access forbidden
1908 $response = array("", "", "");
1914 // Taken from www.php.net eregi() user comments
1915 function VALIDATE_EMAIL($email) {
1917 $email = COMPILE_CODE($email);
1919 // Check first part of email address
1920 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1923 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1926 $regex = "^".$first."@".$domain."$";
1928 // Return check result
1929 return eregi($regex, $email);
1931 // Function taken from user comments on www.php.net / function eregi()
1932 function VALIDATE_URL ($URL, $compile=true) {
1933 // Trim URL a little
1934 $URL = trim(urldecode($URL));
1935 //* DEBUG: */ echo $URL."<br />";
1937 // Compile some chars out...
1938 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1939 //* DEBUG: */ echo $URL."<br />";
1941 // Check for the extension filter
1942 if (EXT_IS_ACTIVE("filter")) {
1943 // Use the extension's filter set
1944 return FILTER_VALIDATE_URL($URL, false);
1947 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1948 // https:// in front of the URLs
1949 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1952 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1953 // Define all main targets
1954 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1956 // Begin of navigation links
1957 $eval = "\$OUT = \"[ ";
1959 foreach ($TARGETS as $tar) {
1960 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1961 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1962 if (($tar == "lock_user") && ($status == "LOCKED")) {
1963 // Locked accounts shall be unlocked
1964 $eval .= "UNLOCK_USER";
1966 // All other status is fine
1967 $eval .= strtoupper($tar);
1969 $eval .= "_TITLE--}\\\">{--ADMIN_";
1970 if (($tar == "lock_user") && ($status == "LOCKED")) {
1971 // Locked accounts shall be unlocked
1972 $eval .= "UNLOCK_USER";
1974 // All other status is fine
1975 $eval .= strtoupper($tar);
1977 $eval .= "--}</a></span> | ";
1980 // Finish navigation link
1981 $eval = substr($eval, 0, -7)."]\";";
1987 // Function for backward-compatiblity
1988 function ADD_CATEGORY_table ($MODE, $return=false) {
1989 // Load it from the register extension
1990 return REGISTER_ADD_CATEGORY_table ($MODE, $return);
1992 // Generate an email link
1993 function CREATE_EMAIL_LINK ($email, $table = "admins") {
1994 // Default email link (INSECURE! Spammer can read this by harvester programs)
1995 $EMAIL = "mailto:".$email;
1997 // Check for several extensions
1998 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1999 // Create email link for contacting admin in guest area
2000 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2001 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2002 // Create email link for contacting a member within admin area (or later in other areas, too?)
2003 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2004 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2005 // Create email link to contact sponsor within admin area (or like the link above?)
2006 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2009 // Shall I close the link when there is no admin?
2010 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2012 // Return email link
2015 // Generate a hash for extra-security for all passwords
2016 function generateHash ($plainText, $salt = "") {
2019 // Is the required extension "sql_patches" there and a salt is not given?
2020 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2021 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2022 return md5($plainText);
2025 // Do we miss an arry element here?
2026 if (!isConfigEntrySet('file_hash')) {
2028 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2031 // When the salt is empty build a new one, else use the first x configured characters as the salt
2033 // Build server string
2034 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2037 $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');
2040 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2042 // Calculate number for generating the code
2043 $a = time() + constant('_ADD') - 1;
2045 // Generate SHA1 sum from modula of number and the prime number
2046 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2047 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2048 $sha1 = scrambleString($sha1);
2049 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2050 //* DEBUG: */ $sha1b = descrambleString($sha1);
2051 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2053 // Generate the password salt string
2054 $salt = substr($sha1, 0, getConfig('salt_length'));
2055 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2058 $salt = substr($salt, 0, getConfig('salt_length'));
2059 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2063 return $salt.sha1($salt.$plainText);
2066 function scrambleString($str) {
2070 // Final check, in case of failture it will return unscrambled string
2071 if (strlen($str) > 40) {
2072 // The string is to long
2074 } elseif (strlen($str) == 40) {
2076 $scrambleNums = explode(":", getConfig('pass_scramble'));
2078 // Generate new numbers
2079 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2082 // Scramble string here
2083 //* DEBUG: */ echo "***Original=".$str."***<br />";
2084 for ($idx = 0; $idx < strlen($str); $idx++) {
2085 // Get char on scrambled position
2086 $char = substr($str, $scrambleNums[$idx], 1);
2088 // Add it to final output string
2089 $scrambled .= $char;
2092 // Return scrambled string
2093 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2097 function descrambleString($str) {
2098 // Scramble only 40 chars long strings
2099 if (strlen($str) != 40) return $str;
2101 // Load numbers from config
2102 $scrambleNums = explode(":", getConfig('pass_scramble'));
2105 if (count($scrambleNums) != 40) return $str;
2107 // Begin descrambling
2108 $orig = str_repeat(" ", 40);
2109 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2110 for ($idx = 0; $idx < 40; $idx++) {
2111 $char = substr($str, $idx, 1);
2112 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2115 // Return scrambled string
2116 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2120 function genScrambleString ($len) {
2121 // Prepare array for the numbers
2122 $scrambleNumbers = array();
2124 // First we need to setup randomized numbers from 0 to 31
2125 for ($idx = 0; $idx < $len; $idx++) {
2127 $rand = mt_rand(0, ($len -1));
2129 // Check for it by creating more numbers
2130 while (array_key_exists($rand, $scrambleNumbers)) {
2131 $rand = mt_rand(0, ($len -1));
2135 $scrambleNumbers[$rand] = $rand;
2138 // So let's create the string for storing it in database
2139 $scrambleString = implode(":", $scrambleNumbers);
2140 return $scrambleString;
2143 // Append data like session ID or referal ID to the given URL which would
2144 // normally be stored in cookies
2145 function ADD_URL_DATA ($URL) {
2149 // Determine URL binder
2151 if (strpos($URL, "?") !== false) $BIND = "&";
2153 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2154 // Cookies are not accepted
2155 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2156 // Cookie found in URL
2157 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2158 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2159 // Not found! So let's set default here
2160 $ADD .= $BIND."refid=".getConfig('def_refid');
2164 // Add all together and return it
2168 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2169 function generatePassString ($passHash) {
2170 // Return vanilla password hash
2173 // Is a secret key and master salt already initialized?
2174 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2175 // Only calculate when the secret key is generated
2176 $newHash = ""; $start = 9;
2177 for ($idx = 0; $idx < 10; $idx++) {
2178 $part1 = hexdec(substr($passHash, $start, 4));
2179 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2180 $mod = dechex($idx);
2181 if ($part1 > $part2) {
2182 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2183 } elseif ($part2 > $part1) {
2184 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2186 $mod = substr(round($mod), 0, 4);
2187 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2188 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2193 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2194 $ret = generateHash($newHash, getConfig('master_salt'));
2195 //* DEBUG: */ print($ret."<br />\n");
2198 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2199 $ret = md5($passHash);
2200 //* DEBUG: */ echo "++".$ret."++<br />\n";
2207 // Fix "deleted" cookies
2208 function FIX_DELETED_COOKIES ($cookies) {
2209 // Is this an array with entries?
2210 if ((is_array($cookies)) && (count($cookies) > 0)) {
2211 // Then check all cookies if they are marked as deleted!
2212 foreach ($cookies as $cookieName) {
2213 // Is the cookie set to "deleted"?
2214 if (get_session($cookieName) == "deleted") {
2215 set_session($cookieName, "");
2221 // Output error messages in a fasioned way and die...
2222 function mxchange_die ($msg) {
2224 LOAD_INC_ONCE("inc/header.php");
2226 // Load the message template
2227 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2230 LOAD_INC_ONCE("inc/footer.php");
2236 // Display parsing time and number of SQL queries in footer
2237 function DISPLAY_PARSING_TIME_FOOTER() {
2238 // Is the timer started?
2239 if (!isset($GLOBALS['startTime'])) {
2245 $endTime = microtime(true);
2247 // "Explode" both times
2248 $start = explode(" ", $GLOBALS['startTime']);
2249 $end = explode(" ", $endTime);
2250 $runTime = $end[0] - $start[0];
2251 if ($runTime < 0) $runTime = 0;
2252 $runTime = TRANSLATE_COMMA($runTime);
2256 'runtime' => $runTime,
2257 'numSQLs' => (getConfig('sql_count') + 1),
2258 'numTemplates' => (getConfig('num_templates') + 1)
2261 // Load the template
2262 LOAD_TEMPLATE("show_timings", false, $content);
2265 // Unset/set session variables
2266 function set_session ($var, $value) {
2269 // Abort in CSS mode here
2270 if ($CSS == 1) return true;
2272 // Trim value and session variable
2273 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2275 // Is the session variable set?
2276 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2277 // Remove the session
2278 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2279 unset($_SESSION[$var]);
2280 return session_unregister($var);
2281 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2283 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2284 $_SESSION[$var] = $value;
2285 return session_register($var);
2286 } elseif (!empty($value)) {
2288 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2289 $_SESSION[$var] = $value;
2293 // Ignored (but valid)
2294 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2298 // Check wether a boolean constant is set
2299 // Taken from user comments in PHP documentation for function constant()
2300 function isBooleanConstantAndTrue($constName) { // : Boolean
2303 // Failed by default
2307 if (isset($cacheArray['const'][$constName])) {
2309 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2310 $res = $cacheArray['const'][$constName];
2313 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2314 if (defined($constName)) $res = (constant($constName) === true);
2317 $cacheArray['const'][$constName] = $res;
2319 //* DEBUG: */ var_dump($res);
2325 // Check wether a session variable is set
2326 function isSessionVariableSet ($var) {
2327 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2328 return (isset($_SESSION[$var]));
2330 // Returns wether the value of the session variable or NULL if not set
2331 function get_session ($var) {
2334 // Default is not found! ;-)
2337 // Is the variable there or cached values?
2338 if (isset($cacheArray['session'][$var])) {
2339 // Get cached value (skips a lot SQL_ESCAPE() calles!
2340 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2341 $value = $cacheArray['session'][$var];
2342 } elseif (isSessionVariableSet($var)) {
2343 // Then get it secured!
2344 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2345 $value = SQL_ESCAPE($_SESSION[$var]);
2348 $cacheArray['session'][$var] = $value;
2355 // Send notification to admin
2356 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2357 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2359 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2361 // Send outdated way
2362 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2363 SEND_ADMIN_EMAILS($subject, $msg);
2367 // Destroy user session
2368 function destroy_user_session () {
2370 $GLOBALS['userid'] = 0;
2372 // Remove all user data from session
2373 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2376 // Merges an array together but only if both are arrays
2377 function merge_array ($array1, $array2) {
2378 // Are both an array?
2379 if ((is_array($array1)) && (is_array($array2))) {
2380 // Merge all together
2381 return array_merge($array1, $array2);
2382 } elseif (is_array($array1)) {
2383 // Return left array
2384 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
2386 } elseif (is_array($array2)) {
2387 // Return right array
2388 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
2392 // Both are not arrays
2393 debug_report_bug(__FUNCTION__.":");
2396 // Debug message logger
2397 function DEBUG_LOG ($file, $line, $message, $force=true) {
2398 // Is debug mode enabled?
2399 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2400 // Log this message away
2401 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2402 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2407 // Reads a directory with PHP files in and gets only files back
2408 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2412 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2415 while ($baseFile = readdir($dirPointer)) {
2416 // Load file only if extension is active
2418 $file = $baseDir.$baseFile;
2420 // Is this a valid reset file?
2421 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2422 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2423 // Remove both for extension name
2424 $extName = substr($baseFile, strlen($prefix), -4);
2427 $extId = GET_EXT_ID($extName);
2429 // Is the extension valid and active?
2430 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2431 // Then add this file
2433 } elseif ($extId == 0) {
2434 // Add non-extension files as well
2441 closedir($dirPointer);
2446 // Return array with include files
2449 // Load more reset scripts
2450 function RESET_ADD_INCLUDES () {
2451 // Is the reset set or old sql_patches?
2452 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2457 // Get more daily reset scripts
2458 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2461 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2463 // Create current week mark
2464 $currWeek = date("W", time());
2467 if (getConfig('last_week') != $currWeek) {
2468 // Include weekly reset scripts
2469 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2472 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2475 // Create current month mark
2476 $currMonth = date("m", time());
2479 if (getConfig('last_month') != $currMonth) {
2480 // Include monthly reset scripts
2481 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2484 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2490 // Handle extra values
2491 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2492 // Default is the value itself
2495 // Do we have a special filter function?
2496 if (!empty($filterFunction)) {
2497 // Does the filter function exist?
2498 if (function_exists($filterFunction)) {
2499 // Do we have extra parameters here?
2500 if (!empty($extraValue)) {
2501 // Put both parameters in one new array by default
2502 $args = array($value, $extraValue);
2504 // If we have an array simply use it and pre-extend it with our value
2505 if (is_array($extraValue)) {
2506 // Make the new args array
2507 $args = merge_array(array($value), $extraValue);
2510 // Call the multi-parameter call-back
2511 $ret = call_user_func_array($filterFunction, $args);
2513 // One parameter call
2514 $ret = call_user_func($filterFunction, $value);
2522 // Check if given FQFN is a readable file
2523 function FILE_READABLE($fqfn) {
2525 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2527 // Converts timestamp selections into a timestamp
2528 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2529 // Init test variable
2532 // Get last three chars
2533 $test = substr($id, -3);
2535 // Improved way of checking! :-)
2536 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2537 // Found a multi-selection for timings?
2538 $test = substr($id, 0, -3);
2539 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)) {
2540 // Generate timestamp
2541 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2542 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2544 // Remove data from array
2545 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2546 unset($POST[$test."_".$rem]);
2550 unset($id); $skip = true; $test2 = $test;
2553 // Process this entry
2554 $skip = false; $test2 = "";
2557 // Reverts the german decimal comma into Computer decimal dot
2558 function REVERT_COMMA ($str) {
2559 // Default float is not a float... ;-)
2562 // Which language is selected?
2563 switch (GET_LANGUAGE()) {
2564 case "de": // German language
2565 // Remove german thousand dots first
2566 $str = str_replace(".", "", $str);
2568 // Replace german commata with decimal dot and cast it
2569 $float = (float)str_replace(",", ".", $str);
2572 default: // US and so on
2573 // Remove thousand dots first and cast
2574 $float = (float)str_replace(",", "", $str);
2582 // Handle menu-depending failed logins and return the rendered content
2583 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2584 // Default output is empty ;-)
2587 // Is the session data set?
2588 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2589 // Ignore zero values
2590 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
2591 // Non-guest has login failures found, get both data and prepare it for template
2592 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2594 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
2595 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2599 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
2602 // Reset session data
2603 set_session('mxchange_'.$accessLevel.'_failures', "");
2604 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2607 // Return rendered content
2612 function REBUILD_CACHE ($cache, $inc="") {
2613 global $cacheInstance, $CSS;
2615 // Shall I remove the cache file?
2616 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2618 if ($cacheInstance->loadCacheFile($cache)) {
2620 $cacheInstance->destroyCacheFile();
2623 // Include file given?
2626 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
2628 // Is the include there?
2629 if (FILE_READABLE($INC)) {
2630 // And rebuild it from scratch
2631 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2634 // Include not found!
2635 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2641 // Purge admin menu cache
2642 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2643 global $cacheInstance;
2645 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2646 if (!EXT_IS_ACTIVE("cache")) {
2647 // Cache extension not active
2649 } elseif (!is_object($cacheInstance)) {
2650 // No cache instance!
2651 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2653 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
2654 // Caching disabled (currently experiemental!)
2658 // Experiemental feature!
2659 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2662 // Translates the "pool type" into human-readable
2663 function TRANSLATE_POOL_TYPE ($type) {
2664 // Default type is unknown
2665 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
2667 // Generate constant
2668 $constName = sprintf("POOL_TYPE_%s", $type);
2671 if (defined($constName)) {
2673 $translated = constant($constName);
2676 // Return "translation"
2680 // "Getter" for remote IP number
2681 function GET_REMOTE_ADDR () {
2682 // Get remote ip from environment
2683 $remoteAddr = getenv('REMOTE_ADDR');
2685 // Is removeip installed?
2686 if (EXT_IS_ACTIVE("removeip")) {
2687 // Then anonymize it
2688 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2694 // "Getter" for remote hostname
2695 function GET_REMOTE_HOST () {
2696 // Get remote ip from environment
2697 $remoteHost = getenv('REMOTE_HOST');
2699 // Is removeip installed?
2700 if (EXT_IS_ACTIVE("removeip")) {
2701 // Then anonymize it
2702 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2708 // "Getter" for user agent
2709 function GET_USER_AGENT () {
2710 // Get remote ip from environment
2711 $userAgent = getenv('HTTP_USER_AGENT');
2713 // Is removeip installed?
2714 if (EXT_IS_ACTIVE("removeip")) {
2715 // Then anonymize it
2716 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2722 // "Getter" for referer
2723 function GET_REFERER () {
2724 // Get remote ip from environment
2725 $referer = getenv('HTTP_REFERER');
2727 // Is removeip installed?
2728 if (EXT_IS_ACTIVE("removeip")) {
2729 // Then anonymize it
2730 $referer = GET_ANONYMOUS_REFERER($referer);
2737 // Adds a bonus mail to the queue
2738 // This is a high-level function!
2739 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2740 // Use mode from data if not set and availble ;-)
2741 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2743 // Generate receiver list
2744 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2747 if (!empty($RECEIVER)) {
2748 // Add bonus mail to queue
2749 ADD_BONUS_MAIL_TO_QUEUE(
2761 // Mail inserted into bonus pool
2762 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
2763 } elseif ($output) {
2764 // More entered than can be reached!
2765 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
2768 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2772 // Determines referal id and sets it
2773 function DETERMINE_REFID () {
2774 global $CLICK, $_SERVER;
2776 // Check if refid is set
2777 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2778 // The variable user comes from the click-counter script click.php and we only accept this here
2779 $GLOBALS['refid'] = bigintval($_GET['user']);
2780 } elseif (!empty($_POST['refid'])) {
2781 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2782 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2783 } elseif (!empty($_GET['refid'])) {
2784 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2785 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2786 } elseif (!empty($_GET['ref'])) {
2787 // Set refid=ref (the referal link uses such variable)
2788 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2789 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2790 // Set session refid als global
2791 $GLOBALS['refid'] = bigintval(get_session('refid'));
2792 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2793 // Set default refid as refid in URL
2794 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2795 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2796 // Select a random user which has confirmed enougth mails
2797 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2799 // No default ID when sql_patches is not installed or none set
2800 $GLOBALS['refid'] = 0;
2803 // Set cookie when default refid > 0
2804 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2806 set_session('refid', $GLOBALS['refid']);
2809 // Return determined refid
2810 return $GLOBALS['refid'];
2813 // Destroys the admin session
2814 function destroyAdminSession ($destroy = true) {
2815 // Kill maybe existing session variables including array elements
2816 set_session('admin_login', "");
2817 set_session('admin_md5' , "");
2818 set_session('admin_last' , "");
2819 set_session('admin_to' , "");
2821 // Destroy session and return status
2823 return session_destroy();
2826 // All fine if we shall not really destroy the session
2830 // Checks if a given apache module is loaded
2831 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2832 // Check it and return result
2833 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2836 // Getter for $_CONFIG entries
2837 function getConfig ($entry) {
2843 // Is the entry there?
2844 if (isConfigEntrySet($entry)) {
2846 $value = $_CONFIG[$entry];
2853 // Setter for $_CONFIG entries
2854 function setConfigEntry ($entry, $value) {
2857 // Secure the entry name
2858 $entry = SQL_ESCAPE($entry);
2861 $_CONFIG[$entry] = $value;
2864 // Checks wether the given config entry is set
2865 function isConfigEntrySet ($entry) {
2867 return (isset($_CONFIG[$entry]));
2870 // Increment or init with given value or 1 as default the given config entry
2871 function incrementConfigEntry ($configEntry, $value=1) {
2874 // Increment it if set or init it with 1
2875 if (getConfig($configEntry) > 0) {
2876 $_CONFIG[$configEntry] += $value;
2878 $_CONFIG[$configEntry] = $value;
2882 // "Getter" for language strings
2883 // @TODO Rewrite all language constants to this function.
2884 function getMessage ($messageId) {
2885 // Default is not found!
2886 $return = "!".$messageId."!";
2888 // Is the language string found?
2889 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2890 // Language array element found in small_letters
2891 $return = $GLOBALS['msg'][$messageId];
2892 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2893 // @DEPRECATED Language array element found in BIG_LETTERS
2894 $return = $GLOBALS['msg'][$messageId];
2895 } elseif (defined($messageId)) {
2896 // @DEPRECATED Deprecated constant found
2897 $return = constant($messageId);
2899 // Missing language constant
2900 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2903 // Return the string
2907 // Get current theme name
2908 function GET_CURR_THEME() {
2909 global $INC_POOL, $CSS, $cacheArray;
2911 // The default theme is 'default'... ;-)
2914 // Load default theme if not empty from configuration
2915 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2917 if (!isSessionVariableSet('mxchange_theme')) {
2918 // Set default theme
2919 set_session('mxchange_theme', $ret);
2920 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2921 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2922 // Get theme from cookie
2923 $ret = get_session('mxchange_theme');
2926 if (THEME_GET_ID($ret) == 0) {
2927 // Fix it to default
2930 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2931 // Prepare FQFN for checking
2932 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_GET['theme']));
2934 // Installation mode active
2935 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2936 // Set cookie from URL data
2937 set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
2938 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_POST['theme'])))) {
2939 // Set cookie from posted data
2940 set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
2944 $ret = get_session('mxchange_theme');
2946 // Invalid design, reset cookie
2947 set_session('mxchange_theme', $ret);
2950 // Add (maybe) found theme.php file to inclusion list
2951 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
2953 // Try to load the requested include file
2954 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2956 // Return theme value
2960 // Get id from theme
2961 function THEME_GET_ID ($name) {
2964 // Is the extension "theme" installed?
2965 if (!EXT_IS_ACTIVE("theme")) {
2973 // Is the cache entry there?
2974 if (isset($cacheArray['themes']['id'][$name])) {
2975 // Get the version from cache
2976 $id = $cacheArray['themes']['id'][$name];
2979 incrementConfigEntry('cache_hits');
2980 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2981 // Check if current theme is already imported or not
2982 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2983 array($name), __FILE__, __LINE__);
2986 if (SQL_NUMROWS($result) == 1) {
2988 list($id) = SQL_FETCHROW($result);
2992 SQL_FREERESULT($result);
2999 // Read a given file
3000 function READ_FILE ($FQFN, $sqlPrepare = false) {
3002 if (function_exists('file_get_contents')) {
3004 $content = file_get_contents($FQFN);
3006 // Fall-back to implode-file chain
3007 $content = implode("", file($FQFN));
3010 // Prepare SQL queries?
3011 if ($sqlPrepare === true) {
3012 // Remove some unwanted chars
3013 $content = str_replace("\r", "", $content);
3014 $content = str_replace("\n\n", "\n", $content);
3017 // Return the content
3021 // Writes content to a file
3022 function WRITE_FILE ($FQFN, $content) {
3023 // Is the function there?
3024 if (function_exists('file_put_contents')) {
3025 // Write it directly
3026 file_put_contents($FQFN, $content);
3028 // Write it with fopen
3029 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
3030 fwrite($fp, $content);
3038 // Generates an error code from given account status
3039 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3040 // Default error code if unknown account status
3041 $ERROR = constant('CODE_UNKNOWN_STATUS');
3043 // Generate constant name
3044 $constantName = sprintf("CODE_ID_%s", $status);
3046 // Is the constant there?
3047 if (defined($constantName)) {
3049 $ERROR = constant($constantName);
3052 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3055 // Return error code
3059 // Clears the output buffer. This function does *NOT* backup sent content.
3060 function clearOutputBuffer () {
3061 // Trigger an error on failure
3062 if (!ob_end_clean()) {
3064 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
3068 // "Getter" for revision/version data
3069 function getActualVersion ($type = 0) {
3070 // By default nothing is new... ;-)
3073 // FQFN of revision file
3074 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
3076 // Check for revision file
3077 if (!FILE_READABLE($FQFN)) {
3078 // Not found, so we need to create it
3081 // Revision file found
3082 $ins_vers = explode("\n", READ_FILE($FQFN));
3084 // Is the content valid?
3085 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
3086 // File needs update!
3089 // Revision-File has valid Data and isn't 'new' so return the Rev-Number
3090 return trim($ins_vers[$type]);
3094 // Has it been updated?
3095 if ($new === true) {
3096 // No Revision-File or has no valid Data so read the Revision from the Server.
3097 $version = GET_URL("check-updates3.php");
3100 $akt_vers[] = trim($version[10]);
3101 $akt_vers[] = trim($version[9]);
3102 $akt_vers[] = trim($version[8]);
3105 WRITE_FILE($FQFN, implode("\n", $akt_vers));
3107 // Return requested content
3108 return trim($akt_vers[$type]);
3112 // Loads an include file and logs any missing files for debug purposes
3113 function LOAD_INC ($INC) {
3114 // Get constant path
3115 $PATH = constant('PATH');
3117 // Use the include file name directly
3118 // @TODO Try to find all locations where an FQFN is given to these two
3119 // @TODO functions and avoid it.
3122 // Check if PATH is in $INC
3123 if (substr($INC, 0, $PATH) != $PATH) {
3124 // Add it. This is why we need a trailing slash in config.php
3125 $FQFN = $PATH . $INC;
3128 // Is the include file there?
3129 if (!FILE_READABLE($FQFN)) {
3130 // Not there so log it
3131 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Include file %s not found.", basename($INC)));
3139 // Loads an include file once
3140 function LOAD_INC_ONCE ($INC) {
3143 // Is it not loaded?
3144 if (!isset($cacheArray['load_once'][$INC])) {
3145 // Then try to load it
3148 // And mark it as loaded
3149 $cacheArray['load_once'][$INC] = true;
3153 // Back-ported from the new ship-simu engine. :-)
3154 function debug_get_printable_backtrace () {
3156 $backtrace = "<ol>\n";
3158 // Get and prepare backtrace for output
3159 $backtraceArray = debug_backtrace();
3160 foreach ($backtraceArray as $key => $trace) {
3161 if (!isset($trace['file'])) $trace['file'] = __FILE__;
3162 if (!isset($trace['line'])) $trace['line'] = __LINE__;
3163 if (!isset($trace['args'])) $trace['args'] = array();
3164 $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";
3168 $backtrace .= "</ol>\n";
3170 // Return the backtrace
3174 // Output a debug backtrace to the user
3175 function debug_report_bug ($message = "") {
3178 // Is the optional message set?
3179 if (!empty($message)) {
3181 $debug = sprintf("Note: %s<br />\n",
3185 // @TODO Add a little more infos here
3186 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
3190 $debug .= ("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
3191 $debug .= (debug_get_printable_backtrace());
3192 $debug .= ("</pre>Thank you for your help finding bugs.");
3198 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
3199 function generateSeed () {
3200 list($usec, $sec) = explode(" ", microtime());
3201 return ((float)$sec + (float)$usec);
3204 // Converts a message code to a human-readable message
3205 function convertCodeToMessage ($code) {
3208 case constant('CODE_LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
3209 case constant('CODE_LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
3210 case constant('CODE_DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
3211 case constant('CODE_POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
3212 case constant('CODE_ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
3213 case constant('CODE_USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
3214 case constant('CODE_STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
3215 case constant('CODE_ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
3217 case constant('CODE_ERROR_MAILID'):
3218 if (EXT_IS_ACTIVE($ext, true)) {
3219 $msg = getMessage('ERROR_CONFIRMING_MAIL');
3221 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
3225 case constant('CODE_EXTENSION_PROBLEM'):
3226 if (isset($_GET['ext'])) {
3227 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), SQL_ESCAPE($_GET['ext']));
3229 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
3233 case constant('CODE_COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
3234 case constant('CODE_BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
3235 case constant('CODE_LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
3236 default : $msg = UNKNOWN_MAILID_CODE_1.$code.UNKNOWN_MAILID_CODE_2; break;
3239 // Return the message
3243 // Checks wether the given extension is currently not installed
3244 // and redirects if so.
3245 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
3246 // Is the extension uninstalled/inactive?
3247 if (!EXT_IS_ACTIVE($ext_name)) {
3248 // Redirect to index
3249 LOAD_URL("modules.php?module=index&msg=".constant('CODE_EXTENSION_PROBLEM')."&ext=".$ext_name);
3253 // Generate a "link" for the given admin id (aid)
3254 function GENERATE_AID_LINK ($aid) {
3255 // No assigned admin is default
3256 $admin = "<div class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</div>";
3258 // Zero? = Not assigned
3260 // Load admin's login
3261 $login = GET_ADMIN_LOGIN($aid);
3262 if ($login != "***") {
3263 // Is the extension there?
3264 if (EXT_IS_ACTIVE("admins")) {
3266 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
3268 // Extension not found
3269 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
3273 $admin = "<div class=\"admin_note\">".ADMIN_ID_404_1.$aid.ADMIN_ID_404_2."</div>";
3281 //////////////////////////////////////////////////
3282 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3283 //////////////////////////////////////////////////
3285 if (!function_exists('html_entity_decode')) {
3286 // Taken from documentation on www.php.net
3287 function html_entity_decode ($string) {
3288 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3289 $trans_tbl = array_flip($trans_tbl);
3290 return strtr($string, $trans_tbl);