From e4f47125ab30ff58f4053900f872a79462b78f3c Mon Sep 17 00:00:00 2001 From: John Blackbourn Date: Mon, 9 Nov 2020 13:16:54 +0000 Subject: [PATCH] Media: Restore the ability of `WP_Image_Editor_Imagick->save()` to create a missing directory when needed. Props eemitch, mikeschroder, hellofromTonya, p00ya, johnbillion Fixes #51665 git-svn-id: https://develop.svn.wordpress.org/trunk@49542 602fd350-edb4-49c9-b593-d223f7449a82 --- .../class-wp-image-editor-imagick.php | 14 +++++++++++ tests/phpunit/tests/image/editorImagick.php | 23 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-imagick.php b/src/wp-includes/class-wp-image-editor-imagick.php index ab9d302070..a03ccf9760 100644 --- a/src/wp-includes/class-wp-image-editor-imagick.php +++ b/src/wp-includes/class-wp-image-editor-imagick.php @@ -741,6 +741,20 @@ class WP_Image_Editor_Imagick extends WP_Image_Editor { return true; } } else { + $dir_name = dirname( $filename ); + $dir_exists = wp_mkdir_p( $dir_name ); + + if ( ! $dir_exists ) { + return new WP_Error( + 'image_save_error', + sprintf( + /* translators: %s: Directory path. */ + __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), + esc_html( $dir_name ) + ) + ); + } + try { return $image->writeImage( $filename ); } catch ( Exception $e ) { diff --git a/tests/phpunit/tests/image/editorImagick.php b/tests/phpunit/tests/image/editorImagick.php index 8bb2cd1d9a..c5fa17272c 100644 --- a/tests/phpunit/tests/image/editorImagick.php +++ b/tests/phpunit/tests/image/editorImagick.php @@ -597,4 +597,27 @@ class Tests_Image_Editor_Imagick extends WP_Image_UnitTestCase { } unlink( $temp_file ); } + + /** + * @ticket 51665 + */ + public function test_directory_creation() { + $file = realpath( DIR_TESTDATA ) . '/images/a2-small.jpg'; + $directory = realpath( DIR_TESTDATA ) . '/images/nonexistent-directory'; + $editor = new WP_Image_Editor_Imagick( $file ); + + $this->assertFileNotExists( $directory ); + + $loaded = $editor->load(); + $this->assertNotWPError( $loaded ); + + $resized = $editor->resize( 100, 100, true ); + $this->assertNotWPError( $resized ); + + $saved = $editor->save( $directory . '/a2-small-cropped.jpg' ); + $this->assertNotWPError( $saved ); + + unlink( $directory . '/a2-small-cropped.jpg' ); + rmdir( $directory ); + } }