Make WordPress Core


Ignore:
Timestamp:
07/04/2020 04:13:17 AM (6 years ago)
Author:
TimothyBlynJacobs
Message:

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 #44405.
Props ajlende, ellatrix, spacedmonkey, azaozz.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php

    r47850 r48291  
    4646                        )
    4747                );
     48                register_rest_route(
     49                        $this->namespace,
     50                        '/' . $this->rest_base . '/(?P<id>[\d]+)/edit',
     51                        array(
     52                                'methods'             => WP_REST_Server::CREATABLE,
     53                                'callback'            => array( $this, 'edit_media_item' ),
     54                                'permission_callback' => array( $this, 'edit_media_item_permissions_check' ),
     55                                'args'                => $this->get_edit_media_item_args(),
     56                        )
     57                );
    4858        }
    4959
    … …  
    366376         * Checks if a given request can perform post processing on an attachment.
    367377         *
    368          * @sicne 5.3.0
     378         * @since 5.3.0
    369379         *
    370380         * @param WP_REST_Request $request Full details about the request.
    … …  
    373383        public function post_process_item_permissions_check( $request ) {
    374384                return $this->update_item_permissions_check( $request );
     385        }
     386
     387        /**
     388         * Checks if a given request has access to editing media.
     389         *
     390         * @since 5.5.0
     391         *
     392         * @param WP_REST_Request $request Full details about the request.
     393         * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
     394         */
     395        public function edit_media_item_permissions_check( $request ) {
     396                if ( ! current_user_can( 'upload_files' ) ) {
     397                        return new WP_Error(
     398                                'rest_cannot_edit_image',
     399                                __( 'Sorry, you are not allowed to upload media on this site.' ),
     400                                array( 'status' => rest_authorization_required_code() )
     401                        );
     402                }
     403
     404                return $this->update_item_permissions_check( $request );
     405        }
     406
     407        /**
     408         * Applies edits to a media item and creates a new attachment record.
     409         *
     410         * @since 5.5.0
     411         *
     412         * @param WP_REST_Request $request Full details about the request.
     413         * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
     414         */
     415        public function edit_media_item( $request ) {
     416                require_once ABSPATH . 'wp-admin/includes/image.php';
     417
     418                $attachment_id = $request['id'];
     419
     420                // This also confirms the attachment is an image.
     421                $image_file = wp_get_original_image_path( $attachment_id );
     422                $image_meta = wp_get_attachment_metadata( $attachment_id );
     423
     424                if ( ! $image_meta || ! $image_file ) {
     425                        return new WP_Error(
     426                                'rest_unknown_attachment',
     427                                __( 'Unable to get meta information for file.' ),
     428                                array( 'status' => 404 )
     429                        );
     430                }
     431
     432                $supported_types = array( 'image/jpeg', 'image/png', 'image/gif' );
     433                $mime_type       = get_post_mime_type( $attachment_id );
     434                if ( ! in_array( $mime_type, $supported_types, true ) ) {
     435                        return new WP_Error(
     436                                'rest_cannot_edit_file_type',
     437                                __( 'This type of file cannot be edited.' ),
     438                                array( 'status' => 400 )
     439                        );
     440                }
     441
     442                // Check if we need to do anything.
     443                $rotate = 0;
     444                $crop   = false;
     445
     446                if ( ! empty( $request['rotation'] ) ) {
     447                        // Rotation direction: clockwise vs. counter clockwise.
     448                        $rotate = 0 - (int) $request['rotation'];
     449                }
     450
     451                if ( isset( $request['x'], $request['y'], $request['width'], $request['height'] ) ) {
     452                        $crop = true;
     453                }
     454
     455                if ( ! $rotate && ! $crop ) {
     456                        return new WP_Error(
     457                                'rest_image_not_edited',
     458                                __( 'The image was not edited. Edit the image before applying the changes.' ),
     459                                array( 'status' => 400 )
     460                        );
     461                }
     462
     463                $image_editor = wp_get_image_editor( $image_file );
     464
     465                if ( is_wp_error( $image_editor ) ) {
     466                        return new WP_Error(
     467                                'rest_unknown_image_file_type',
     468                                __( 'Unable to edit this image.' ),
     469                                array( 'status' => 500 )
     470                        );
     471                }
     472
     473                if ( 0 !== $rotate ) {
     474                        $result = $image_editor->rotate( $rotate );
     475
     476                        if ( is_wp_error( $result ) ) {
     477                                return new WP_Error(
     478                                        'rest_image_rotation_failed',
     479                                        __( 'Unable to rotate this image.' ),
     480                                        array( 'status' => 500 )
     481                                );
     482                        }
     483                }
     484
     485                if ( $crop ) {
     486                        $size = $image_editor->get_size();
     487
     488                        $crop_x = round( ( $size['width'] * floatval( $request['x'] ) ) / 100.0 );
     489                        $crop_y = round( ( $size['height'] * floatval( $request['y'] ) ) / 100.0 );
     490                        $width  = round( ( $size['width'] * floatval( $request['width'] ) ) / 100.0 );
     491                        $height = round( ( $size['height'] * floatval( $request['height'] ) ) / 100.0 );
     492
     493                        $result = $image_editor->crop( $crop_x, $crop_y, $width, $height );
     494
     495                        if ( is_wp_error( $result ) ) {
     496                                return new WP_Error(
     497                                        'rest_image_crop_failed',
     498                                        __( 'Unable to crop this image.' ),
     499                                        array( 'status' => 500 )
     500                                );
     501                        }
     502                }
     503
     504                // Calculate the file name.
     505                $image_ext  = pathinfo( $image_file, PATHINFO_EXTENSION );
     506                $image_name = wp_basename( $image_file, ".{$image_ext}" );
     507
     508                // Do not append multiple `-edited` to the file name.
     509                // The user may be editing a previously edited image.
     510                if ( preg_match( '/-edited(-\d+)?$/', $image_name ) ) {
     511                        // Remove any `-1`, `-2`, etc. `wp_unique_filename()` will add the proper number.
     512                        $image_name = preg_replace( '/-edited(-\d+)?$/', '-edited', $image_name );
     513                } else {
     514                        // Append `-edited` before the extension.
     515                        $image_name .= '-edited';
     516                }
     517
     518                $filename = "{$image_name}.{$image_ext}";
     519
     520                // Create the uploads sub-directory if needed.
     521                $uploads = wp_upload_dir();
     522
     523                // Make the file name unique in the (new) upload directory.
     524                $filename = wp_unique_filename( $uploads['path'], $filename );
     525
     526                // Save to disk.
     527                $saved = $image_editor->save( $uploads['path'] . "/$filename" );
     528
     529                if ( is_wp_error( $saved ) ) {
     530                        return $saved;
     531                }
     532
     533                // Create new attachment post.
     534                $attachment_post = array(
     535                        'post_mime_type' => $saved['mime-type'],
     536                        'guid'           => $uploads['url'] . "/$filename",
     537                        'post_title'     => $filename,
     538                        'post_content'   => '',
     539                );
     540
     541                $new_attachment_id = wp_insert_attachment( wp_slash( $attachment_post ), $saved['path'], 0, true );
     542
     543                if ( is_wp_error( $new_attachment_id ) ) {
     544                        if ( 'db_update_error' === $new_attachment_id->get_error_code() ) {
     545                                $new_attachment_id->add_data( array( 'status' => 500 ) );
     546                        } else {
     547                                $new_attachment_id->add_data( array( 'status' => 400 ) );
     548                        }
     549
     550                        return $new_attachment_id;
     551                }
     552
     553                // Generate image sub-sizes and meta.
     554                $new_image_meta = wp_generate_attachment_metadata( $new_attachment_id, $saved['path'] );
     555
     556                // Copy the EXIF metadata from the original attachment if not generated for the edited image.
     557                if ( ! empty( $image_meta['image_meta'] ) ) {
     558                        $empty_image_meta = true;
     559
     560                        if ( isset( $new_image_meta['image_meta'] ) && is_array( $new_image_meta['image_meta'] ) ) {
     561                                $empty_image_meta = empty( array_filter( array_values( $new_image_meta['image_meta'] ) ) );
     562                        }
     563
     564                        if ( $empty_image_meta ) {
     565                                $new_image_meta['image_meta'] = $image_meta['image_meta'];
     566                        }
     567                }
     568
     569                // Reset orientation. At this point the image is edited and orientation is correct.
     570                if ( ! empty( $new_image_meta['image_meta']['orientation'] ) ) {
     571                        $new_image_meta['image_meta']['orientation'] = 1;
     572                }
     573
     574                // The attachment_id may change if the site is exported and imported.
     575                $new_image_meta['parent_image'] = array(
     576                        'attachment_id' => $attachment_id,
     577                        // Path to the originally uploaded image file relative to the uploads directory.
     578                        'file'          => _wp_relative_upload_path( $image_file ),
     579                );
     580
     581                /**
     582                 * Filters the updated attachment meta data.
     583                 *
     584                 * @since 5.5.0
     585                 *
     586                 * @param array $data              Array of updated attachment meta data.
     587                 * @param int   $new_attachment_id Attachment post ID.
     588                 * @param int   $attachment_id     Original Attachment post ID.
     589                 */
     590                $new_image_meta = apply_filters( 'wp_edited_attachment_metadata', $new_image_meta, $new_attachment_id, $attachment_id );
     591
     592                wp_update_attachment_metadata( $new_attachment_id, $new_image_meta );
     593
     594                $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request );
     595                $response->set_status( 201 );
     596                $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) );
     597
     598                return $response;
    375599        }
    376600
    … …  
    10151239        }
    10161240
     1241        /**
     1242         * Gets the request args for the edit item route.
     1243         *
     1244         * @since 5.5.0
     1245         *
     1246         * @return array
     1247         */
     1248        protected function get_edit_media_item_args() {
     1249                return array(
     1250                        'rotation' => array(
     1251                                'description'      => __( 'The amount to rotate the image clockwise in degrees.' ),
     1252                                'type'             => 'integer',
     1253                                'minimum'          => 0,
     1254                                'exclusiveMinimum' => true,
     1255                                'maximum'          => 360,
     1256                                'exclusiveMaximum' => true,
     1257                        ),
     1258                        'x'        => array(
     1259                                'description' => __( 'As a percentage of the image, the x position to start the crop from.' ),
     1260                                'type'        => 'number',
     1261                                'minimum'     => 0,
     1262                                'maximum'     => 100,
     1263                        ),
     1264                        'y'        => array(
     1265                                'description' => __( 'As a percentage of the image, the y position to start the crop from.' ),
     1266                                'type'        => 'number',
     1267                                'minimum'     => 0,
     1268                                'maximum'     => 100,
     1269                        ),
     1270                        'width'    => array(
     1271                                'description' => __( 'As a percentage of the image, the width to crop the image to.' ),
     1272                                'type'        => 'number',
     1273                                'minimum'     => 0,
     1274                                'maximum'     => 100,
     1275                        ),
     1276                        'height'   => array(
     1277                                'description' => __( 'As a percentage of the image, the height to crop the image to.' ),
     1278                                'type'        => 'number',
     1279                                'minimum'     => 0,
     1280                                'maximum'     => 100,
     1281                        ),
     1282                );
     1283        }
     1284
    10171285}
Note: See TracChangeset for help on using the changeset viewer.