From 19bedb8eba335de09f8aa3715b7ed9e604593239 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Fri, 6 Jan 2023 22:36:54 +0800 Subject: [PATCH] MDL-76362 core: Short-circuit strip_querystring on empty values --- lib/tests/weblib_test.php | 30 ++++++++++++++++++++++++++++-- lib/weblib.php | 5 ++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/lib/tests/weblib_test.php b/lib/tests/weblib_test.php index 9dc91dbac75..561b64a48df 100644 --- a/lib/tests/weblib_test.php +++ b/lib/tests/weblib_test.php @@ -23,9 +23,7 @@ * @author T.J.Hunt@open.ac.uk * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ - class weblib_test extends advanced_testcase { - /** * @covers ::format_string */ @@ -1119,4 +1117,32 @@ EXPECTED; ], ]; } + + /** + * Data provider for strip_querystring tests. + * + * @return array + */ + public function strip_querystring_provider(): array { + return [ + 'Null' => [null, ''], + 'Empty string' => ['', ''], + 'No querystring' => ['https://example.com', 'https://example.com'], + 'Querystring' => ['https://example.com?foo=bar', 'https://example.com'], + 'Querystring with fragment' => ['https://example.com?foo=bar#baz', 'https://example.com'], + 'Querystring with fragment and path' => ['https://example.com/foo/bar?foo=bar#baz', 'https://example.com/foo/bar'], + ]; + } + + /** + * Test the strip_querystring function with various exampels. + * + * @dataProvider strip_querystring_provider + * @param mixed $value + * @param mixed $expected + * @covers ::strip_querystring + */ + public function test_strip_querystring($value, $expected): void { + $this->assertEquals($expected, strip_querystring($value)); + } } diff --git a/lib/weblib.php b/lib/weblib.php index 1607c47a24e..bd724d3637b 100644 --- a/lib/weblib.php +++ b/lib/weblib.php @@ -148,8 +148,11 @@ function addslashes_js($var) { * @return string The remaining URL. */ function strip_querystring($url) { + if ($url === null || $url === '') { + return ''; + } - if ($commapos = strpos($url ?? '', '?')) { + if ($commapos = strpos($url, '?')) { return substr($url, 0, $commapos); } else { return $url;