Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/wp-admin/includes/image.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
*/
function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
$src_file = $src;
if ( is_numeric( $src ) ) { // Handle int as attachment ID.
$tmp_file = false;

// Handle int as attachment ID.
if ( is_numeric( $src ) ) {
$src_file = get_attached_file( $src );

if ( ! file_exists( $src_file ) ) {
Expand All @@ -38,7 +41,29 @@ function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $s
}
}

if ( wp_http_validate_url( $src ) ) {
if ( ! function_exists( 'download_url' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}

$tmp_file = download_url( $src );
if ( is_wp_error( $tmp_file ) ) {
return $tmp_file;
}

if ( wp_http_validate_url( $src_file ) ) {
$src_file = $tmp_file;
}

$src = $tmp_file;
}

$editor = wp_get_image_editor( $src );

if ( $tmp_file ) {
wp_delete_file( $tmp_file );
}

if ( is_wp_error( $editor ) ) {
return $editor;
}
Expand Down
50 changes: 36 additions & 14 deletions tests/phpunit/tests/image/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -636,25 +636,47 @@ public function test_wp_crop_image_with_file() {
}

/**
* @ticket 42064
*
* @covers ::wp_crop_image
* @requires function imagejpeg
* @requires extension openssl
*/
public function test_wp_crop_image_with_url() {
$file = wp_crop_image(
'https://s.w.org/screenshots/3.9/dashboard.png',
0,
0,
100,
100,
100,
100,
false,
DIR_TESTDATA . '/images/' . __FUNCTION__ . '.png'
);
$url = 'https://example.org/canola.jpg';
$mock_image_download = static function ( $response, $args, $requested_url ) use ( $url ) {
if ( $url !== $requested_url ) {
return $response;
}

if ( empty( $args['filename'] ) || ! copy( DIR_TESTDATA . '/images/canola.jpg', $args['filename'] ) ) {
return new WP_Error( 'copy_failed', 'Could not copy the image fixture.' );
}

if ( is_wp_error( $file ) && $file->get_error_code() === 'invalid_image' ) {
$this->markTestSkipped( 'Tests_Image_Functions::test_wp_crop_image_url() cannot access remote image.' );
return array(
'response' => array(
'code' => 200,
'message' => 'OK',
),
'headers' => array(),
'cookies' => array(),
'body' => '',
);
};

add_filter( 'pre_http_request', $mock_image_download, 10, 3 );

try {
$file = wp_crop_image(
$url,
0,
0,
100,
100,
100,
100
);
} finally {
remove_filter( 'pre_http_request', $mock_image_download, 10 );
}

$this->assertNotWPError( $file, 'Cropping the image resulted in a WP_Error.' );
Expand Down
Loading