From 6f604612204d05de55b9abd1a98671d7f3c2c983 Mon Sep 17 00:00:00 2001 From: Paul Holden Date: Wed, 6 Dec 2023 10:48:13 +0000 Subject: [PATCH] MDL-80338 core: encode moodle_url instance anchor properties. --- lib/tests/moodle_url_test.php | 15 +++++++++++++++ lib/weblib.php | 4 ++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/tests/moodle_url_test.php b/lib/tests/moodle_url_test.php index 61b39455e64..eb33e6ba76a 100644 --- a/lib/tests/moodle_url_test.php +++ b/lib/tests/moodle_url_test.php @@ -50,6 +50,9 @@ class moodle_url_test extends \advanced_testcase { $url = new \moodle_url('/index.php', null, 'test'); $this->assertSame($CFG->wwwroot.'/index.php#test', $url->out()); + $url = new \moodle_url('/index.php', null, 'Long "Anchor"'); + $this->assertSame($CFG->wwwroot . '/index.php#Long%20%22Anchor%22', $url->out()); + $url = new \moodle_url('/index.php', array('id' => 2), 'test'); $this->assertSame($CFG->wwwroot.'/index.php?id=2#test', $url->out()); } @@ -136,6 +139,18 @@ class moodle_url_test extends \advanced_testcase { $this->assertSame($strurl, $url->out(false)); } + /** + * Test returning URL without parameters + */ + public function test_out_omit_querystring(): void { + global $CFG; + + $url = new \moodle_url('/index.php', ['id' => 2], 'Long "Anchor"'); + + $this->assertSame($CFG->wwwroot . '/index.php', $url->out_omit_querystring()); + $this->assertSame($CFG->wwwroot . '/index.php#Long%20%22Anchor%22', $url->out_omit_querystring(true)); + } + public function test_compare_url() { $url1 = new \moodle_url('index.php', array('var1' => 1, 'var2' => 2)); $url2 = new \moodle_url('index2.php', array('var1' => 1, 'var2' => 2, 'var3' => 3)); diff --git a/lib/weblib.php b/lib/weblib.php index 8415fe0a90b..a18ac9c60cc 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -619,7 +619,7 @@ class moodle_url { $uri .= '?' . $querystring; } if (!is_null($this->anchor)) { - $uri .= '#'.$this->anchor; + $uri .= '#' . rawurlencode($this->anchor); } return $uri; @@ -639,7 +639,7 @@ class moodle_url { $uri .= $this->port ? ':'.$this->port : ''; $uri .= $this->path ? $this->path : ''; if ($includeanchor and !is_null($this->anchor)) { - $uri .= '#' . $this->anchor; + $uri .= '#' . rawurlencode($this->anchor); } return $uri;