[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/rest-api/endpoints/ -> class-wp-rest-attachments-controller.php (source)

   1  <?php
   2  /**
   3   * REST API: WP_REST_Attachments_Controller class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 4.7.0
   8   */
   9  
  10  /**
  11   * Core controller used to access attachments via the REST API.
  12   *
  13   * @since 4.7.0
  14   *
  15   * @see WP_REST_Posts_Controller
  16   */
  17  class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
  18  
  19      /**
  20       * Whether the controller supports batching.
  21       *
  22       * @since 5.9.0
  23       * @var false
  24       */
  25      protected $allow_batch = false;
  26  
  27      /**
  28       * Registers the routes for attachments.
  29       *
  30       * @since 5.3.0
  31       *
  32       * @see register_rest_route()
  33       */
  34  	public function register_routes() {
  35          parent::register_routes();
  36          register_rest_route(
  37              $this->namespace,
  38              '/' . $this->rest_base . '/(?P<id>[\d]+)/post-process',
  39              array(
  40                  'methods'             => WP_REST_Server::CREATABLE,
  41                  'callback'            => array( $this, 'post_process_item' ),
  42                  'permission_callback' => array( $this, 'post_process_item_permissions_check' ),
  43                  'args'                => array(
  44                      'id'     => array(
  45                          'description' => __( 'Unique identifier for the attachment.' ),
  46                          'type'        => 'integer',
  47                      ),
  48                      'action' => array(
  49                          'type'     => 'string',
  50                          'enum'     => array( 'create-image-subsizes' ),
  51                          'required' => true,
  52                      ),
  53                  ),
  54              )
  55          );
  56          register_rest_route(
  57              $this->namespace,
  58              '/' . $this->rest_base . '/(?P<id>[\d]+)/edit',
  59              array(
  60                  'methods'             => WP_REST_Server::CREATABLE,
  61                  'callback'            => array( $this, 'edit_media_item' ),
  62                  'permission_callback' => array( $this, 'edit_media_item_permissions_check' ),
  63                  'args'                => $this->get_edit_media_item_args(),
  64              )
  65          );
  66  
  67          if ( wp_is_client_side_media_processing_enabled() ) {
  68              $valid_image_sizes = array_keys( wp_get_registered_image_subsizes() );
  69              // Special case to set 'original_image' in attachment metadata.
  70              $valid_image_sizes[] = 'original';
  71              // Used for PDF thumbnails.
  72              $valid_image_sizes[] = 'full';
  73              // Client-side big image threshold: sideload the scaled version.
  74              $valid_image_sizes[] = 'scaled';
  75  
  76              register_rest_route(
  77                  $this->namespace,
  78                  '/' . $this->rest_base . '/(?P<id>[\d]+)/sideload',
  79                  array(
  80                      array(
  81                          'methods'             => WP_REST_Server::CREATABLE,
  82                          'callback'            => array( $this, 'sideload_item' ),
  83                          'permission_callback' => array( $this, 'sideload_item_permissions_check' ),
  84                          'args'                => array(
  85                              'id'             => array(
  86                                  'description' => __( 'Unique identifier for the attachment.' ),
  87                                  'type'        => 'integer',
  88                              ),
  89                              'image_size'     => array(
  90                                  'description' => __( 'Image size.' ),
  91                                  'type'        => 'string',
  92                                  'enum'        => $valid_image_sizes,
  93                                  'required'    => true,
  94                              ),
  95                              'convert_format' => array(
  96                                  'type'        => 'boolean',
  97                                  'default'     => true,
  98                                  'description' => __( 'Whether to convert image formats.' ),
  99                              ),
 100                          ),
 101                      ),
 102                      'allow_batch' => $this->allow_batch,
 103                      'schema'      => array( $this, 'get_public_item_schema' ),
 104                  )
 105              );
 106  
 107              register_rest_route(
 108                  $this->namespace,
 109                  '/' . $this->rest_base . '/(?P<id>[\d]+)/finalize',
 110                  array(
 111                      array(
 112                          'methods'             => WP_REST_Server::CREATABLE,
 113                          'callback'            => array( $this, 'finalize_item' ),
 114                          'permission_callback' => array( $this, 'edit_media_item_permissions_check' ),
 115                          'args'                => array(
 116                              'id' => array(
 117                                  'description' => __( 'Unique identifier for the attachment.' ),
 118                                  'type'        => 'integer',
 119                              ),
 120                          ),
 121                      ),
 122                      'allow_batch' => $this->allow_batch,
 123                      'schema'      => array( $this, 'get_public_item_schema' ),
 124                  )
 125              );
 126          }
 127      }
 128  
 129      /**
 130       * Retrieves the query params for the attachments collection.
 131       *
 132       * @since 7.1.0
 133       *
 134       * @param string $method Optional. HTTP method of the request.
 135       *                       The arguments for `CREATABLE` requests are
 136       *                       checked for required values and may fall-back to a given default.
 137       *                       Default WP_REST_Server::CREATABLE.
 138       * @return array<string, array<string, mixed>> Endpoint arguments.
 139       */
 140  	public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CREATABLE ) {
 141          $args = parent::get_endpoint_args_for_item_schema( $method );
 142  
 143          if ( WP_REST_Server::CREATABLE === $method && wp_is_client_side_media_processing_enabled() ) {
 144              $args['generate_sub_sizes'] = array(
 145                  'type'        => 'boolean',
 146                  'default'     => true,
 147                  'description' => __( 'Whether to generate image sub sizes.' ),
 148              );
 149              $args['convert_format']     = array(
 150                  'type'        => 'boolean',
 151                  'default'     => true,
 152                  'description' => __( 'Whether to convert image formats.' ),
 153              );
 154          }
 155  
 156          return $args;
 157      }
 158  
 159      /**
 160       * Determines the allowed query_vars for a get_items() response and
 161       * prepares for WP_Query.
 162       *
 163       * @since 4.7.0
 164       * @since 6.9.0 Extends the `media_type` and `mime_type` request arguments to support array values.
 165       *
 166       * @param array           $prepared_args Optional. Array of prepared arguments. Default empty array.
 167       * @param WP_REST_Request $request       Optional. Request to prepare items for.
 168       * @return array Array of query arguments.
 169       */
 170  	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
 171          $query_args = parent::prepare_items_query( $prepared_args, $request );
 172  
 173          if ( empty( $query_args['post_status'] ) ) {
 174              $query_args['post_status'] = 'inherit';
 175          }
 176  
 177          $all_mime_types = array();
 178          $media_types    = $this->get_media_types();
 179  
 180          if ( ! empty( $request['media_type'] ) && is_array( $request['media_type'] ) ) {
 181              foreach ( $request['media_type'] as $type ) {
 182                  if ( isset( $media_types[ $type ] ) ) {
 183                      $all_mime_types = array_merge( $all_mime_types, $media_types[ $type ] );
 184                  }
 185              }
 186          }
 187  
 188          if ( ! empty( $request['mime_type'] ) && is_array( $request['mime_type'] ) ) {
 189              foreach ( $request['mime_type'] as $mime_type ) {
 190                  $parts = explode( '/', $mime_type );
 191                  if ( isset( $media_types[ $parts[0] ] ) && in_array( $mime_type, $media_types[ $parts[0] ], true ) ) {
 192                      $all_mime_types[] = $mime_type;
 193                  }
 194              }
 195          }
 196  
 197          if ( ! empty( $all_mime_types ) ) {
 198              $query_args['post_mime_type'] = array_values( array_unique( $all_mime_types ) );
 199          }
 200  
 201          // Filter query clauses to include filenames.
 202          if ( isset( $query_args['s'] ) ) {
 203              add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' );
 204          }
 205  
 206          return $query_args;
 207      }
 208  
 209      /**
 210       * Checks if a given request has access to create an attachment.
 211       *
 212       * @since 4.7.0
 213       *
 214       * @param WP_REST_Request $request Full details about the request.
 215       * @return true|WP_Error Boolean true if the attachment may be created, or a WP_Error if not.
 216       */
 217  	public function create_item_permissions_check( $request ) {
 218          $ret = parent::create_item_permissions_check( $request );
 219  
 220          if ( ! $ret || is_wp_error( $ret ) ) {
 221              return $ret;
 222          }
 223  
 224          if ( ! current_user_can( 'upload_files' ) ) {
 225              return new WP_Error(
 226                  'rest_cannot_create',
 227                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 228                  array( 'status' => 400 )
 229              );
 230          }
 231  
 232          // Attaching media to a post requires ability to edit said post.
 233          if ( ! empty( $request['post'] ) && ! current_user_can( 'edit_post', (int) $request['post'] ) ) {
 234              return new WP_Error(
 235                  'rest_cannot_edit',
 236                  __( 'Sorry, you are not allowed to upload media to this post.' ),
 237                  array( 'status' => rest_authorization_required_code() )
 238              );
 239          }
 240          $files = $request->get_file_params();
 241  
 242          /**
 243           * Filter whether the server should prevent uploads for image types it doesn't support. Default true.
 244           *
 245           * Developers can use this filter to enable uploads of certain image types. By default image types that are not
 246           * supported by the server are prevented from being uploaded.
 247           *
 248           * @since 6.8.0
 249           *
 250           * @param bool        $check_mime Whether to prevent uploads of unsupported image types.
 251           * @param string|null $mime_type  The mime type of the file being uploaded (if available).
 252           */
 253          $prevent_unsupported_uploads = apply_filters( 'wp_prevent_unsupported_mime_type_uploads', true, $files['file']['type'] ?? null );
 254  
 255          // When the client handles image processing (generate_sub_sizes is false),
 256          // skip the server-side image editor support check.
 257          if ( false === $request['generate_sub_sizes'] ) {
 258              $prevent_unsupported_uploads = false;
 259          }
 260  
 261          // If the upload is an image, check if the server can handle the mime type.
 262          if (
 263              $prevent_unsupported_uploads &&
 264              isset( $files['file']['type'] ) &&
 265              str_starts_with( $files['file']['type'], 'image/' )
 266          ) {
 267              // List of non-resizable image formats.
 268              $editor_non_resizable_formats = array(
 269                  'image/svg+xml',
 270              );
 271  
 272              // Check if the image editor supports the type or ignore if it isn't a format resizable by an editor.
 273              if (
 274                  ! in_array( $files['file']['type'], $editor_non_resizable_formats, true ) &&
 275                  ! wp_image_editor_supports( array( 'mime_type' => $files['file']['type'] ) )
 276              ) {
 277                  return new WP_Error(
 278                      'rest_upload_image_type_not_supported',
 279                      __( 'The web server cannot generate responsive image sizes for this image. Convert it to JPEG or PNG before uploading.' ),
 280                      array( 'status' => 400 )
 281                  );
 282              }
 283          }
 284  
 285          return true;
 286      }
 287  
 288      /**
 289       * Creates a single attachment.
 290       *
 291       * @since 4.7.0
 292       * @since 7.1.0 Added `generate_sub_sizes` and `convert_format` parameters.
 293       *
 294       * @param WP_REST_Request $request Full details about the request.
 295       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 296       */
 297  	public function create_item( $request ) {
 298          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 299              return new WP_Error(
 300                  'rest_invalid_param',
 301                  __( 'Invalid parent type.' ),
 302                  array( 'status' => 400 )
 303              );
 304          }
 305  
 306          // Handle generate_sub_sizes parameter.
 307          if ( false === $request['generate_sub_sizes'] ) {
 308              add_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 );
 309              add_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
 310              // Disable server-side EXIF rotation so the client can handle it.
 311              // This preserves the original orientation value in the metadata.
 312              add_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 );
 313          }
 314  
 315          // Handle convert_format parameter.
 316          if ( false === $request['convert_format'] ) {
 317              add_filter( 'image_editor_output_format', '__return_empty_array', 100 );
 318          }
 319  
 320          $insert = $this->insert_attachment( $request );
 321  
 322          if ( is_wp_error( $insert ) ) {
 323              $this->remove_client_side_media_processing_filters();
 324              return $insert;
 325          }
 326  
 327          $schema = $this->get_item_schema();
 328  
 329          // Extract by name.
 330          $attachment_id = $insert['attachment_id'];
 331          $file          = $insert['file'];
 332  
 333          if ( isset( $request['alt_text'] ) ) {
 334              update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
 335          }
 336  
 337          if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
 338              $thumbnail_update = $this->handle_featured_media( $request['featured_media'], $attachment_id );
 339  
 340              if ( is_wp_error( $thumbnail_update ) ) {
 341                  $this->remove_client_side_media_processing_filters();
 342                  return $thumbnail_update;
 343              }
 344          }
 345  
 346          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 347              $meta_update = $this->meta->update_value( $request['meta'], $attachment_id );
 348  
 349              if ( is_wp_error( $meta_update ) ) {
 350                  $this->remove_client_side_media_processing_filters();
 351                  return $meta_update;
 352              }
 353          }
 354  
 355          $attachment    = get_post( $attachment_id );
 356          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 357  
 358          if ( is_wp_error( $fields_update ) ) {
 359              $this->remove_client_side_media_processing_filters();
 360              return $fields_update;
 361          }
 362  
 363          $terms_update = $this->handle_terms( $attachment_id, $request );
 364  
 365          if ( is_wp_error( $terms_update ) ) {
 366              $this->remove_client_side_media_processing_filters();
 367              return $terms_update;
 368          }
 369  
 370          $request->set_param( 'context', 'edit' );
 371  
 372          /**
 373           * Fires after a single attachment is completely created or updated via the REST API.
 374           *
 375           * @since 5.0.0
 376           *
 377           * @param WP_Post         $attachment Inserted or updated attachment object.
 378           * @param WP_REST_Request $request    Request object.
 379           * @param bool            $creating   True when creating an attachment, false when updating.
 380           */
 381          do_action( 'rest_after_insert_attachment', $attachment, $request, true );
 382  
 383          wp_after_insert_post( $attachment, false, null );
 384  
 385          if ( wp_is_serving_rest_request() ) {
 386              /*
 387               * Set a custom header with the attachment_id.
 388               * Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
 389               */
 390              header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id );
 391          }
 392  
 393          // Include media and image functions to get access to wp_generate_attachment_metadata().
 394          require_once  ABSPATH . 'wp-admin/includes/media.php';
 395          require_once  ABSPATH . 'wp-admin/includes/image.php';
 396  
 397          /*
 398           * Post-process the upload (create image sub-sizes, make PDF thumbnails, etc.) and insert attachment meta.
 399           * At this point the server may run out of resources and post-processing of uploaded images may fail.
 400           */
 401          wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
 402  
 403          $this->remove_client_side_media_processing_filters();
 404  
 405          $response = $this->prepare_item_for_response( $attachment, $request );
 406          $response = rest_ensure_response( $response );
 407          $response->set_status( 201 );
 408          $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $attachment_id ) ) );
 409  
 410          return $response;
 411      }
 412  
 413      /**
 414       * Removes filters added for client-side media processing.
 415       *
 416       * @since 7.1.0
 417       */
 418  	private function remove_client_side_media_processing_filters(): void {
 419          remove_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 );
 420          remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
 421          remove_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 );
 422          remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );
 423      }
 424  
 425      /**
 426       * Inserts the attachment post in the database. Does not update the attachment meta.
 427       *
 428       * @since 5.3.0
 429       *
 430       * @param WP_REST_Request $request
 431       * @return array|WP_Error
 432       */
 433  	protected function insert_attachment( $request ) {
 434          // Get the file via $_FILES or raw data.
 435          $files   = $request->get_file_params();
 436          $headers = $request->get_headers();
 437  
 438          $time = null;
 439  
 440          // Matches logic in media_handle_upload().
 441          if ( ! empty( $request['post'] ) ) {
 442              $post = get_post( $request['post'] );
 443              // The post date doesn't usually matter for pages, so don't backdate this upload.
 444              if ( $post && 'page' !== $post->post_type && substr( $post->post_date, 0, 4 ) > 0 ) {
 445                  $time = $post->post_date;
 446              }
 447          }
 448  
 449          if ( ! empty( $files ) ) {
 450              $file = $this->upload_from_file( $files, $headers, $time );
 451          } else {
 452              $file = $this->upload_from_data( $request->get_body(), $headers, $time );
 453          }
 454  
 455          if ( is_wp_error( $file ) ) {
 456              return $file;
 457          }
 458  
 459          $name       = wp_basename( $file['file'] );
 460          $name_parts = pathinfo( $name );
 461          $name       = trim( substr( $name, 0, -( 1 + strlen( $name_parts['extension'] ) ) ) );
 462  
 463          $url  = $file['url'];
 464          $type = $file['type'];
 465          $file = $file['file'];
 466          $alt  = '';
 467  
 468          // Include image functions to get access to wp_read_image_metadata().
 469          require_once  ABSPATH . 'wp-admin/includes/image.php';
 470  
 471          // Use image exif/iptc data for title and caption defaults if possible.
 472          $image_meta = wp_read_image_metadata( $file );
 473  
 474          if ( ! empty( $image_meta ) ) {
 475              if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
 476                  $request['title'] = $image_meta['title'];
 477              }
 478  
 479              if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
 480                  $request['caption'] = $image_meta['caption'];
 481              }
 482  
 483              if ( empty( $request['alt'] ) && trim( $image_meta['alt'] ) ) {
 484                  $alt = $image_meta['alt'];
 485              }
 486          }
 487  
 488          $attachment = $this->prepare_item_for_database( $request );
 489  
 490          $attachment->post_mime_type = $type;
 491          $attachment->guid           = $url;
 492  
 493          // If the title was not set, use the original filename.
 494          if ( empty( $attachment->post_title ) && ! empty( $files['file']['name'] ) ) {
 495              // Remove the file extension (after the last `.`)
 496              $tmp_title = substr( $files['file']['name'], 0, strrpos( $files['file']['name'], '.' ) );
 497  
 498              if ( ! empty( $tmp_title ) ) {
 499                  $attachment->post_title = $tmp_title;
 500              }
 501          }
 502  
 503          // Fall back to the original approach.
 504          if ( empty( $attachment->post_title ) ) {
 505              $attachment->post_title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) );
 506          }
 507  
 508          // $post_parent is inherited from $attachment['post_parent'].
 509          $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true, false );
 510  
 511          if ( trim( $alt ) ) {
 512              update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $alt ) );
 513          }
 514  
 515          if ( is_wp_error( $id ) ) {
 516              if ( 'db_update_error' === $id->get_error_code() ) {
 517                  $id->add_data( array( 'status' => 500 ) );
 518              } else {
 519                  $id->add_data( array( 'status' => 400 ) );
 520              }
 521  
 522              return $id;
 523          }
 524  
 525          $attachment = get_post( $id );
 526  
 527          /**
 528           * Fires after a single attachment is created or updated via the REST API.
 529           *
 530           * @since 4.7.0
 531           *
 532           * @param WP_Post         $attachment Inserted or updated attachment object.
 533           * @param WP_REST_Request $request    The request sent to the API.
 534           * @param bool            $creating   True when creating an attachment, false when updating.
 535           */
 536          do_action( 'rest_insert_attachment', $attachment, $request, true );
 537  
 538          return array(
 539              'attachment_id' => $id,
 540              'file'          => $file,
 541          );
 542      }
 543  
 544      /**
 545       * Determines the featured media based on a request param.
 546       *
 547       * @since 6.5.0
 548       *
 549       * @param int $featured_media Featured Media ID.
 550       * @param int $post_id        Post ID.
 551       * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
 552       */
 553  	protected function handle_featured_media( $featured_media, $post_id ) {
 554          $post_type         = get_post_type( $post_id );
 555          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' );
 556  
 557          // Similar check as in wp_insert_post().
 558          if ( ! $thumbnail_support && get_post_mime_type( $post_id ) ) {
 559              if ( wp_attachment_is( 'audio', $post_id ) ) {
 560                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
 561              } elseif ( wp_attachment_is( 'video', $post_id ) ) {
 562                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
 563              }
 564          }
 565  
 566          if ( $thumbnail_support ) {
 567              return parent::handle_featured_media( $featured_media, $post_id );
 568          }
 569  
 570          return new WP_Error(
 571              'rest_no_featured_media',
 572              sprintf(
 573                  /* translators: %s: attachment mime type */
 574                  __( 'This site does not support post thumbnails on attachments with MIME type %s.' ),
 575                  get_post_mime_type( $post_id )
 576              ),
 577              array( 'status' => 400 )
 578          );
 579      }
 580  
 581      /**
 582       * Updates a single attachment.
 583       *
 584       * @since 4.7.0
 585       *
 586       * @param WP_REST_Request $request Full details about the request.
 587       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 588       */
 589  	public function update_item( $request ) {
 590          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 591              return new WP_Error(
 592                  'rest_invalid_param',
 593                  __( 'Invalid parent type.' ),
 594                  array( 'status' => 400 )
 595              );
 596          }
 597  
 598          $attachment_before = get_post( $request['id'] );
 599          $response          = parent::update_item( $request );
 600  
 601          if ( is_wp_error( $response ) ) {
 602              return $response;
 603          }
 604  
 605          $response = rest_ensure_response( $response );
 606          $data     = $response->get_data();
 607  
 608          if ( isset( $request['alt_text'] ) ) {
 609              update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
 610          }
 611  
 612          $attachment = get_post( $request['id'] );
 613  
 614          if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
 615              $thumbnail_update = $this->handle_featured_media( $request['featured_media'], $attachment->ID );
 616  
 617              if ( is_wp_error( $thumbnail_update ) ) {
 618                  return $thumbnail_update;
 619              }
 620          }
 621  
 622          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 623  
 624          if ( is_wp_error( $fields_update ) ) {
 625              return $fields_update;
 626          }
 627  
 628          $request->set_param( 'context', 'edit' );
 629  
 630          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
 631          do_action( 'rest_after_insert_attachment', $attachment, $request, false );
 632  
 633          wp_after_insert_post( $attachment, true, $attachment_before );
 634  
 635          $response = $this->prepare_item_for_response( $attachment, $request );
 636          $response = rest_ensure_response( $response );
 637  
 638          return $response;
 639      }
 640  
 641      /**
 642       * Performs post-processing on an attachment.
 643       *
 644       * @since 5.3.0
 645       *
 646       * @param WP_REST_Request $request Full details about the request.
 647       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 648       */
 649  	public function post_process_item( $request ) {
 650          switch ( $request['action'] ) {
 651              case 'create-image-subsizes':
 652                  require_once  ABSPATH . 'wp-admin/includes/image.php';
 653                  wp_update_image_subsizes( $request['id'] );
 654                  break;
 655          }
 656  
 657          $request['context'] = 'edit';
 658  
 659          return $this->prepare_item_for_response( get_post( $request['id'] ), $request );
 660      }
 661  
 662      /**
 663       * Checks if a given request can perform post-processing on an attachment.
 664       *
 665       * @since 5.3.0
 666       *
 667       * @param WP_REST_Request $request Full details about the request.
 668       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
 669       */
 670  	public function post_process_item_permissions_check( $request ) {
 671          return $this->update_item_permissions_check( $request );
 672      }
 673  
 674      /**
 675       * Checks if a given request has access to editing media.
 676       *
 677       * @since 5.5.0
 678       *
 679       * @param WP_REST_Request $request Full details about the request.
 680       * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
 681       */
 682  	public function edit_media_item_permissions_check( $request ) {
 683          if ( ! current_user_can( 'upload_files' ) ) {
 684              return new WP_Error(
 685                  'rest_cannot_edit_image',
 686                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 687                  array( 'status' => rest_authorization_required_code() )
 688              );
 689          }
 690  
 691          return $this->update_item_permissions_check( $request );
 692      }
 693  
 694      /**
 695       * Applies edits to a media item and creates a new attachment record.
 696       *
 697       * @since 5.5.0
 698       * @since 6.9.0 Adds flips capability and editable fields for the newly-created attachment post.
 699       *
 700       * @param WP_REST_Request $request Full details about the request.
 701       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 702       */
 703  	public function edit_media_item( $request ) {
 704          require_once  ABSPATH . 'wp-admin/includes/image.php';
 705  
 706          $attachment_id = $request['id'];
 707  
 708          // This also confirms the attachment is an image.
 709          $image_file = wp_get_original_image_path( $attachment_id );
 710          $image_meta = wp_get_attachment_metadata( $attachment_id );
 711  
 712          if (
 713              ! $image_meta ||
 714              ! $image_file ||
 715              ! wp_image_file_matches_image_meta( $request['src'], $image_meta, $attachment_id )
 716          ) {
 717              return new WP_Error(
 718                  'rest_unknown_attachment',
 719                  __( 'Unable to get meta information for file.' ),
 720                  array( 'status' => 404 )
 721              );
 722          }
 723  
 724          $supported_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif', 'image/heic' );
 725          $mime_type       = get_post_mime_type( $attachment_id );
 726          if ( ! in_array( $mime_type, $supported_types, true ) ) {
 727              return new WP_Error(
 728                  'rest_cannot_edit_file_type',
 729                  __( 'This type of file cannot be edited.' ),
 730                  array( 'status' => 400 )
 731              );
 732          }
 733  
 734          // The `modifiers` param takes precedence over the older format.
 735          if ( isset( $request['modifiers'] ) ) {
 736              $modifiers = $request['modifiers'];
 737          } else {
 738              $modifiers = array();
 739  
 740              if ( isset( $request['flip']['horizontal'] ) || isset( $request['flip']['vertical'] ) ) {
 741                  $flip_args = array(
 742                      'vertical'   => isset( $request['flip']['vertical'] ) ? (bool) $request['flip']['vertical'] : false,
 743                      'horizontal' => isset( $request['flip']['horizontal'] ) ? (bool) $request['flip']['horizontal'] : false,
 744                  );
 745  
 746                  $modifiers[] = array(
 747                      'type' => 'flip',
 748                      'args' => array(
 749                          'flip' => $flip_args,
 750                      ),
 751                  );
 752              }
 753  
 754              if ( ! empty( $request['rotation'] ) ) {
 755                  $modifiers[] = array(
 756                      'type' => 'rotate',
 757                      'args' => array(
 758                          'angle' => $request['rotation'],
 759                      ),
 760                  );
 761              }
 762  
 763              if ( isset( $request['x'], $request['y'], $request['width'], $request['height'] ) ) {
 764                  $modifiers[] = array(
 765                      'type' => 'crop',
 766                      'args' => array(
 767                          'left'   => $request['x'],
 768                          'top'    => $request['y'],
 769                          'width'  => $request['width'],
 770                          'height' => $request['height'],
 771                      ),
 772                  );
 773              }
 774  
 775              if ( 0 === count( $modifiers ) ) {
 776                  return new WP_Error(
 777                      'rest_image_not_edited',
 778                      __( 'The image was not edited. Edit the image before applying the changes.' ),
 779                      array( 'status' => 400 )
 780                  );
 781              }
 782          }
 783  
 784          /*
 785           * If the file doesn't exist, attempt a URL fopen on the src link.
 786           * This can occur with certain file replication plugins.
 787           * Keep the original file path to get a modified name later.
 788           */
 789          $image_file_to_edit = $image_file;
 790          if ( ! file_exists( $image_file_to_edit ) ) {
 791              $image_file_to_edit = _load_image_to_edit_path( $attachment_id );
 792          }
 793  
 794          $image_editor = wp_get_image_editor( $image_file_to_edit );
 795  
 796          if ( is_wp_error( $image_editor ) ) {
 797              return new WP_Error(
 798                  'rest_unknown_image_file_type',
 799                  __( 'Unable to edit this image.' ),
 800                  array( 'status' => 500 )
 801              );
 802          }
 803  
 804          foreach ( $modifiers as $modifier ) {
 805              $args = $modifier['args'];
 806              switch ( $modifier['type'] ) {
 807                  case 'flip':
 808                      /*
 809                       * Flips the current image.
 810                       * The vertical flip is the first argument (flip along horizontal axis), the horizontal flip is the second argument (flip along vertical axis).
 811                       * See: WP_Image_Editor::flip()
 812                       */
 813                      $result = $image_editor->flip( $args['flip']['vertical'], $args['flip']['horizontal'] );
 814                      if ( is_wp_error( $result ) ) {
 815                          return new WP_Error(
 816                              'rest_image_flip_failed',
 817                              __( 'Unable to flip this image.' ),
 818                              array( 'status' => 500 )
 819                          );
 820                      }
 821                      break;
 822                  case 'rotate':
 823                      // Rotation direction: clockwise vs. counterclockwise.
 824                      $rotate = 0 - $args['angle'];
 825  
 826                      if ( 0 !== $rotate ) {
 827                          $result = $image_editor->rotate( $rotate );
 828  
 829                          if ( is_wp_error( $result ) ) {
 830                              return new WP_Error(
 831                                  'rest_image_rotation_failed',
 832                                  __( 'Unable to rotate this image.' ),
 833                                  array( 'status' => 500 )
 834                              );
 835                          }
 836                      }
 837  
 838                      break;
 839  
 840                  case 'crop':
 841                      $size = $image_editor->get_size();
 842  
 843                      $crop_x = (int) round( ( $size['width'] * $args['left'] ) / 100.0 );
 844                      $crop_y = (int) round( ( $size['height'] * $args['top'] ) / 100.0 );
 845                      $width  = (int) round( ( $size['width'] * $args['width'] ) / 100.0 );
 846                      $height = (int) round( ( $size['height'] * $args['height'] ) / 100.0 );
 847  
 848                      if ( $size['width'] !== $width || $size['height'] !== $height ) {
 849                          $result = $image_editor->crop( $crop_x, $crop_y, $width, $height );
 850  
 851                          if ( is_wp_error( $result ) ) {
 852                              return new WP_Error(
 853                                  'rest_image_crop_failed',
 854                                  __( 'Unable to crop this image.' ),
 855                                  array( 'status' => 500 )
 856                              );
 857                          }
 858                      }
 859  
 860                      break;
 861  
 862              }
 863          }
 864  
 865          // Calculate the file name.
 866          $image_ext  = pathinfo( $image_file, PATHINFO_EXTENSION );
 867          $image_name = wp_basename( $image_file, ".{$image_ext}" );
 868  
 869          /*
 870           * Do not append multiple `-edited` to the file name.
 871           * The user may be editing a previously edited image.
 872           */
 873          if ( preg_match( '/-edited(-\d+)?$/', $image_name ) ) {
 874              // Remove any `-1`, `-2`, etc. `wp_unique_filename()` will add the proper number.
 875              $image_name = preg_replace( '/-edited(-\d+)?$/', '-edited', $image_name );
 876          } else {
 877              // Append `-edited` before the extension.
 878              $image_name .= '-edited';
 879          }
 880  
 881          $filename = "{$image_name}.{$image_ext}";
 882  
 883          // Create the uploads subdirectory if needed.
 884          $uploads = wp_upload_dir();
 885  
 886          // Make the file name unique in the (new) upload directory.
 887          $filename = wp_unique_filename( $uploads['path'], $filename );
 888  
 889          // Save to disk.
 890          $saved = $image_editor->save( $uploads['path'] . "/$filename" );
 891  
 892          if ( is_wp_error( $saved ) ) {
 893              return $saved;
 894          }
 895  
 896          // Grab original attachment post so we can use it to set defaults.
 897          $original_attachment_post = get_post( $attachment_id );
 898  
 899          // Check request fields and assign default values.
 900          $new_attachment_post                 = $this->prepare_item_for_database( $request );
 901          $new_attachment_post->post_mime_type = $saved['mime-type'];
 902          $new_attachment_post->guid           = $uploads['url'] . "/$filename";
 903  
 904          // Unset ID so wp_insert_attachment generates a new ID.
 905          unset( $new_attachment_post->ID );
 906  
 907          // Set new attachment post title with fallbacks.
 908          $new_attachment_post->post_title = $new_attachment_post->post_title ?? $original_attachment_post->post_title ?? $image_name;
 909  
 910          // Set new attachment post caption (post_excerpt).
 911          $new_attachment_post->post_excerpt = $new_attachment_post->post_excerpt ?? $original_attachment_post->post_excerpt ?? '';
 912  
 913          // Set new attachment post description (post_content) with fallbacks.
 914          $new_attachment_post->post_content = $new_attachment_post->post_content ?? $original_attachment_post->post_content ?? '';
 915  
 916          // Set post parent if set in request, else the default of `0` (no parent).
 917          $new_attachment_post->post_parent = $new_attachment_post->post_parent ?? 0;
 918  
 919          // Insert the new attachment post.
 920          $new_attachment_id = wp_insert_attachment( wp_slash( (array) $new_attachment_post ), $saved['path'], 0, true );
 921  
 922          if ( is_wp_error( $new_attachment_id ) ) {
 923              if ( 'db_update_error' === $new_attachment_id->get_error_code() ) {
 924                  $new_attachment_id->add_data( array( 'status' => 500 ) );
 925              } else {
 926                  $new_attachment_id->add_data( array( 'status' => 400 ) );
 927              }
 928  
 929              return $new_attachment_id;
 930          }
 931  
 932          // First, try to use the alt text from the request. If not set, copy the image alt text from the original attachment.
 933          $image_alt = isset( $request['alt_text'] ) ? sanitize_text_field( $request['alt_text'] ) : get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
 934  
 935          if ( ! empty( $image_alt ) ) {
 936              // update_post_meta() expects slashed.
 937              update_post_meta( $new_attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
 938          }
 939  
 940          if ( wp_is_serving_rest_request() ) {
 941              /*
 942               * Set a custom header with the attachment_id.
 943               * Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
 944               */
 945              header( 'X-WP-Upload-Attachment-ID: ' . $new_attachment_id );
 946          }
 947  
 948          // Generate image sub-sizes and meta.
 949          $new_image_meta = wp_generate_attachment_metadata( $new_attachment_id, $saved['path'] );
 950  
 951          // Copy the EXIF metadata from the original attachment if not generated for the edited image.
 952          if ( isset( $image_meta['image_meta'] ) && isset( $new_image_meta['image_meta'] ) && is_array( $new_image_meta['image_meta'] ) ) {
 953              // Merge but skip empty values.
 954              foreach ( (array) $image_meta['image_meta'] as $key => $value ) {
 955                  if ( empty( $new_image_meta['image_meta'][ $key ] ) && ! empty( $value ) ) {
 956                      $new_image_meta['image_meta'][ $key ] = $value;
 957                  }
 958              }
 959          }
 960  
 961          // Reset orientation. At this point the image is edited and orientation is correct.
 962          if ( ! empty( $new_image_meta['image_meta']['orientation'] ) ) {
 963              $new_image_meta['image_meta']['orientation'] = 1;
 964          }
 965  
 966          // The attachment_id may change if the site is exported and imported.
 967          $new_image_meta['parent_image'] = array(
 968              'attachment_id' => $attachment_id,
 969              // Path to the originally uploaded image file relative to the uploads directory.
 970              'file'          => _wp_relative_upload_path( $image_file ),
 971          );
 972  
 973          /**
 974           * Filters the meta data for the new image created by editing an existing image.
 975           *
 976           * @since 5.5.0
 977           *
 978           * @param array $new_image_meta    Meta data for the new image.
 979           * @param int   $new_attachment_id Attachment post ID for the new image.
 980           * @param int   $attachment_id     Attachment post ID for the edited (parent) image.
 981           */
 982          $new_image_meta = apply_filters( 'wp_edited_image_metadata', $new_image_meta, $new_attachment_id, $attachment_id );
 983  
 984          wp_update_attachment_metadata( $new_attachment_id, $new_image_meta );
 985  
 986          $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request );
 987          $response->set_status( 201 );
 988          $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) );
 989  
 990          return $response;
 991      }
 992  
 993      /**
 994       * Prepares a single attachment for create or update.
 995       *
 996       * @since 4.7.0
 997       *
 998       * @param WP_REST_Request $request Request object.
 999       * @return stdClass|WP_Error Post object.
1000       */
1001  	protected function prepare_item_for_database( $request ) {
1002          $prepared_attachment = parent::prepare_item_for_database( $request );
1003  
1004          // Attachment caption (post_excerpt internally).
1005          if ( isset( $request['caption'] ) ) {
1006              if ( is_string( $request['caption'] ) ) {
1007                  $prepared_attachment->post_excerpt = $request['caption'];
1008              } elseif ( isset( $request['caption']['raw'] ) ) {
1009                  $prepared_attachment->post_excerpt = $request['caption']['raw'];
1010              }
1011          }
1012  
1013          // Attachment description (post_content internally).
1014          if ( isset( $request['description'] ) ) {
1015              if ( is_string( $request['description'] ) ) {
1016                  $prepared_attachment->post_content = $request['description'];
1017              } elseif ( isset( $request['description']['raw'] ) ) {
1018                  $prepared_attachment->post_content = $request['description']['raw'];
1019              }
1020          }
1021  
1022          if ( isset( $request['post'] ) ) {
1023              $prepared_attachment->post_parent = (int) $request['post'];
1024          }
1025  
1026          return $prepared_attachment;
1027      }
1028  
1029      /**
1030       * Prepares a single attachment output for response.
1031       *
1032       * @since 4.7.0
1033       * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
1034       *
1035       * @param WP_Post         $item    Attachment object.
1036       * @param WP_REST_Request $request Request object.
1037       * @return WP_REST_Response Response object.
1038       */
1039  	public function prepare_item_for_response( $item, $request ) {
1040          // Restores the more descriptive, specific name for use within this method.
1041          $post = $item;
1042  
1043          $response = parent::prepare_item_for_response( $post, $request );
1044          $fields   = $this->get_fields_for_response( $request );
1045          $data     = $response->get_data();
1046  
1047          if ( in_array( 'description', $fields, true ) ) {
1048              $data['description'] = array(
1049                  'raw'      => $post->post_content,
1050                  /** This filter is documented in wp-includes/post-template.php */
1051                  'rendered' => apply_filters( 'the_content', $post->post_content ),
1052              );
1053          }
1054  
1055          if ( in_array( 'caption', $fields, true ) ) {
1056              /** This filter is documented in wp-includes/post-template.php */
1057              $caption = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
1058  
1059              /** This filter is documented in wp-includes/post-template.php */
1060              $caption = apply_filters( 'the_excerpt', $caption );
1061  
1062              $data['caption'] = array(
1063                  'raw'      => $post->post_excerpt,
1064                  'rendered' => $caption,
1065              );
1066          }
1067  
1068          if ( in_array( 'alt_text', $fields, true ) ) {
1069              $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
1070          }
1071  
1072          if ( in_array( 'media_type', $fields, true ) ) {
1073              $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
1074          }
1075  
1076          if ( in_array( 'mime_type', $fields, true ) ) {
1077              $data['mime_type'] = $post->post_mime_type;
1078          }
1079  
1080          if ( in_array( 'media_details', $fields, true ) ) {
1081              $data['media_details'] = wp_get_attachment_metadata( $post->ID );
1082  
1083              // Ensure empty details is an empty object.
1084              if ( empty( $data['media_details'] ) ) {
1085                  $data['media_details'] = new stdClass();
1086              } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
1087  
1088                  foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
1089  
1090                      if ( isset( $size_data['mime-type'] ) ) {
1091                          $size_data['mime_type'] = $size_data['mime-type'];
1092                          unset( $size_data['mime-type'] );
1093                      }
1094  
1095                      // Use the same method image_downsize() does.
1096                      $image_src = wp_get_attachment_image_src( $post->ID, $size );
1097                      if ( ! $image_src ) {
1098                          continue;
1099                      }
1100  
1101                      $size_data['source_url'] = $image_src[0];
1102                  }
1103  
1104                  $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
1105  
1106                  if ( ! empty( $full_src ) ) {
1107                      $data['media_details']['sizes']['full'] = array(
1108                          'file'       => wp_basename( $full_src[0] ),
1109                          'width'      => $full_src[1],
1110                          'height'     => $full_src[2],
1111                          'mime_type'  => $post->post_mime_type,
1112                          'source_url' => $full_src[0],
1113                      );
1114                  }
1115              } else {
1116                  $data['media_details']['sizes'] = new stdClass();
1117              }
1118          }
1119  
1120          if ( in_array( 'post', $fields, true ) ) {
1121              $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
1122          }
1123  
1124          if ( in_array( 'source_url', $fields, true ) ) {
1125              $data['source_url'] = wp_get_attachment_url( $post->ID );
1126          }
1127  
1128          if ( in_array( 'missing_image_sizes', $fields, true ) ) {
1129              require_once  ABSPATH . 'wp-admin/includes/image.php';
1130              $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) );
1131  
1132              // Handle PDFs which don't use wp_get_missing_image_subsizes().
1133              if ( empty( $data['missing_image_sizes'] ) && 'application/pdf' === get_post_mime_type( $post ) ) {
1134                  $metadata = wp_get_attachment_metadata( $post->ID, true );
1135  
1136                  if ( ! is_array( $metadata ) ) {
1137                      $metadata = array();
1138                  }
1139  
1140                  $metadata['sizes'] = $metadata['sizes'] ?? array();
1141  
1142                  $fallback_sizes = array(
1143                      'thumbnail',
1144                      'medium',
1145                      'large',
1146                  );
1147  
1148                  // The filter might have been added by ::create_item().
1149                  remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
1150  
1151                  /** This filter is documented in wp-admin/includes/image.php */
1152                  $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
1153  
1154                  $registered_sizes = wp_get_registered_image_subsizes();
1155                  $merged_sizes     = array_keys( array_intersect_key( $registered_sizes, array_flip( $fallback_sizes ) ) );
1156  
1157                  $data['missing_image_sizes'] = array_values( array_diff( $merged_sizes, array_keys( $metadata['sizes'] ) ) );
1158              }
1159          }
1160  
1161          if ( in_array( 'filename', $fields, true ) ) {
1162              $data['filename'] = $this->get_attachment_filename( $post->ID );
1163          }
1164  
1165          if ( in_array( 'filesize', $fields, true ) ) {
1166              $data['filesize'] = $this->get_attachment_filesize( $post->ID );
1167          }
1168  
1169          if ( in_array( 'exif_orientation', $fields, true ) && wp_attachment_is_image( $post ) ) {
1170              $metadata = wp_get_attachment_metadata( $post->ID, true );
1171  
1172              // Default to 1 (no rotation needed) if orientation not set.
1173              $orientation = 1;
1174  
1175              if (
1176                  is_array( $metadata ) &&
1177                  isset( $metadata['image_meta']['orientation'] ) &&
1178                  (int) $metadata['image_meta']['orientation'] > 0
1179              ) {
1180                  $orientation = (int) $metadata['image_meta']['orientation'];
1181              }
1182  
1183              $data['exif_orientation'] = $orientation;
1184          }
1185  
1186          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1187  
1188          $data = $this->filter_response_by_context( $data, $context );
1189  
1190          $links = $response->get_links();
1191  
1192          // Wrap the data in a response object.
1193          $response = rest_ensure_response( $data );
1194  
1195          foreach ( $links as $rel => $rel_links ) {
1196              foreach ( $rel_links as $link ) {
1197                  $response->add_link( $rel, $link['href'], $link['attributes'] );
1198              }
1199          }
1200  
1201          /**
1202           * Filters an attachment returned from the REST API.
1203           *
1204           * Allows modification of the attachment right before it is returned.
1205           *
1206           * @since 4.7.0
1207           *
1208           * @param WP_REST_Response $response The response object.
1209           * @param WP_Post          $post     The original attachment post.
1210           * @param WP_REST_Request  $request  Request used to generate the response.
1211           */
1212          return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
1213      }
1214  
1215      /**
1216       * Prepares attachment links for the request.
1217       *
1218       * @since 6.9.0
1219       *
1220       * @param WP_Post $post Post object.
1221       * @return array Links for the given attachment.
1222       */
1223  	protected function prepare_links( $post ) {
1224          $links = parent::prepare_links( $post );
1225  
1226          if ( ! empty( $post->post_parent ) ) {
1227              $post = get_post( $post->post_parent );
1228  
1229              if ( ! empty( $post ) ) {
1230                  $links['https://api.w.org/attached-to'] = array(
1231                      'href'       => rest_url( rest_get_route_for_post( $post ) ),
1232                      'embeddable' => true,
1233                      'post_type'  => $post->post_type,
1234                      'id'         => $post->ID,
1235                  );
1236              }
1237          }
1238  
1239          return $links;
1240      }
1241  
1242      /**
1243       * Retrieves the attachment's schema, conforming to JSON Schema.
1244       *
1245       * @since 4.7.0
1246       *
1247       * @return array Item schema as an array.
1248       */
1249  	public function get_item_schema() {
1250          if ( $this->schema ) {
1251              return $this->add_additional_fields_schema( $this->schema );
1252          }
1253  
1254          $schema = parent::get_item_schema();
1255  
1256          $schema['properties']['alt_text'] = array(
1257              'description' => __( 'Alternative text to display when attachment is not displayed.' ),
1258              'type'        => 'string',
1259              'context'     => array( 'view', 'edit', 'embed' ),
1260              'arg_options' => array(
1261                  'sanitize_callback' => 'sanitize_text_field',
1262              ),
1263          );
1264  
1265          $schema['properties']['caption'] = array(
1266              'description' => __( 'The attachment caption.' ),
1267              'type'        => 'object',
1268              'context'     => array( 'view', 'edit', 'embed' ),
1269              'arg_options' => array(
1270                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
1271                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
1272              ),
1273              'properties'  => array(
1274                  'raw'      => array(
1275                      'description' => __( 'Caption for the attachment, as it exists in the database.' ),
1276                      'type'        => 'string',
1277                      'context'     => array( 'edit' ),
1278                  ),
1279                  'rendered' => array(
1280                      'description' => __( 'HTML caption for the attachment, transformed for display.' ),
1281                      'type'        => 'string',
1282                      'context'     => array( 'view', 'edit', 'embed' ),
1283                      'readonly'    => true,
1284                  ),
1285              ),
1286          );
1287  
1288          $schema['properties']['description'] = array(
1289              'description' => __( 'The attachment description.' ),
1290              'type'        => 'object',
1291              'context'     => array( 'view', 'edit' ),
1292              'arg_options' => array(
1293                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
1294                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
1295              ),
1296              'properties'  => array(
1297                  'raw'      => array(
1298                      'description' => __( 'Description for the attachment, as it exists in the database.' ),
1299                      'type'        => 'string',
1300                      'context'     => array( 'edit' ),
1301                  ),
1302                  'rendered' => array(
1303                      'description' => __( 'HTML description for the attachment, transformed for display.' ),
1304                      'type'        => 'string',
1305                      'context'     => array( 'view', 'edit' ),
1306                      'readonly'    => true,
1307                  ),
1308              ),
1309          );
1310  
1311          $schema['properties']['media_type'] = array(
1312              'description' => __( 'Attachment type.' ),
1313              'type'        => 'string',
1314              'enum'        => array( 'image', 'file' ),
1315              'context'     => array( 'view', 'edit', 'embed' ),
1316              'readonly'    => true,
1317          );
1318  
1319          $schema['properties']['mime_type'] = array(
1320              'description' => __( 'The attachment MIME type.' ),
1321              'type'        => 'string',
1322              'context'     => array( 'view', 'edit', 'embed' ),
1323              'readonly'    => true,
1324          );
1325  
1326          $schema['properties']['media_details'] = array(
1327              'description' => __( 'Details about the media file, specific to its type.' ),
1328              'type'        => 'object',
1329              'context'     => array( 'view', 'edit', 'embed' ),
1330              'readonly'    => true,
1331          );
1332  
1333          $schema['properties']['post'] = array(
1334              'description' => __( 'The ID for the associated post of the attachment.' ),
1335              'type'        => 'integer',
1336              'context'     => array( 'view', 'edit' ),
1337          );
1338  
1339          $schema['properties']['source_url'] = array(
1340              'description' => __( 'URL to the original attachment file.' ),
1341              'type'        => 'string',
1342              'format'      => 'uri',
1343              'context'     => array( 'view', 'edit', 'embed' ),
1344              'readonly'    => true,
1345          );
1346  
1347          $schema['properties']['missing_image_sizes'] = array(
1348              'description' => __( 'List of the missing image sizes of the attachment.' ),
1349              'type'        => 'array',
1350              'items'       => array( 'type' => 'string' ),
1351              'context'     => array( 'edit' ),
1352              'readonly'    => true,
1353          );
1354  
1355          $schema['properties']['filename'] = array(
1356              'description' => __( 'Original attachment file name.' ),
1357              'type'        => 'string',
1358              'context'     => array( 'view', 'edit' ),
1359              'readonly'    => true,
1360          );
1361  
1362          $schema['properties']['filesize'] = array(
1363              'description' => __( 'Attachment file size in bytes.' ),
1364              'type'        => 'integer',
1365              'context'     => array( 'view', 'edit' ),
1366              'readonly'    => true,
1367          );
1368  
1369          $schema['properties']['exif_orientation'] = array(
1370              'description' => __( 'EXIF orientation value. Values 1-8 follow the EXIF specification, where 1 means no rotation needed.' ),
1371              'type'        => 'integer',
1372              'context'     => array( 'edit' ),
1373              'readonly'    => true,
1374          );
1375  
1376          unset( $schema['properties']['password'] );
1377  
1378          $this->schema = $schema;
1379  
1380          return $this->add_additional_fields_schema( $this->schema );
1381      }
1382  
1383      /**
1384       * Handles an upload via raw POST data.
1385       *
1386       * @since 4.7.0
1387       * @since 6.6.0 Added the `$time` parameter.
1388       *
1389       * @param string      $data    Supplied file data.
1390       * @param array       $headers HTTP headers from the request.
1391       * @param string|null $time    Optional. Time formatted in 'yyyy/mm'. Default null.
1392       * @return array|WP_Error Data from wp_handle_sideload().
1393       */
1394  	protected function upload_from_data( $data, $headers, $time = null ) {
1395          if ( empty( $data ) ) {
1396              return new WP_Error(
1397                  'rest_upload_no_data',
1398                  __( 'No data supplied.' ),
1399                  array( 'status' => 400 )
1400              );
1401          }
1402  
1403          if ( empty( $headers['content_type'] ) ) {
1404              return new WP_Error(
1405                  'rest_upload_no_content_type',
1406                  __( 'No Content-Type supplied.' ),
1407                  array( 'status' => 400 )
1408              );
1409          }
1410  
1411          if ( empty( $headers['content_disposition'] ) ) {
1412              return new WP_Error(
1413                  'rest_upload_no_content_disposition',
1414                  __( 'No Content-Disposition supplied.' ),
1415                  array( 'status' => 400 )
1416              );
1417          }
1418  
1419          $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
1420  
1421          if ( empty( $filename ) ) {
1422              return new WP_Error(
1423                  'rest_upload_invalid_disposition',
1424                  __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ),
1425                  array( 'status' => 400 )
1426              );
1427          }
1428  
1429          if ( ! empty( $headers['content_md5'] ) ) {
1430              $content_md5 = array_shift( $headers['content_md5'] );
1431              $expected    = trim( $content_md5 );
1432              $actual      = md5( $data );
1433  
1434              if ( $expected !== $actual ) {
1435                  return new WP_Error(
1436                      'rest_upload_hash_mismatch',
1437                      __( 'Content hash did not match expected.' ),
1438                      array( 'status' => 412 )
1439                  );
1440              }
1441          }
1442  
1443          // Get the content-type.
1444          $type = array_shift( $headers['content_type'] );
1445  
1446          // Include filesystem functions to get access to wp_tempnam() and wp_handle_sideload().
1447          require_once  ABSPATH . 'wp-admin/includes/file.php';
1448  
1449          // Save the file.
1450          $tmpfname = wp_tempnam( $filename );
1451  
1452          $fp = fopen( $tmpfname, 'w+' );
1453  
1454          if ( ! $fp ) {
1455              return new WP_Error(
1456                  'rest_upload_file_error',
1457                  __( 'Could not open file handle.' ),
1458                  array( 'status' => 500 )
1459              );
1460          }
1461  
1462          fwrite( $fp, $data );
1463          fclose( $fp );
1464  
1465          // Now, sideload it in.
1466          $file_data = array(
1467              'error'    => null,
1468              'tmp_name' => $tmpfname,
1469              'name'     => $filename,
1470              'type'     => $type,
1471          );
1472  
1473          $size_check = self::check_upload_size( $file_data );
1474          if ( is_wp_error( $size_check ) ) {
1475              return $size_check;
1476          }
1477  
1478          $overrides = array(
1479              'test_form' => false,
1480          );
1481  
1482          $sideloaded = wp_handle_sideload( $file_data, $overrides, $time );
1483  
1484          if ( isset( $sideloaded['error'] ) ) {
1485              @unlink( $tmpfname );
1486  
1487              return new WP_Error(
1488                  'rest_upload_sideload_error',
1489                  $sideloaded['error'],
1490                  array( 'status' => 500 )
1491              );
1492          }
1493  
1494          return $sideloaded;
1495      }
1496  
1497      /**
1498       * Parses filename from a Content-Disposition header value.
1499       *
1500       * As per RFC6266:
1501       *
1502       *     content-disposition = "Content-Disposition" ":"
1503       *                            disposition-type *( ";" disposition-parm )
1504       *
1505       *     disposition-type    = "inline" | "attachment" | disp-ext-type
1506       *                         ; case-insensitive
1507       *     disp-ext-type       = token
1508       *
1509       *     disposition-parm    = filename-parm | disp-ext-parm
1510       *
1511       *     filename-parm       = "filename" "=" value
1512       *                         | "filename*" "=" ext-value
1513       *
1514       *     disp-ext-parm       = token "=" value
1515       *                         | ext-token "=" ext-value
1516       *     ext-token           = <the characters in token, followed by "*">
1517       *
1518       * @since 4.7.0
1519       *
1520       * @link https://tools.ietf.org/html/rfc2388
1521       * @link https://tools.ietf.org/html/rfc6266
1522       *
1523       * @param string[] $disposition_header List of Content-Disposition header values.
1524       * @return string|null Filename if available, or null if not found.
1525       */
1526  	public static function get_filename_from_disposition( $disposition_header ) {
1527          // Get the filename.
1528          $filename = null;
1529  
1530          foreach ( $disposition_header as $value ) {
1531              $value = trim( $value );
1532  
1533              if ( ! str_contains( $value, ';' ) ) {
1534                  continue;
1535              }
1536  
1537              list( , $attr_parts ) = explode( ';', $value, 2 );
1538  
1539              $attr_parts = explode( ';', $attr_parts );
1540              $attributes = array();
1541  
1542              foreach ( $attr_parts as $part ) {
1543                  if ( ! str_contains( $part, '=' ) ) {
1544                      continue;
1545                  }
1546  
1547                  list( $key, $value ) = explode( '=', $part, 2 );
1548  
1549                  $attributes[ trim( $key ) ] = trim( $value );
1550              }
1551  
1552              if ( empty( $attributes['filename'] ) ) {
1553                  continue;
1554              }
1555  
1556              $filename = trim( $attributes['filename'] );
1557  
1558              // Unquote quoted filename, but after trimming.
1559              if ( str_starts_with( $filename, '"' ) && str_ends_with( $filename, '"' ) ) {
1560                  $filename = substr( $filename, 1, -1 );
1561              }
1562          }
1563  
1564          return $filename;
1565      }
1566  
1567      /**
1568       * Retrieves the query params for collections of attachments.
1569       *
1570       * @since 4.7.0
1571       * @since 6.9.0 Extends the `media_type` and `mime_type` request arguments to support array values.
1572       *
1573       * @return array Query parameters for the attachment collection as an array.
1574       */
1575  	public function get_collection_params() {
1576          $params                            = parent::get_collection_params();
1577          $params['status']['default']       = 'inherit';
1578          $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
1579          $media_types                       = array_keys( $this->get_media_types() );
1580  
1581          $params['media_type'] = array(
1582              'default'     => null,
1583              'description' => __( 'Limit result set to attachments of a particular media type or media types.' ),
1584              'type'        => 'array',
1585              'items'       => array(
1586                  'type' => 'string',
1587                  'enum' => $media_types,
1588              ),
1589          );
1590  
1591          $params['mime_type'] = array(
1592              'default'     => null,
1593              'description' => __( 'Limit result set to attachments of a particular MIME type or MIME types.' ),
1594              'type'        => 'array',
1595              'items'       => array(
1596                  'type' => 'string',
1597              ),
1598          );
1599  
1600          return $params;
1601      }
1602  
1603      /**
1604       * Handles an upload via multipart/form-data ($_FILES).
1605       *
1606       * @since 4.7.0
1607       * @since 6.6.0 Added the `$time` parameter.
1608       *
1609       * @param array       $files   Data from the `$_FILES` superglobal.
1610       * @param array       $headers HTTP headers from the request.
1611       * @param string|null $time    Optional. Time formatted in 'yyyy/mm'. Default null.
1612       * @return array|WP_Error Data from wp_handle_upload().
1613       */
1614  	protected function upload_from_file( $files, $headers, $time = null ) {
1615          if ( empty( $files ) ) {
1616              return new WP_Error(
1617                  'rest_upload_no_data',
1618                  __( 'No data supplied.' ),
1619                  array( 'status' => 400 )
1620              );
1621          }
1622  
1623          // Verify hash, if given.
1624          if ( ! empty( $headers['content_md5'] ) ) {
1625              $content_md5 = array_shift( $headers['content_md5'] );
1626              $expected    = trim( $content_md5 );
1627              $actual      = md5_file( $files['file']['tmp_name'] );
1628  
1629              if ( $expected !== $actual ) {
1630                  return new WP_Error(
1631                      'rest_upload_hash_mismatch',
1632                      __( 'Content hash did not match expected.' ),
1633                      array( 'status' => 412 )
1634                  );
1635              }
1636          }
1637  
1638          // Pass off to WP to handle the actual upload.
1639          $overrides = array(
1640              'test_form' => false,
1641          );
1642  
1643          // Bypasses is_uploaded_file() when running unit tests.
1644          if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
1645              $overrides['action'] = 'wp_handle_mock_upload';
1646          }
1647  
1648          $size_check = self::check_upload_size( $files['file'] );
1649          if ( is_wp_error( $size_check ) ) {
1650              return $size_check;
1651          }
1652  
1653          // Include filesystem functions to get access to wp_handle_upload().
1654          require_once  ABSPATH . 'wp-admin/includes/file.php';
1655  
1656          $file = wp_handle_upload( $files['file'], $overrides, $time );
1657  
1658          if ( isset( $file['error'] ) ) {
1659              return new WP_Error(
1660                  'rest_upload_unknown_error',
1661                  $file['error'],
1662                  array( 'status' => 500 )
1663              );
1664          }
1665  
1666          return $file;
1667      }
1668  
1669      /**
1670       * Retrieves the supported media types.
1671       *
1672       * Media types are considered the MIME type category.
1673       *
1674       * @since 4.7.0
1675       *
1676       * @return array Array of supported media types.
1677       */
1678  	protected function get_media_types() {
1679          $media_types = array();
1680  
1681          foreach ( get_allowed_mime_types() as $mime_type ) {
1682              $parts = explode( '/', $mime_type );
1683  
1684              if ( ! isset( $media_types[ $parts[0] ] ) ) {
1685                  $media_types[ $parts[0] ] = array();
1686              }
1687  
1688              $media_types[ $parts[0] ][] = $mime_type;
1689          }
1690  
1691          return $media_types;
1692      }
1693  
1694      /**
1695       * Determine if uploaded file exceeds space quota on multisite.
1696       *
1697       * Replicates check_upload_size().
1698       *
1699       * @since 4.9.8
1700       *
1701       * @param array $file $_FILES array for a given file.
1702       * @return true|WP_Error True if can upload, error for errors.
1703       */
1704  	protected function check_upload_size( $file ) {
1705          if ( ! is_multisite() ) {
1706              return true;
1707          }
1708  
1709          if ( get_site_option( 'upload_space_check_disabled' ) ) {
1710              return true;
1711          }
1712  
1713          $space_left = get_upload_space_available();
1714  
1715          $file_size = filesize( $file['tmp_name'] );
1716  
1717          if ( $space_left < $file_size ) {
1718              return new WP_Error(
1719                  'rest_upload_limited_space',
1720                  /* translators: %s: Required disk space in kilobytes. */
1721                  sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ),
1722                  array( 'status' => 400 )
1723              );
1724          }
1725  
1726          if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
1727              return new WP_Error(
1728                  'rest_upload_file_too_big',
1729                  /* translators: %s: Maximum allowed file size in kilobytes. */
1730                  sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ),
1731                  array( 'status' => 400 )
1732              );
1733          }
1734  
1735          // Include multisite admin functions to get access to upload_is_user_over_quota().
1736          require_once  ABSPATH . 'wp-admin/includes/ms.php';
1737  
1738          if ( upload_is_user_over_quota( false ) ) {
1739              return new WP_Error(
1740                  'rest_upload_user_quota_exceeded',
1741                  __( 'You have used your space quota. Please delete files before uploading.' ),
1742                  array( 'status' => 400 )
1743              );
1744          }
1745  
1746          return true;
1747      }
1748  
1749      /**
1750       * Gets the request args for the edit item route.
1751       *
1752       * @since 5.5.0
1753       * @since 6.9.0 Adds flips capability and editable fields for the newly-created attachment post.
1754       *
1755       * @return array
1756       */
1757  	protected function get_edit_media_item_args() {
1758          $args = array(
1759              'src'       => array(
1760                  'description' => __( 'URL to the edited image file.' ),
1761                  'type'        => 'string',
1762                  'format'      => 'uri',
1763                  'required'    => true,
1764              ),
1765              // The `modifiers` param takes precedence over the older format.
1766              'modifiers' => array(
1767                  'description' => __( 'Array of image edits.' ),
1768                  'type'        => 'array',
1769                  'minItems'    => 1,
1770                  'items'       => array(
1771                      'description' => __( 'Image edit.' ),
1772                      'type'        => 'object',
1773                      'required'    => array(
1774                          'type',
1775                          'args',
1776                      ),
1777                      'oneOf'       => array(
1778                          array(
1779                              'title'      => __( 'Flip' ),
1780                              'properties' => array(
1781                                  'type' => array(
1782                                      'description' => __( 'Flip type.' ),
1783                                      'type'        => 'string',
1784                                      'enum'        => array( 'flip' ),
1785                                  ),
1786                                  'args' => array(
1787                                      'description' => __( 'Flip arguments.' ),
1788                                      'type'        => 'object',
1789                                      'required'    => array(
1790                                          'flip',
1791                                      ),
1792                                      'properties'  => array(
1793                                          'flip' => array(
1794                                              'description' => __( 'Flip direction.' ),
1795                                              'type'        => 'object',
1796                                              'required'    => array(
1797                                                  'horizontal',
1798                                                  'vertical',
1799                                              ),
1800                                              'properties'  => array(
1801                                                  'horizontal' => array(
1802                                                      'description' => __( 'Whether to flip in the horizontal direction.' ),
1803                                                      'type' => 'boolean',
1804                                                  ),
1805                                                  'vertical' => array(
1806                                                      'description' => __( 'Whether to flip in the vertical direction.' ),
1807                                                      'type' => 'boolean',
1808                                                  ),
1809                                              ),
1810                                          ),
1811                                      ),
1812                                  ),
1813                              ),
1814                          ),
1815                          array(
1816                              'title'      => __( 'Rotation' ),
1817                              'properties' => array(
1818                                  'type' => array(
1819                                      'description' => __( 'Rotation type.' ),
1820                                      'type'        => 'string',
1821                                      'enum'        => array( 'rotate' ),
1822                                  ),
1823                                  'args' => array(
1824                                      'description' => __( 'Rotation arguments.' ),
1825                                      'type'        => 'object',
1826                                      'required'    => array(
1827                                          'angle',
1828                                      ),
1829                                      'properties'  => array(
1830                                          'angle' => array(
1831                                              'description' => __( 'Angle to rotate clockwise in degrees.' ),
1832                                              'type'        => 'number',
1833                                          ),
1834                                      ),
1835                                  ),
1836                              ),
1837                          ),
1838                          array(
1839                              'title'      => __( 'Crop' ),
1840                              'properties' => array(
1841                                  'type' => array(
1842                                      'description' => __( 'Crop type.' ),
1843                                      'type'        => 'string',
1844                                      'enum'        => array( 'crop' ),
1845                                  ),
1846                                  'args' => array(
1847                                      'description' => __( 'Crop arguments.' ),
1848                                      'type'        => 'object',
1849                                      'required'    => array(
1850                                          'left',
1851                                          'top',
1852                                          'width',
1853                                          'height',
1854                                      ),
1855                                      'properties'  => array(
1856                                          'left'   => array(
1857                                              'description' => __( 'Horizontal position from the left to begin the crop as a percentage of the image width.' ),
1858                                              'type'        => 'number',
1859                                          ),
1860                                          'top'    => array(
1861                                              'description' => __( 'Vertical position from the top to begin the crop as a percentage of the image height.' ),
1862                                              'type'        => 'number',
1863                                          ),
1864                                          'width'  => array(
1865                                              'description' => __( 'Width of the crop as a percentage of the image width.' ),
1866                                              'type'        => 'number',
1867                                          ),
1868                                          'height' => array(
1869                                              'description' => __( 'Height of the crop as a percentage of the image height.' ),
1870                                              'type'        => 'number',
1871                                          ),
1872                                      ),
1873                                  ),
1874                              ),
1875                          ),
1876                      ),
1877                  ),
1878              ),
1879              'rotation'  => array(
1880                  'description'      => __( 'The amount to rotate the image clockwise in degrees. DEPRECATED: Use `modifiers` instead.' ),
1881                  'type'             => 'integer',
1882                  'minimum'          => 0,
1883                  'exclusiveMinimum' => true,
1884                  'maximum'          => 360,
1885                  'exclusiveMaximum' => true,
1886              ),
1887              'x'         => array(
1888                  'description' => __( 'As a percentage of the image, the x position to start the crop from. DEPRECATED: Use `modifiers` instead.' ),
1889                  'type'        => 'number',
1890                  'minimum'     => 0,
1891                  'maximum'     => 100,
1892              ),
1893              'y'         => array(
1894                  'description' => __( 'As a percentage of the image, the y position to start the crop from. DEPRECATED: Use `modifiers` instead.' ),
1895                  'type'        => 'number',
1896                  'minimum'     => 0,
1897                  'maximum'     => 100,
1898              ),
1899              'width'     => array(
1900                  'description' => __( 'As a percentage of the image, the width to crop the image to. DEPRECATED: Use `modifiers` instead.' ),
1901                  'type'        => 'number',
1902                  'minimum'     => 0,
1903                  'maximum'     => 100,
1904              ),
1905              'height'    => array(
1906                  'description' => __( 'As a percentage of the image, the height to crop the image to. DEPRECATED: Use `modifiers` instead.' ),
1907                  'type'        => 'number',
1908                  'minimum'     => 0,
1909                  'maximum'     => 100,
1910              ),
1911          );
1912  
1913          /*
1914           * Get the args based on the post schema. This calls `rest_get_endpoint_args_for_schema()`,
1915           * which also takes care of sanitization and validation.
1916           */
1917          $update_item_args = $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE );
1918  
1919          if ( isset( $update_item_args['caption'] ) ) {
1920              $args['caption'] = $update_item_args['caption'];
1921          }
1922  
1923          if ( isset( $update_item_args['description'] ) ) {
1924              $args['description'] = $update_item_args['description'];
1925          }
1926  
1927          if ( isset( $update_item_args['title'] ) ) {
1928              $args['title'] = $update_item_args['title'];
1929          }
1930  
1931          if ( isset( $update_item_args['post'] ) ) {
1932              $args['post'] = $update_item_args['post'];
1933          }
1934  
1935          if ( isset( $update_item_args['alt_text'] ) ) {
1936              $args['alt_text'] = $update_item_args['alt_text'];
1937          }
1938  
1939          return $args;
1940      }
1941  
1942      /**
1943       * Gets the attachment's original file name.
1944       *
1945       * @since 7.0.0
1946       *
1947       * @param int $attachment_id Attachment ID.
1948       * @return string|null Attachment file name, or null if not found.
1949       */
1950  	protected function get_attachment_filename( int $attachment_id ): ?string {
1951          $path = wp_get_original_image_path( $attachment_id );
1952  
1953          if ( $path ) {
1954              return wp_basename( $path );
1955          }
1956  
1957          $path = get_attached_file( $attachment_id );
1958  
1959          if ( $path ) {
1960              return wp_basename( $path );
1961          }
1962  
1963          return null;
1964      }
1965  
1966      /**
1967       * Gets the attachment's file size in bytes.
1968       *
1969       * @since 7.0.0
1970       *
1971       * @param int $attachment_id Attachment ID.
1972       * @return int|null Attachment file size in bytes, or null if not available.
1973       */
1974  	protected function get_attachment_filesize( int $attachment_id ): ?int {
1975          $meta = wp_get_attachment_metadata( $attachment_id );
1976  
1977          if ( isset( $meta['filesize'] ) ) {
1978              return $meta['filesize'];
1979          }
1980  
1981          $original_path = wp_get_original_image_path( $attachment_id );
1982          $attached_file = $original_path ? $original_path : get_attached_file( $attachment_id );
1983  
1984          if ( is_string( $attached_file ) && is_readable( $attached_file ) ) {
1985              return wp_filesize( $attached_file );
1986          }
1987  
1988          return null;
1989      }
1990  
1991      /**
1992       * Checks if a given request has access to sideload a file.
1993       *
1994       * Sideloading a file for an existing attachment
1995       * requires both update and create permissions.
1996       *
1997       * @since 7.1.0
1998       *
1999       * @param WP_REST_Request $request Full details about the request.
2000       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
2001       */
2002  	public function sideload_item_permissions_check( $request ) {
2003          return $this->edit_media_item_permissions_check( $request );
2004      }
2005  
2006      /**
2007       * Side-loads a media file without creating a new attachment.
2008       *
2009       * @since 7.1.0
2010       *
2011       * @param WP_REST_Request $request Full details about the request.
2012       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
2013       */
2014  	public function sideload_item( WP_REST_Request $request ) {
2015          $attachment_id = (int) $request['id'];
2016  
2017          $post = $this->get_post( $attachment_id );
2018  
2019          if ( is_wp_error( $post ) ) {
2020              return $post;
2021          }
2022  
2023          if (
2024              ! wp_attachment_is_image( $post ) &&
2025              ! wp_attachment_is( 'pdf', $post )
2026          ) {
2027              return new WP_Error(
2028                  'rest_post_invalid_id',
2029                  __( 'Invalid post ID. Only images and PDFs can be sideloaded.' ),
2030                  array( 'status' => 400 )
2031              );
2032          }
2033  
2034          if ( false === $request['convert_format'] ) {
2035              // Prevent image conversion as that is done client-side.
2036              add_filter( 'image_editor_output_format', '__return_empty_array', 100 );
2037          }
2038  
2039          // Get the file via $_FILES or raw data.
2040          $files   = $request->get_file_params();
2041          $headers = $request->get_headers();
2042  
2043          /*
2044           * wp_unique_filename() will always add numeric suffix if the name looks like a sub-size to avoid conflicts.
2045           * See /wp-includes/functions.php.
2046           * With the following filter we can work around this safeguard.
2047           */
2048          $attachment_filename = get_attached_file( $attachment_id, true );
2049          $attachment_filename = $attachment_filename ? wp_basename( $attachment_filename ) : null;
2050  
2051          $filter_filename = static function ( $filename, $ext, $dir, $unique_filename_callback, $alt_filenames, $number ) use ( $attachment_filename ) {
2052              return self::filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename );
2053          };
2054  
2055          add_filter( 'wp_unique_filename', $filter_filename, 10, 6 );
2056  
2057          $parent_post = get_post_parent( $attachment_id );
2058  
2059          $time = null;
2060  
2061          // Matches logic in media_handle_upload().
2062          // The post date doesn't usually matter for pages, so don't backdate this upload.
2063          if ( $parent_post && 'page' !== $parent_post->post_type && ! str_starts_with( $parent_post->post_date, '0000-00-00' ) ) {
2064              $time = $parent_post->post_date;
2065          }
2066  
2067          if ( ! empty( $files ) ) {
2068              $file = $this->upload_from_file( $files, $headers, $time );
2069          } else {
2070              $file = $this->upload_from_data( $request->get_body(), $headers, $time );
2071          }
2072  
2073          remove_filter( 'wp_unique_filename', $filter_filename );
2074          remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );
2075  
2076          if ( is_wp_error( $file ) ) {
2077              return $file;
2078          }
2079  
2080          $type = $file['type'];
2081          $path = $file['file'];
2082  
2083          $image_size = $request['image_size'];
2084  
2085          $metadata = wp_get_attachment_metadata( $attachment_id, true );
2086  
2087          if ( ! $metadata ) {
2088              $metadata = array();
2089          }
2090  
2091          if ( 'original' === $image_size ) {
2092              $metadata['original_image'] = wp_basename( $path );
2093          } elseif ( 'scaled' === $image_size ) {
2094              // The current attached file is the original; record it as original_image.
2095              $current_file = get_attached_file( $attachment_id, true );
2096  
2097              if ( ! $current_file ) {
2098                  return new WP_Error(
2099                      'rest_sideload_no_attached_file',
2100                      __( 'Unable to retrieve the attached file for this attachment.' ),
2101                      array( 'status' => 404 )
2102                  );
2103              }
2104  
2105              $metadata['original_image'] = wp_basename( $current_file );
2106  
2107              // Validate the scaled image before updating the attached file.
2108              $size     = wp_getimagesize( $path );
2109              $filesize = wp_filesize( $path );
2110  
2111              if ( ! $size || ! $filesize ) {
2112                  return new WP_Error(
2113                      'rest_sideload_invalid_image',
2114                      __( 'Unable to read the scaled image file.' ),
2115                      array( 'status' => 500 )
2116                  );
2117              }
2118  
2119              // Update the attached file to point to the scaled version.
2120              if (
2121                  get_attached_file( $attachment_id, true ) !== $path &&
2122                  ! update_attached_file( $attachment_id, $path )
2123              ) {
2124                  return new WP_Error(
2125                      'rest_sideload_update_attached_file_failed',
2126                      __( 'Unable to update the attached file for this attachment.' ),
2127                      array( 'status' => 500 )
2128                  );
2129              }
2130  
2131              $metadata['width']    = $size[0];
2132              $metadata['height']   = $size[1];
2133              $metadata['filesize'] = $filesize;
2134              $metadata['file']     = _wp_relative_upload_path( $path );
2135          } else {
2136              $metadata['sizes'] = $metadata['sizes'] ?? array();
2137  
2138              $size = wp_getimagesize( $path );
2139  
2140              $metadata['sizes'][ $image_size ] = array(
2141                  'width'     => $size ? $size[0] : 0,
2142                  'height'    => $size ? $size[1] : 0,
2143                  'file'      => wp_basename( $path ),
2144                  'mime-type' => $type,
2145                  'filesize'  => wp_filesize( $path ),
2146              );
2147          }
2148  
2149          wp_update_attachment_metadata( $attachment_id, $metadata );
2150  
2151          $response_request = new WP_REST_Request(
2152              WP_REST_Server::READABLE,
2153              rest_get_route_for_post( $attachment_id )
2154          );
2155  
2156          $response_request['context'] = 'edit';
2157  
2158          if ( isset( $request['_fields'] ) ) {
2159              $response_request['_fields'] = $request['_fields'];
2160          }
2161  
2162          $response = $this->prepare_item_for_response( get_post( $attachment_id ), $response_request );
2163  
2164          $response->header( 'Location', rest_url( rest_get_route_for_post( $attachment_id ) ) );
2165  
2166          return $response;
2167      }
2168  
2169      /**
2170       * Filters wp_unique_filename during sideloads.
2171       *
2172       * wp_unique_filename() will always add numeric suffix if the name looks like a sub-size to avoid conflicts.
2173       * Adding this closure to the filter helps work around this safeguard.
2174       *
2175       * Example: when uploading myphoto.jpeg, WordPress normally creates myphoto-150x150.jpeg,
2176       * and when uploading myphoto-150x150.jpeg, it will be renamed to myphoto-150x150-1.jpeg
2177       * However, here it is desired not to add the suffix in order to maintain the same
2178       * naming convention as if the file was uploaded regularly.
2179       *
2180       * @since 7.1.0
2181       *
2182       * @link https://github.com/WordPress/wordpress-develop/blob/30954f7ac0840cfdad464928021d7f380940c347/src/wp-includes/functions.php#L2576-L2582
2183       *
2184       * @param string      $filename            Unique file name.
2185       * @param string      $dir                 Directory path.
2186       * @param int|string  $number              The highest number that was used to make the file name unique
2187       *                                         or an empty string if unused.
2188       * @param string|null $attachment_filename Original attachment file name.
2189       * @return string Filtered file name.
2190       */
2191  	private static function filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename ) {
2192          if ( ! is_int( $number ) || ! $attachment_filename ) {
2193              return $filename;
2194          }
2195  
2196          $ext       = pathinfo( $filename, PATHINFO_EXTENSION );
2197          $name      = pathinfo( $filename, PATHINFO_FILENAME );
2198          $orig_name = pathinfo( $attachment_filename, PATHINFO_FILENAME );
2199  
2200          if ( ! $ext || ! $name ) {
2201              return $filename;
2202          }
2203  
2204          $matches = array();
2205          if ( preg_match( '/(.*)-(\d+x\d+|scaled)-' . $number . '$/', $name, $matches ) ) {
2206              $filename_without_suffix = $matches[1] . '-' . $matches[2] . ".$ext";
2207              if ( $matches[1] === $orig_name && ! file_exists( "$dir/$filename_without_suffix" ) ) {
2208                  return $filename_without_suffix;
2209              }
2210          }
2211  
2212          return $filename;
2213      }
2214  
2215      /**
2216       * Finalizes an attachment after client-side media processing.
2217       *
2218       * Triggers the 'wp_generate_attachment_metadata' filter so that
2219       * server-side plugins can process the attachment after all client-side
2220       * operations (upload, thumbnail generation, sideloads) are complete.
2221       *
2222       * @since 7.1.0
2223       *
2224       * @param WP_REST_Request $request Full details about the request.
2225       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
2226       */
2227  	public function finalize_item( WP_REST_Request $request ) {
2228          $attachment_id = (int) $request['id'];
2229  
2230          $post = $this->get_post( $attachment_id );
2231          if ( is_wp_error( $post ) ) {
2232              return $post;
2233          }
2234  
2235          $metadata = wp_get_attachment_metadata( $attachment_id );
2236          if ( ! is_array( $metadata ) ) {
2237              $metadata = array();
2238          }
2239  
2240          /** This filter is documented in wp-admin/includes/image.php */
2241          $metadata = apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id, 'update' );
2242  
2243          wp_update_attachment_metadata( $attachment_id, $metadata );
2244  
2245          $response_request = new WP_REST_Request(
2246              WP_REST_Server::READABLE,
2247              rest_get_route_for_post( $attachment_id )
2248          );
2249  
2250          $response_request['context'] = 'edit';
2251  
2252          if ( isset( $request['_fields'] ) ) {
2253              $response_request['_fields'] = $request['_fields'];
2254          }
2255  
2256          return $this->prepare_item_for_response( $post, $response_request );
2257      }
2258  }


Generated : Fri Jun 26 08:20:11 2026 Cross-referenced by PHPXref