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
This commit is contained in:
Sergey Biryukov 2022-03-09 15:06:09 +00:00
parent 4d29532b9b
commit 6b224e3ac0
2 changed files with 49 additions and 3 deletions

View File

@ -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'];
}

View File

@ -0,0 +1,40 @@
<?php
/**
* @group canonical
* @group rewrite
* @group query
* @covers ::strip_fragment_from_url
*/
class Tests_Canonical_StripFragmentFromUrl extends WP_UnitTestCase {
/**
* @dataProvider data_strip_fragment_from_url
* @ticket 55333
*/
public function test_strip_fragment_from_url( $test_url, $expected ) {
$this->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/' ),
);
}
}