From 6b224e3ac043009663be61c6646841c0fe45bf0a Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Wed, 9 Mar 2022 15:06:09 +0000 Subject: [PATCH] Canonical: Check if the URL scheme exists in `strip_fragment_from_url()`. This avoids an "Undefined index" PHP notice when a schemeless URI is passed. Props dd32, SergeyBiryukov. Fixes #55333. git-svn-id: https://develop.svn.wordpress.org/trunk@52833 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/canonical.php | 12 ++++-- .../tests/canonical/stripFragmentFromUrl.php | 40 +++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 tests/phpunit/tests/canonical/stripFragmentFromUrl.php diff --git a/src/wp-includes/canonical.php b/src/wp-includes/canonical.php index 184fb756e8..0defa8227d 100644 --- a/src/wp-includes/canonical.php +++ b/src/wp-includes/canonical.php @@ -847,11 +847,17 @@ function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $ur * @return string The altered URL. */ function strip_fragment_from_url( $url ) { - $parsed_url = parse_url( $url ); + $parsed_url = wp_parse_url( $url ); if ( ! empty( $parsed_url['host'] ) ) { - // This mirrors code in redirect_canonical(). It does not handle every case. - $url = $parsed_url['scheme'] . '://' . $parsed_url['host']; + $url = ''; + + if ( ! empty( $parsed_url['scheme'] ) ) { + $url = $parsed_url['scheme'] . ':'; + } + + $url .= '//' . $parsed_url['host']; + if ( ! empty( $parsed_url['port'] ) ) { $url .= ':' . $parsed_url['port']; } diff --git a/tests/phpunit/tests/canonical/stripFragmentFromUrl.php b/tests/phpunit/tests/canonical/stripFragmentFromUrl.php new file mode 100644 index 0000000000..053ad88528 --- /dev/null +++ b/tests/phpunit/tests/canonical/stripFragmentFromUrl.php @@ -0,0 +1,40 @@ +assertSame( $expected, strip_fragment_from_url( $test_url ) ); + } + + /** + * Data provider for test_strip_fragment_from_url(). + * + * @return array[] { + * Data to test with. + * + * @type string $0 The test URL. + * @type string $1 The expected canonical URL. + * } + */ + public function data_strip_fragment_from_url() { + return array( + array( '//example.com', '//example.com' ), + array( 'http://example.com', 'http://example.com' ), + array( 'https://example.com', 'https://example.com' ), + array( 'https://example.com/', 'https://example.com/' ), + array( 'https://example.com/?test', 'https://example.com/?test' ), + array( 'https://example.com/?#test', 'https://example.com/' ), + array( 'https://example.com/?#test#', 'https://example.com/' ), + ); + } +}