<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[48291] trunk: REST API: Introduce endpoint for editing images.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="https://core.trac.wordpress.org/changeset/48291">48291</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"https://core.trac.wordpress.org/changeset/48291","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>TimothyBlynJacobs</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2020-07-04 04:13:17 +0000 (Sat, 04 Jul 2020)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>REST API: Introduce endpoint for editing images.

To facilitate inline image editing in Gutenberg, a new endpoint at wp/v2/media/<id>/edit has been introduced. This is functionally similar to the existing ajax image editor, however the REST API editor creates a new attachment record instead of updating an existing attachment.

Fixes <a href="https://core.trac.wordpress.org/ticket/44405">#44405</a>.
Props ajlende, ellatrix, spacedmonkey, azaozz.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludesrestapiendpointsclasswprestattachmentscontrollerphp">trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php</a></li>
<li><a href="#trunktestsphpunitincludesmockimageeditorphp">trunk/tests/phpunit/includes/mock-image-editor.php</a></li>
<li><a href="#trunktestsphpunittestsrestapirestattachmentscontrollerphp">trunk/tests/phpunit/tests/rest-api/rest-attachments-controller.php</a></li>
<li><a href="#trunktestsphpunittestsrestapirestschemasetupphp">trunk/tests/phpunit/tests/rest-api/rest-schema-setup.php</a></li>
<li><a href="#trunktestsqunitfixtureswpapigeneratedjs">trunk/tests/qunit/fixtures/wp-api-generated.js</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludesrestapiendpointsclasswprestattachmentscontrollerphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 2020-07-03 23:40:45 UTC (rev 48290)
+++ trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php   2020-07-04 04:13:17 UTC (rev 48291)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -45,6 +45,16 @@
</span><span class="cx" style="display: block; padding: 0 10px">                                ),
</span><span class="cx" style="display: block; padding: 0 10px">                        )
</span><span class="cx" style="display: block; padding: 0 10px">                );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                register_rest_route(
+                       $this->namespace,
+                       '/' . $this->rest_base . '/(?P<id>[\d]+)/edit',
+                       array(
+                               'methods'             => WP_REST_Server::CREATABLE,
+                               'callback'            => array( $this, 'edit_media_item' ),
+                               'permission_callback' => array( $this, 'edit_media_item_permissions_check' ),
+                               'args'                => $this->get_edit_media_item_args(),
+                       )
+               );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -365,7 +375,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="cx" style="display: block; padding: 0 10px">         * Checks if a given request can perform post processing on an attachment.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-         * @sicne 5.3.0
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+  * @since 5.3.0
</ins><span class="cx" style="display: block; padding: 0 10px">          *
</span><span class="cx" style="display: block; padding: 0 10px">         * @param WP_REST_Request $request Full details about the request.
</span><span class="cx" style="display: block; padding: 0 10px">         * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -375,6 +385,220 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Checks if a given request has access to editing media.
+        *
+        * @since 5.5.0
+        *
+        * @param WP_REST_Request $request Full details about the request.
+        * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
+        */
+       public function edit_media_item_permissions_check( $request ) {
+               if ( ! current_user_can( 'upload_files' ) ) {
+                       return new WP_Error(
+                               'rest_cannot_edit_image',
+                               __( 'Sorry, you are not allowed to upload media on this site.' ),
+                               array( 'status' => rest_authorization_required_code() )
+                       );
+               }
+
+               return $this->update_item_permissions_check( $request );
+       }
+
+       /**
+        * Applies edits to a media item and creates a new attachment record.
+        *
+        * @since 5.5.0
+        *
+        * @param WP_REST_Request $request Full details about the request.
+        * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
+        */
+       public function edit_media_item( $request ) {
+               require_once ABSPATH . 'wp-admin/includes/image.php';
+
+               $attachment_id = $request['id'];
+
+               // This also confirms the attachment is an image.
+               $image_file = wp_get_original_image_path( $attachment_id );
+               $image_meta = wp_get_attachment_metadata( $attachment_id );
+
+               if ( ! $image_meta || ! $image_file ) {
+                       return new WP_Error(
+                               'rest_unknown_attachment',
+                               __( 'Unable to get meta information for file.' ),
+                               array( 'status' => 404 )
+                       );
+               }
+
+               $supported_types = array( 'image/jpeg', 'image/png', 'image/gif' );
+               $mime_type       = get_post_mime_type( $attachment_id );
+               if ( ! in_array( $mime_type, $supported_types, true ) ) {
+                       return new WP_Error(
+                               'rest_cannot_edit_file_type',
+                               __( 'This type of file cannot be edited.' ),
+                               array( 'status' => 400 )
+                       );
+               }
+
+               // Check if we need to do anything.
+               $rotate = 0;
+               $crop   = false;
+
+               if ( ! empty( $request['rotation'] ) ) {
+                       // Rotation direction: clockwise vs. counter clockwise.
+                       $rotate = 0 - (int) $request['rotation'];
+               }
+
+               if ( isset( $request['x'], $request['y'], $request['width'], $request['height'] ) ) {
+                       $crop = true;
+               }
+
+               if ( ! $rotate && ! $crop ) {
+                       return new WP_Error(
+                               'rest_image_not_edited',
+                               __( 'The image was not edited. Edit the image before applying the changes.' ),
+                               array( 'status' => 400 )
+                       );
+               }
+
+               $image_editor = wp_get_image_editor( $image_file );
+
+               if ( is_wp_error( $image_editor ) ) {
+                       return new WP_Error(
+                               'rest_unknown_image_file_type',
+                               __( 'Unable to edit this image.' ),
+                               array( 'status' => 500 )
+                       );
+               }
+
+               if ( 0 !== $rotate ) {
+                       $result = $image_editor->rotate( $rotate );
+
+                       if ( is_wp_error( $result ) ) {
+                               return new WP_Error(
+                                       'rest_image_rotation_failed',
+                                       __( 'Unable to rotate this image.' ),
+                                       array( 'status' => 500 )
+                               );
+                       }
+               }
+
+               if ( $crop ) {
+                       $size = $image_editor->get_size();
+
+                       $crop_x = round( ( $size['width'] * floatval( $request['x'] ) ) / 100.0 );
+                       $crop_y = round( ( $size['height'] * floatval( $request['y'] ) ) / 100.0 );
+                       $width  = round( ( $size['width'] * floatval( $request['width'] ) ) / 100.0 );
+                       $height = round( ( $size['height'] * floatval( $request['height'] ) ) / 100.0 );
+
+                       $result = $image_editor->crop( $crop_x, $crop_y, $width, $height );
+
+                       if ( is_wp_error( $result ) ) {
+                               return new WP_Error(
+                                       'rest_image_crop_failed',
+                                       __( 'Unable to crop this image.' ),
+                                       array( 'status' => 500 )
+                               );
+                       }
+               }
+
+               // Calculate the file name.
+               $image_ext  = pathinfo( $image_file, PATHINFO_EXTENSION );
+               $image_name = wp_basename( $image_file, ".{$image_ext}" );
+
+               // Do not append multiple `-edited` to the file name.
+               // The user may be editing a previously edited image.
+               if ( preg_match( '/-edited(-\d+)?$/', $image_name ) ) {
+                       // Remove any `-1`, `-2`, etc. `wp_unique_filename()` will add the proper number.
+                       $image_name = preg_replace( '/-edited(-\d+)?$/', '-edited', $image_name );
+               } else {
+                       // Append `-edited` before the extension.
+                       $image_name .= '-edited';
+               }
+
+               $filename = "{$image_name}.{$image_ext}";
+
+               // Create the uploads sub-directory if needed.
+               $uploads = wp_upload_dir();
+
+               // Make the file name unique in the (new) upload directory.
+               $filename = wp_unique_filename( $uploads['path'], $filename );
+
+               // Save to disk.
+               $saved = $image_editor->save( $uploads['path'] . "/$filename" );
+
+               if ( is_wp_error( $saved ) ) {
+                       return $saved;
+               }
+
+               // Create new attachment post.
+               $attachment_post = array(
+                       'post_mime_type' => $saved['mime-type'],
+                       'guid'           => $uploads['url'] . "/$filename",
+                       'post_title'     => $filename,
+                       'post_content'   => '',
+               );
+
+               $new_attachment_id = wp_insert_attachment( wp_slash( $attachment_post ), $saved['path'], 0, true );
+
+               if ( is_wp_error( $new_attachment_id ) ) {
+                       if ( 'db_update_error' === $new_attachment_id->get_error_code() ) {
+                               $new_attachment_id->add_data( array( 'status' => 500 ) );
+                       } else {
+                               $new_attachment_id->add_data( array( 'status' => 400 ) );
+                       }
+
+                       return $new_attachment_id;
+               }
+
+               // Generate image sub-sizes and meta.
+               $new_image_meta = wp_generate_attachment_metadata( $new_attachment_id, $saved['path'] );
+
+               // Copy the EXIF metadata from the original attachment if not generated for the edited image.
+               if ( ! empty( $image_meta['image_meta'] ) ) {
+                       $empty_image_meta = true;
+
+                       if ( isset( $new_image_meta['image_meta'] ) && is_array( $new_image_meta['image_meta'] ) ) {
+                               $empty_image_meta = empty( array_filter( array_values( $new_image_meta['image_meta'] ) ) );
+                       }
+
+                       if ( $empty_image_meta ) {
+                               $new_image_meta['image_meta'] = $image_meta['image_meta'];
+                       }
+               }
+
+               // Reset orientation. At this point the image is edited and orientation is correct.
+               if ( ! empty( $new_image_meta['image_meta']['orientation'] ) ) {
+                       $new_image_meta['image_meta']['orientation'] = 1;
+               }
+
+               // The attachment_id may change if the site is exported and imported.
+               $new_image_meta['parent_image'] = array(
+                       'attachment_id' => $attachment_id,
+                       // Path to the originally uploaded image file relative to the uploads directory.
+                       'file'          => _wp_relative_upload_path( $image_file ),
+               );
+
+               /**
+                * Filters the updated attachment meta data.
+                *
+                * @since 5.5.0
+                *
+                * @param array $data              Array of updated attachment meta data.
+                * @param int   $new_attachment_id Attachment post ID.
+                * @param int   $attachment_id     Original Attachment post ID.
+                */
+               $new_image_meta = apply_filters( 'wp_edited_attachment_metadata', $new_image_meta, $new_attachment_id, $attachment_id );
+
+               wp_update_attachment_metadata( $new_attachment_id, $new_image_meta );
+
+               $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request );
+               $response->set_status( 201 );
+               $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) );
+
+               return $response;
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Prepares a single attachment for create or update.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @since 4.7.0
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1014,4 +1238,48 @@
</span><span class="cx" style="display: block; padding: 0 10px">                return true;
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        /**
+        * Gets the request args for the edit item route.
+        *
+        * @since 5.5.0
+        *
+        * @return array
+        */
+       protected function get_edit_media_item_args() {
+               return array(
+                       'rotation' => array(
+                               'description'      => __( 'The amount to rotate the image clockwise in degrees.' ),
+                               'type'             => 'integer',
+                               'minimum'          => 0,
+                               'exclusiveMinimum' => true,
+                               'maximum'          => 360,
+                               'exclusiveMaximum' => true,
+                       ),
+                       'x'        => array(
+                               'description' => __( 'As a percentage of the image, the x position to start the crop from.' ),
+                               'type'        => 'number',
+                               'minimum'     => 0,
+                               'maximum'     => 100,
+                       ),
+                       'y'        => array(
+                               'description' => __( 'As a percentage of the image, the y position to start the crop from.' ),
+                               'type'        => 'number',
+                               'minimum'     => 0,
+                               'maximum'     => 100,
+                       ),
+                       'width'    => array(
+                               'description' => __( 'As a percentage of the image, the width to crop the image to.' ),
+                               'type'        => 'number',
+                               'minimum'     => 0,
+                               'maximum'     => 100,
+                       ),
+                       'height'   => array(
+                               'description' => __( 'As a percentage of the image, the height to crop the image to.' ),
+                               'type'        => 'number',
+                               'minimum'     => 0,
+                               'maximum'     => 100,
+                       ),
+               );
+       }
+
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span></span></pre></div>
<a id="trunktestsphpunitincludesmockimageeditorphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/includes/mock-image-editor.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/includes/mock-image-editor.php        2020-07-03 23:40:45 UTC (rev 48290)
+++ trunk/tests/phpunit/includes/mock-image-editor.php  2020-07-04 04:13:17 UTC (rev 48291)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -7,6 +7,9 @@
</span><span class="cx" style="display: block; padding: 0 10px">                public static $load_return = true;
</span><span class="cx" style="display: block; padding: 0 10px">                public static $test_return = true;
</span><span class="cx" style="display: block; padding: 0 10px">                public static $save_return = array();
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                public static $spy         = array();
+               public static $edit_return = array();
+               public static $size_return = null;
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                // Allow testing of jpeg_quality filter.
</span><span class="cx" style="display: block; padding: 0 10px">                public function set_mime_type( $mime_type = null ) {
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -23,19 +26,34 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        return true;
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px">                public function resize( $max_w, $max_h, $crop = false ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 self::$spy[ __FUNCTION__ ][] = func_get_args();
+                       if ( isset( self::$edit_return[ __FUNCTION__ ] ) ) {
+                               return self::$edit_return[ __FUNCTION__ ];
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px">                public function multi_resize( $sizes ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 self::$spy[ __FUNCTION__ ][] = func_get_args();
+                       if ( isset( self::$edit_return[ __FUNCTION__ ] ) ) {
+                               return self::$edit_return[ __FUNCTION__ ];
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px">                public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 self::$spy[ __FUNCTION__ ][] = func_get_args();
+                       if ( isset( self::$edit_return[ __FUNCTION__ ] ) ) {
+                               return self::$edit_return[ __FUNCTION__ ];
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px">                public function rotate( $angle ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 self::$spy[ __FUNCTION__ ][] = func_get_args();
+                       if ( isset( self::$edit_return[ __FUNCTION__ ] ) ) {
+                               return self::$edit_return[ __FUNCTION__ ];
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px">                public function flip( $horz, $vert ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                 self::$spy[ __FUNCTION__ ][] = func_get_args();
+                       if ( isset( self::$edit_return[ __FUNCTION__ ] ) ) {
+                               return self::$edit_return[ __FUNCTION__ ];
+                       }
</ins><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px">                public function save( $destfilename = null, $mime_type = null ) {
</span><span class="cx" style="display: block; padding: 0 10px">                        return self::$save_return;
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -43,6 +61,14 @@
</span><span class="cx" style="display: block; padding: 0 10px">                public function stream( $mime_type = null ) {
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+               public function get_size() {
+                       if ( self::$size_return ) {
+                               return self::$size_return;
+                       }
+
+                       return parent::get_size();
+               }
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px"> endif;
</span></span></pre></div>
<a id="trunktestsphpunittestsrestapirestattachmentscontrollerphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/rest-api/rest-attachments-controller.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/rest-api/rest-attachments-controller.php        2020-07-03 23:40:45 UTC (rev 48290)
+++ trunk/tests/phpunit/tests/rest-api/rest-attachments-controller.php  2020-07-04 04:13:17 UTC (rev 48291)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -19,6 +19,16 @@
</span><span class="cx" style="display: block; padding: 0 10px">        protected static $rest_after_insert_attachment_count;
</span><span class="cx" style="display: block; padding: 0 10px">        protected static $rest_insert_attachment_count;
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        /**
+        * @var string The path to a test file.
+        */
+       private $test_file;
+
+       /**
+        * @var string The path to a second test file.
+        */
+       private $test_file2;
+
</ins><span class="cx" style="display: block; padding: 0 10px">         public static function wpSetUpBeforeClass( $factory ) {
</span><span class="cx" style="display: block; padding: 0 10px">                self::$superadmin_id  = $factory->user->create(
</span><span class="cx" style="display: block; padding: 0 10px">                        array(
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -77,6 +87,28 @@
</span><span class="cx" style="display: block; padding: 0 10px">                copy( $orig_file2, $this->test_file2 );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        public function tearDown() {
+               parent::tearDown();
+
+               if ( file_exists( $this->test_file ) ) {
+                       unlink( $this->test_file );
+               }
+               if ( file_exists( $this->test_file2 ) ) {
+                       unlink( $this->test_file2 );
+               }
+
+               remove_action( 'rest_insert_attachment', array( $this, 'filter_rest_insert_attachment' ) );
+               remove_action( 'rest_after_insert_attachment', array( $this, 'filter_rest_after_insert_attachment' ) );
+
+               $this->remove_added_uploads();
+
+               if ( class_exists( WP_Image_Editor_Mock::class ) ) {
+                       WP_Image_Editor_Mock::$spy         = array();
+                       WP_Image_Editor_Mock::$edit_return = array();
+                       WP_Image_Editor_Mock::$size_return = null;
+               }
+       }
+
</ins><span class="cx" style="display: block; padding: 0 10px">         public function test_register_routes() {
</span><span class="cx" style="display: block; padding: 0 10px">                $routes = rest_get_server()->get_routes();
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertArrayHasKey( '/wp/v2/media', $routes );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1537,21 +1569,6 @@
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertArrayNotHasKey( 'https://api.w.org/action-publish', $links );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-        public function tearDown() {
-               parent::tearDown();
-               if ( file_exists( $this->test_file ) ) {
-                       unlink( $this->test_file );
-               }
-               if ( file_exists( $this->test_file2 ) ) {
-                       unlink( $this->test_file2 );
-               }
-
-               remove_action( 'rest_insert_attachment', array( $this, 'filter_rest_insert_attachment' ) );
-               remove_action( 'rest_after_insert_attachment', array( $this, 'filter_rest_after_insert_attachment' ) );
-
-               $this->remove_added_uploads();
-       }
-
</del><span class="cx" style="display: block; padding: 0 10px">         protected function check_post_data( $attachment, $data, $context = 'view', $links ) {
</span><span class="cx" style="display: block; padding: 0 10px">                parent::check_post_data( $attachment, $data, $context, $links );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -1776,4 +1793,175 @@
</span><span class="cx" style="display: block; padding: 0 10px">        public function filter_rest_after_insert_attachment( $attachment ) {
</span><span class="cx" style="display: block; padding: 0 10px">                self::$rest_after_insert_attachment_count++;
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_returns_error_if_logged_out() {
+               $attachment = self::factory()->attachment->create();
+
+               $request  = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_cannot_edit_image', $response, 401 );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_returns_error_if_cannot_upload() {
+               $user = self::factory()->user->create_and_get( array( 'role' => 'editor' ) );
+               $user->add_cap( 'upload_files', false );
+
+               wp_set_current_user( $user->ID );
+               $attachment = self::factory()->attachment->create( array( 'post_author' => $user->ID ) );
+
+               $request  = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_cannot_edit_image', $response, 403 );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_returns_error_if_cannot_edit() {
+               wp_set_current_user( self::$uploader_id );
+               $attachment = self::factory()->attachment->create();
+
+               $request  = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_cannot_edit', $response, 403 );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_returns_error_if_no_attachment() {
+               wp_set_current_user( self::$superadmin_id );
+               $attachment = self::factory()->attachment->create();
+
+               $request  = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_unknown_attachment', $response, 404 );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_returns_error_if_unsupported_mime_type() {
+               wp_set_current_user( self::$superadmin_id );
+               $attachment = self::factory()->attachment->create_upload_object( $this->test_file );
+               wp_update_post(
+                       array(
+                               'ID'             => $attachment,
+                               'post_mime_type' => 'image/invalid',
+                       )
+               );
+
+               $request  = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_cannot_edit_file_type', $response, 400 );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_returns_error_if_no_edits() {
+               wp_set_current_user( self::$superadmin_id );
+               $attachment = self::factory()->attachment->create_upload_object( $this->test_file );
+
+               $request  = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_image_not_edited', $response, 400 );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_rotate() {
+               wp_set_current_user( self::$superadmin_id );
+               $attachment = self::factory()->attachment->create_upload_object( $this->test_file );
+
+               $this->setup_mock_editor();
+               WP_Image_Editor_Mock::$edit_return['rotate'] = new WP_Error();
+
+               $request = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $request->set_body_params( array( 'rotation' => 60 ) );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_image_rotation_failed', $response, 500 );
+
+               $this->assertCount( 1, WP_Image_Editor_Mock::$spy['rotate'] );
+               $this->assertEquals( array( -60 ), WP_Image_Editor_Mock::$spy['rotate'][0] );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image_crop() {
+               wp_set_current_user( self::$superadmin_id );
+               $attachment = self::factory()->attachment->create_upload_object( $this->test_file );
+
+               $this->setup_mock_editor();
+               WP_Image_Editor_Mock::$size_return = array(
+                       'width'  => 640,
+                       'height' => 480,
+               );
+
+               WP_Image_Editor_Mock::$edit_return['crop'] = new WP_Error();
+
+               $request = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $request->set_body_params(
+                       array(
+                               'x'      => 50,
+                               'y'      => 10,
+                               'width'  => 10,
+                               'height' => 5,
+                       )
+               );
+               $response = rest_do_request( $request );
+               $this->assertErrorResponse( 'rest_image_crop_failed', $response, 500 );
+
+               $this->assertCount( 1, WP_Image_Editor_Mock::$spy['crop'] );
+               $this->assertEquals(
+                       array( 320.0, 48.0, 64.0, 24.0 ),
+                       WP_Image_Editor_Mock::$spy['crop'][0]
+               );
+       }
+
+       /**
+        * @ticket 44405
+        */
+       public function test_edit_image() {
+               wp_set_current_user( self::$superadmin_id );
+               $attachment = self::factory()->attachment->create_upload_object( $this->test_file );
+
+               $request = new WP_REST_Request( 'POST', "/wp/v2/media/{$attachment}/edit" );
+               $request->set_body_params( array( 'rotation' => 60 ) );
+               $response = rest_do_request( $request );
+               $item     = $response->get_data();
+
+               $this->assertEquals( 201, $response->get_status() );
+               $this->assertEquals( rest_url( '/wp/v2/media/' . $item['id'] ), $response->get_headers()['Location'] );
+
+               $this->assertStringEndsWith( '-edited.jpg', $item['media_details']['file'] );
+               $this->assertArrayHasKey( 'parent_image', $item['media_details'] );
+               $this->assertEquals( $attachment, $item['media_details']['parent_image']['attachment_id'] );
+               $this->assertContains( 'canola', $item['media_details']['parent_image']['file'] );
+       }
+
+       /**
+        * Sets up the mock image editor.
+        *
+        * @since 5.5.0
+        */
+       protected function setup_mock_editor() {
+               require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
+               require_once DIR_TESTDATA . '/../includes/mock-image-editor.php';
+
+               add_filter(
+                       'wp_image_editors',
+                       static function () {
+                               return array( 'WP_Image_Editor_Mock' );
+                       }
+               );
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span></span></pre></div>
<a id="trunktestsphpunittestsrestapirestschemasetupphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/rest-api/rest-schema-setup.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/rest-api/rest-schema-setup.php  2020-07-03 23:40:45 UTC (rev 48290)
+++ trunk/tests/phpunit/tests/rest-api/rest-schema-setup.php    2020-07-04 04:13:17 UTC (rev 48291)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -100,6 +100,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        '/wp/v2/media',
</span><span class="cx" style="display: block; padding: 0 10px">                        '/wp/v2/media/(?P<id>[\\d]+)',
</span><span class="cx" style="display: block; padding: 0 10px">                        '/wp/v2/media/(?P<id>[\\d]+)/post-process',
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                        '/wp/v2/media/(?P<id>[\\d]+)/edit',
</ins><span class="cx" style="display: block; padding: 0 10px">                         '/wp/v2/blocks',
</span><span class="cx" style="display: block; padding: 0 10px">                        '/wp/v2/blocks/(?P<id>[\d]+)',
</span><span class="cx" style="display: block; padding: 0 10px">                        '/wp/v2/blocks/(?P<id>[\d]+)/autosaves',
</span></span></pre></div>
<a id="trunktestsqunitfixtureswpapigeneratedjs"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/qunit/fixtures/wp-api-generated.js</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/qunit/fixtures/wp-api-generated.js    2020-07-03 23:40:45 UTC (rev 48290)
+++ trunk/tests/qunit/fixtures/wp-api-generated.js      2020-07-04 04:13:17 UTC (rev 48291)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -2342,6 +2342,46 @@
</span><span class="cx" style="display: block; padding: 0 10px">                 }
</span><span class="cx" style="display: block; padding: 0 10px">             ]
</span><span class="cx" style="display: block; padding: 0 10px">         },
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+        "/wp/v2/media/(?P<id>[\\d]+)/edit": {
+            "namespace": "wp/v2",
+            "methods": [
+                "POST"
+            ],
+            "endpoints": [
+                {
+                    "methods": [
+                        "POST"
+                    ],
+                    "args": {
+                        "rotation": {
+                            "required": false,
+                            "description": "The amount to rotate the image clockwise in degrees.",
+                            "type": "integer"
+                        },
+                        "x": {
+                            "required": false,
+                            "description": "As a percentage of the image, the x position to start the crop from.",
+                            "type": "number"
+                        },
+                        "y": {
+                            "required": false,
+                            "description": "As a percentage of the image, the y position to start the crop from.",
+                            "type": "number"
+                        },
+                        "width": {
+                            "required": false,
+                            "description": "As a percentage of the image, the width to crop the image to.",
+                            "type": "number"
+                        },
+                        "height": {
+                            "required": false,
+                            "description": "As a percentage of the image, the height to crop the image to.",
+                            "type": "number"
+                        }
+                    }
+                }
+            ]
+        },
</ins><span class="cx" style="display: block; padding: 0 10px">         "/wp/v2/blocks": {
</span><span class="cx" style="display: block; padding: 0 10px">             "namespace": "wp/v2",
</span><span class="cx" style="display: block; padding: 0 10px">             "methods": [
</span></span></pre>
</div>
</div>

</body>
</html>