Skip to content

Commit

Permalink
Media: Check if content URL includes a hostname in `wp_calculate_imag…
Browse files Browse the repository at this point in the history
…e_srcset()`.

This resolves an `Undefined array key "host"` PHP warning if `WP_CONTENT_URL` is set to a relative URL.

Follow-up to [58097].

Props mattraines, narenin, pamprn, SergeyBiryukov.
Fixes #61690.

git-svn-id: https://develop.svn.wordpress.org/trunk@58773 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information
SergeyBiryukov committed Jul 20, 2024
1 parent ffba41d commit 68b2338
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/wp-includes/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -1366,13 +1366,17 @@ function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attac
* (which is to say, when they share the domain name of the current request).
*/
if ( is_ssl() && ! str_starts_with( $image_baseurl, 'https' ) ) {
// Since the `Host:` header might contain a port we should
// compare it against the image URL using the same port.
/*
* Since the `Host:` header might contain a port, it should
* be compared against the image URL using the same port.
*/
$parsed = parse_url( $image_baseurl );
$domain = $parsed['host'];
$domain = isset( $parsed['host'] ) ? $parsed['host'] : '';

if ( isset( $parsed['port'] ) ) {
$domain .= ':' . $parsed['port'];
}

if ( $_SERVER['HTTP_HOST'] === $domain ) {
$image_baseurl = set_url_scheme( $image_baseurl, 'https' );
}
Expand Down
25 changes: 25 additions & 0 deletions tests/phpunit/tests/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -1833,6 +1833,31 @@ public function test_wp_calculate_image_srcset_with_absolute_path_in_meta() {
}
}

/**
* @ticket 61690
* @requires function imagejpeg
*/
public function test_wp_calculate_image_srcset_with_relative_content_url() {
$_SERVER['HTTPS'] = 'on';

add_filter(
'upload_dir',
static function ( $upload_dir ) {
$upload_dir['baseurl'] = '/wp-content/uploads';
return $upload_dir;
}
);

$image_url = wp_get_attachment_image_url( self::$large_id, 'medium' );
$image_meta = wp_get_attachment_metadata( self::$large_id );

$size_array = array( 300, 225 );

$srcset = wp_calculate_image_srcset( $size_array, $image_url, $image_meta );

$this->assertStringStartsWith( '/wp-content/uploads', $srcset );
}

/**
* @ticket 33641
*/
Expand Down

0 comments on commit 68b2338

Please sign in to comment.