Skip to content

Commit

Permalink
MDL-17754, MDL-11061, MDL-9276, MDL-17777, MDL-17787 - various url ha…
Browse files Browse the repository at this point in the history
…ndling improvemetns; rewritten $FULLME and added $ME, $SCRIPT and $FULLSCRIPT; improved slashargument handling especially for IIS; removed legacy slasharguments functions obsoleted since 1.6; some other refactoring; reverse procy support, ssl appliance support
  • Loading branch information
skodak committed Jan 5, 2009
1 parent 9843511 commit 11e7b50
Show file tree
Hide file tree
Showing 28 changed files with 198 additions and 196 deletions.
5 changes: 2 additions & 3 deletions admin/cron.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
/// we do not want HTML in output and there is no real session ;-)
define('CLI_SCRIPT', true);

/// The following is a hack necessary to allow this script to work well
/// from the command line.
define('FULLME', 'cron'); //TODO: to be removed soon ;-)
/// Following hack used to identify cron and other CLI scripts - use CLI_SCRIPT or $FULLME == "/$CFG->admin/cropn.php" instead
//define('FULLME', 'cron');

/// Do not set moodle cookie because we do not need it here, it is better to emulate session
define('NO_MOODLE_COOKIES', true);
Expand Down
4 changes: 2 additions & 2 deletions blocks/tags/block_tags.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function specialization() {

function get_content() {

global $CFG, $SITE, $COURSE, $USER;
global $CFG, $SITE, $COURSE, $USER, $SCRIPT;

if (empty($CFG->usetags)) {
$this->content->text = '';
Expand Down Expand Up @@ -80,7 +80,7 @@ function get_content() {
$loggedin = isloggedin() && !$isguest;
$coursepage = $canedit = false;
$coursepage = (isset($COURSE->id) && $COURSE->id != SITEID);
$mymoodlepage = strpos($_SERVER['PHP_SELF'], 'my') > 0 ? true : false;
$mymoodlepage = ($SCRIPT == '/my/index.php') ? true : false;
$sitepage = (isset($COURSE->id) && $COURSE->id == SITEID && !$mymoodlepage);
$coursecontext = get_context_instance(CONTEXT_COURSE, $COURSE->id);
if ($coursepage) {
Expand Down
2 changes: 1 addition & 1 deletion blog/lib.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ function blog_print_html_formatted_entries($postid, $filtertype, $filterselect,
* display the entry in its abbreviated format (eg. index page)
*/
function blog_print_entry($blogEntry, $viewtype='full', $filtertype='', $filterselect='', $mode='loud') {
global $USER, $CFG, $COURSE, $ME, $DB;
global $USER, $CFG, $COURSE, $DB;

$template['body'] = format_text($blogEntry->summary, $blogEntry->format);
$template['title'] = '<a id=b"'. s($blogEntry->id) .'" />';
Expand Down
10 changes: 10 additions & 0 deletions config-dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@
// web address to where moodle has been installed. If your web site
// is accessible via multiple URLs then choose the most natural one
// that your students would use. Do not include a trailing slash
//
// If you need both intranet and Internet access please read
// http://docs.moodle.org/en/masquerading

$CFG->wwwroot = 'http://example.com/moodle';

Expand Down Expand Up @@ -193,6 +196,13 @@
// $CFG->mailprefix = 'mdl-'; // - is the separator for qmail
// $CFG->maildomain = 'youremaildomain.com';
//
// Enable when setting up advanced reverse proxy load balancing configurations.
// $CFG->reverseproxy = true;
//
// Enable when using external SSL appliance for performance reasons.
// Please note that site may be accessible via https: or https:, but not both!
// $CFG->sslproxy = true;
//
// The following setting will tell Moodle to respect your PHP session
// settings. Use this if you want to control session configuration
// from php.ini, httpd.conf or .htaccess files.
Expand Down
2 changes: 1 addition & 1 deletion course/report/participation/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ function checknos() {
echo '<form action="'.$CFG->wwwroot.'/user/action_redir.php" method="post" id="studentsform" onsubmit="return checksubmit(this);">'."\n";
echo '<div>'."\n";
echo '<input type="hidden" name="id" value="'.$id.'" />'."\n";
echo '<input type="hidden" name="returnto" value="'. format_string($_SERVER['REQUEST_URI']) .'" />'."\n";
echo '<input type="hidden" name="returnto" value="'. s($FULLME) .'" />'."\n";
echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />'."\n";

foreach ($users as $u) {
Expand Down
2 changes: 1 addition & 1 deletion draftfile.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// disable moodle specific debug messages
disable_debugging();

$relativepath = get_file_argument('draftfile.php');
$relativepath = get_file_argument();

// relative path must start with '/'
if (!$relativepath) {
Expand Down
2 changes: 1 addition & 1 deletion file.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
// disable moodle specific debug messages
disable_debugging();

$relativepath = get_file_argument('file.php');
$relativepath = get_file_argument();
$forcedownload = optional_param('forcedownload', 0, PARAM_BOOL);

// relative path must start with '/', because of backup/restore!!!
Expand Down
2 changes: 1 addition & 1 deletion filter/algebra/pix.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

//error_reporting(E_ALL);

$relativepath = get_file_argument('pix.php');
$relativepath = get_file_argument();

$args = explode('/', trim($relativepath, '/'));

Expand Down
2 changes: 1 addition & 1 deletion filter/tex/pix.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

error_reporting(E_ALL);

$relativepath = get_file_argument('pix.php');
$relativepath = get_file_argument();

$args = explode('/', trim($relativepath, '/'));

Expand Down
2 changes: 1 addition & 1 deletion install.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@

/// guess the www root
if ($INSTALL['wwwroot'] == '') {
list($INSTALL['wwwroot'], $xtra) = explode('/install.php', qualified_me());
$INSTALL['wwwroot'] = install_guess_wwwroot();
$INSTALL['wwwrootform'] = $INSTALL['wwwroot'];

// now try to guess the correct dataroot not accessible via web
Expand Down
3 changes: 3 additions & 0 deletions lang/en_utf8/error.php
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@
$string['sessionipnomatch2'] = 'Sorry, but your IP number seems to have changed from when you first logged in. This security feature prevents crackers stealing your identity while logged in to this site. You may see this error if you use wireless networks or if you are roaming between different networks. Please ask the site administrator for more help.<br /><br />If you want to continue please press F5 key to refresh this page.';
$string['socksnotsupported'] = 'SOCKS5 proxy is not supported in PHP4';
$string['spellcheckernotconf'] = 'Spellchecker not configured';
$string['sslonlyaccess'] = 'For security reasons only https connections are allowed, sorry.';
$string['statscatchupmode'] = 'Statistics is currently in catchup mode. So far $a->daysdone day(s) have been processed and $a->dayspending are pending. Check back soon!';
$string['storedfilecannotcreatefiledirs'] = 'Can not create local file pool directories, please verify permissions in dataroot.';
$string['storedfilecannotread'] = 'Can not read file, either file does not exist or there are permission problems';
Expand Down Expand Up @@ -440,6 +441,7 @@
$string['unknowuploadaction'] = 'Error: Unknown upload action ($a)';
$string['unsupportedevent'] = 'Unsupported event type';
$string['unsupportedstate'] = 'Unsupported completion state';
$string['usupportedwebserver'] = 'Web server software ($a) is not suported, sorry.';
$string['upgraderequires19'] = 'Error: New Moodle version was installed on server, unfortunately upgrade from the previous version is not supported.<br />Please upgrade first to latest 1.9.x release. You can also return to previous version by reinstalling original files.';
$string['urlnotdefinerss'] = 'URL not defined for RSS feed';
$string['userautherror'] = 'Unknown auth plugin';
Expand Down Expand Up @@ -473,6 +475,7 @@
$string['wrongroleid'] = 'Incorrect role ID!';
$string['wrongsourcebase'] = 'Wrong source URL base';
$string['wrongzipfilename'] = 'Wrong ZIP file name';
$string['wwwrootmismatch'] = 'Incorrect access detected, this server may be accessed only through \"$a\" address, sorry.<br />Please notify server administrator.';
$string['xmldberror'] = 'XMLDB error!';
$string['youcannotdeletecategory'] = 'You cannot delete category \'$a\' becuase you can neither delete the contents, nor move them elsewhere.';

Expand Down
2 changes: 1 addition & 1 deletion lib/filelib.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function get_file_url($path, $options=null, $type='coursefile') {
$url = $wwwroot."/user/pix.php";
break;
case 'usergroup':
$url = $CFG->wwwroot."/user/pixgroup.php";
$url = $CFG->wwwroot."/user/grouppix.php";
break;
case 'httpscoursefile':
$url = $CFG->httpswwwroot."/file.php";
Expand Down
3 changes: 2 additions & 1 deletion lib/flickrlib.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,11 +229,12 @@ function getFriendlyGeodata($lat, $lon) {

function auth ($perms = "write", $remember_uri = true)
{
global $FULLME;
// Redirects to Flickr's authentication piece if there is no valid token.
// If remember_uri is set to false, the callback script (included) will
// redirect to its default page.
if ($remember_uri) {
$redirect = $_SERVER['REQUEST_URI'];
$redirect = $FULLME;
}
$api_sig = md5($this->secret . "api_key" . $this->api_key . "perms" . $perms);
$url = 'http://www.flickr.com/services/auth/?api_key=' . $this->api_key . "&perms=" . $perms . '&api_sig='. $api_sig;
Expand Down
24 changes: 24 additions & 0 deletions lib/installlib.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@
* Functions to support installation process
*/

/**
*Tries to detect the right www root setting.
*
* @return string detected www root
*/
function install_guess_wwwroot() {
$wwwroot = '';
if (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off') {
$wwwroot .= 'http://';
} else {
$wwwroot .= 'https://';
}
$hostport = explode(':', $_SERVER['HTTP_HOST']);
$wwwroot .= reset($hostport);
if ($_SERVER['SERVER_PORT'] != 80 and $_SERVER['SERVER_PORT'] != '443') {
$wwwroot .= ':'.$_SERVER['SERVER_PORT'];
}
$wwwroot .= $_SERVER['SCRIPT_NAME'];

list($wwwroot, $xtra) = explode('/install.php', $wwwroot);

return $wwwroot;
}

/**
* This function returns a list of languages and their full names. The
* list of available languages is fetched from install/lang/xx/installer.php
Expand Down
4 changes: 3 additions & 1 deletion lib/portfolio/exceptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,16 @@ class portfolio_export_exception extends portfolio_exception {
* @param mixed $a language string data (optional, defaults to null)
*/
public function __construct($exporter, $errorcode, $module=null, $continue=null, $a=null) {
global $SCRIPT, $CFG;

if (!empty($exporter) && $exporter instanceof portfolio_exporter) {
if (empty($continue)) {
$caller = $exporter->get('caller');
if (!empty($caller) && $caller instanceof portfolio_caller_base) {
$continue = $exporter->get('caller')->get_return_url();
}
}
if (!defined('FULLME') || FULLME != 'cron') { // TODO: this is not nice at all
if ($SCRIPT == "/$CFG->admin/cron.php") {
$exporter->process_stage_cleanup();
}
} else {
Expand Down
5 changes: 1 addition & 4 deletions lib/sessionlib.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,6 @@ protected function check_security() {
print_error('sessionipnomatch2', 'error');
}
}

// TODO: add wwwroot check here

}

/**
Expand Down Expand Up @@ -171,7 +168,7 @@ protected function prepare_cookies() {
}
unset($nomoodlecookie); // cleanup

if (!isset($CFG->cookiesecure) or strpos($CFG->wwwroot, 'https://') !== 0) {
if (!isset($CFG->cookiesecure) or (strpos($CFG->wwwroot, 'https://') !== 0 and empty($CFG->sslproxy))) {
$CFG->cookiesecure = 0;
}

Expand Down
16 changes: 9 additions & 7 deletions lib/setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@
*/
global $HTTPSPAGEREQUIRED;

/** Full script path including all params, slash arguments, scheme and host.*/
global $FULLME;
/** Script path including query string and slash arguments without host. */
global $ME;
/** $FULLME without slasharguments and query string.*/
global $FULLSCRIPT;
/** Relative moodle script path "/course/view.php" */
global $SCRIPT;

/// First try to detect some attacks on older buggy PHP versions
if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
Expand Down Expand Up @@ -404,13 +412,7 @@ function stripslashes_deep($value) {
}

/// initialise ME's
if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
$FULLME = FULLME;
$ME = FULLME;
} else {
$FULLME = qualified_me();
$ME = strip_querystring($FULLME);
}
initialise_fullme();

/// start session and prepare global $SESSION, $USER
session_get_instance();
Expand Down
103 changes: 102 additions & 1 deletion lib/setuplib.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,106 @@ function default_exception_handler($ex) {
}
}

/**
* Initialises $FULLME and friends.
* @return void
*/
function initialise_fullme() {
global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;

$url = parse_url($CFG->wwwroot);

if (CLI_SCRIPT) {
// urls do not make much sense in CLI scripts
$backtrace = debug_backtrace();
$topfile = array_pop($backtrace);
$topfile = realpath($topfile['file']);
$dirroot = realpath($CFG->dirroot);

if (strpos($topfile, $dirroot) !== 0) {
$SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
} else {
$relme = substr($topfile, strlen($dirroot));
$relme = str_replace('\\', '/', $relme); // Win fix
$SCRIPT = $FULLSCRIPT = $FULLME = $ME = $relme;
}

return;
}

$rurl = array();
$hostport = explode(':', $_SERVER['HTTP_HOST']);
$rurl['host'] = reset($hostport);
$rurl['port'] = $_SERVER['SERVER_PORT'];
$rurl['path'] = $_SERVER['SCRIPT_NAME']; // script path without slash arguments

if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
//Apache server
$rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

} else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
//lighttpd
$rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded

} else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
//IIS
$rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
$rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];

// NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
// since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
// example rule: RewriteRule ^([^\?]+\.php)(\/.+)$ $1\?file=$2 [QSA]

if ($_SERVER['QUERY_STRING'] != '') {
// iis is decoding the query string, let's reencode it in order to emulate QUERY_STRING in Apache
// TODO: move this into lib/setup.php
$encoded = urlencode($_SERVER['QUERY_STRING']);
$encoded = str_replace(urlencode('='), '=', $encoded);
$encoded = str_replace(urlencode('%'), '%', $encoded);
$encoded = str_replace(urlencode('&'), '&', $encoded);
$rurl['fullpath'] .= '?'.$encoded;
}
$_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility

} else {
print_error('usupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
}

if (strpos($rurl['path'], $url['path']) === 0) {
$SCRIPT = substr($rurl['path'], strlen($url['path']));
} else {
// probably some weird external script
$SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
return;
}

// $CFG->sslproxy specifies if external SSL apliance is used (server using http, ext box translating everything to https)
if (empty($CFG->sslproxy)) {
if ($rurl['scheme'] == 'http' and $url['scheme'] == 'https') {
print_error('sslonlyaccess', 'error');
}
}

// $CFG->reverseproxy specifies if reverse proxy server used - used in advanced load balancing setups only!
// this is not supposed to solve lan/wan access problems!!!!!
if (empty($CFG->reverseproxy)) {
if (($rurl['host'] != $url['host']) or (!empty($url['port']) and $rurl['port'] != $url['port'])) {
print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
}
}

$FULLME = $rurl['scheme'].'://'.$url['host'];
if (!empty($url['port'])) {
$FULLME .= ':'.$url['port'];
}
$FULLSCRIPT = $FULLME.$rurl['path'];
$FULLME = $FULLME.$rurl['fullpath'];
$ME = $rurl['fullpath'];

}

/**
* Initializes our performance info early.
*
Expand Down Expand Up @@ -130,7 +230,7 @@ function init_performance_info() {
* @param string $newlimit the new memory limit
* @return bool
*/
function raise_memory_limit ($newlimit) {
function raise_memory_limit($newlimit) {

if (empty($newlimit)) {
return false;
Expand Down Expand Up @@ -166,6 +266,7 @@ function get_real_size($size=0) {
if (!$size) {
return 0;
}
$scan = array();
$scan['MB'] = 1048576;
$scan['Mb'] = 1048576;
$scan['M'] = 1048576;
Expand Down
Loading

0 comments on commit 11e7b50

Please sign in to comment.