diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index 238bcc738c..6f5d0432a8 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -4296,16 +4296,20 @@ function esc_sql( $data ) { * is applied to the returned cleaned URL. * * @since 2.8.0 - * - * @param string $url The URL to be cleaned. - * @param string[] $protocols Optional. An array of acceptable protocols. - * Defaults to return value of wp_allowed_protocols(). - * @param string $_context Private. Use esc_url_raw() for database usage. + * @since 5.8.0 Added the `$default_protocol` parameter. + * + * @param string $url The URL to be cleaned. + * @param string[] $protocols Optional. An array of acceptable protocols. + * Defaults to return value of wp_allowed_protocols(). + * @param string $_context Private. Use esc_url_raw() for database usage. + * @param string $default_protocol Use to specify different default, for historical + * reasons esc_url defaults to http:// pass string + * https:// to change the default behavior. * @return string The cleaned URL after the {@see 'clean_url'} filter is applied. * An empty string is returned if `$url` specifies a protocol other than * those in `$protocols`, or if `$url` contains an empty string. */ -function esc_url( $url, $protocols = null, $_context = 'display' ) { +function esc_url( $url, $protocols = null, $_context = 'display', $default_protocol = 'http://' ) { $original_url = $url; if ( '' === $url ) { @@ -4329,10 +4333,11 @@ function esc_url( $url, $protocols = null, $_context = 'display' ) { * If the URL doesn't appear to contain a scheme, we presume * it needs http:// prepended (unless it's a relative link * starting with /, # or ?, or a PHP file). + * Since 5.8, it uses $default_protocol to allow https:// presumption */ if ( strpos( $url, ':' ) === false && ! in_array( $url[0], array( '/', '#', '?' ), true ) && ! preg_match( '/^[a-z0-9-]+?\.php/i', $url ) ) { - $url = 'http://' . $url; + $url = $default_protocol . $url; } // Replace ampersands and single quotes only when displaying. diff --git a/tests/phpunit/tests/formatting/EscUrl.php b/tests/phpunit/tests/formatting/EscUrl.php index 13ecc4af66..076da6234f 100644 --- a/tests/phpunit/tests/formatting/EscUrl.php +++ b/tests/phpunit/tests/formatting/EscUrl.php @@ -262,4 +262,20 @@ EOT; $this->assertSame( 'http://[::FFFF::127.0.0.1]/?foo%5Bbar%5D=baz', esc_url( 'http://[::FFFF::127.0.0.1]/?foo[bar]=baz' ) ); } + /** + * @ticket 52886 + */ + function test_default_protocol() { + $this->assertSame( 'http://example.com', esc_url( 'example.com' ) ); + $this->assertSame( + 'https://example.com', + esc_url( + 'example.com', + null, + 'display', + 'https://' + ) + ); + } + }