From d1e841c03b794be451ab942b9e64f35b5d9e19ac Mon Sep 17 00:00:00 2001 From: Boone Gorges Date: Wed, 19 Nov 2014 01:52:57 +0000 Subject: [PATCH] Improvements to `wp_make_link_relative()`. * Support relative URL input. * When the URL being made relative has another URL as a parameter, don't make the second URL relative. Props voldemortensen. Fixes #30373. git-svn-id: https://develop.svn.wordpress.org/trunk@30383 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/formatting.php | 2 +- tests/phpunit/tests/link.php | 32 +++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index 411eaa8601..57cfcb1eac 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -3239,7 +3239,7 @@ function tag_escape($tag_name) { * @return string Absolute path. */ function wp_make_link_relative( $link ) { - return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link ); + return preg_replace( '|^(https?:)?//[^/]+(/.*)|i', '$2', $link ); } /** diff --git a/tests/phpunit/tests/link.php b/tests/phpunit/tests/link.php index 9e3a39d1a0..ec94d6084e 100644 --- a/tests/phpunit/tests/link.php +++ b/tests/phpunit/tests/link.php @@ -256,4 +256,34 @@ class Tests_Link extends WP_UnitTestCase { $this->assertEquals( $four, get_adjacent_post( true, array( $exclude ), true ) ); $this->assertEmpty( get_adjacent_post( false, array(), false ) ); } -} \ No newline at end of file + + public function test_wp_make_link_relative_with_http_scheme() { + $link = 'http://example.com/this-is-a-test-http-url/'; + $relative_link = wp_make_link_relative( $link ); + $this->assertEquals( '/this-is-a-test-http-url/', $relative_link ); + } + + public function test_wp_make_link_relative_with_https_scheme() { + $link = 'https://example.com/this-is-a-test-https-url/'; + $relative_link = wp_make_link_relative( $link ); + $this->assertEquals( '/this-is-a-test-https-url/', $relative_link ); + } + + /** + * @ticket 30373 + */ + public function test_wp_make_link_relative_with_no_scheme() { + $link = '//example.com/this-is-a-test-schemeless-url/'; + $relative_link = wp_make_link_relative( $link ); + $this->assertEquals( '/this-is-a-test-schemeless-url/', $relative_link ); + } + + /** + * @ticket 30373 + */ + public function test_wp_make_link_relative_should_retain_URL_param_that_is_also_a_URL() { + $link = 'https://example.com/this-is-a-test/?redirect=https://example.org/a-different-test-post/'; + $relative_link = wp_make_link_relative( $link ); + $this->assertEquals( '/this-is-a-test/?redirect=https://example.org/a-different-test-post/', $relative_link ); + } +}