[ 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       * Image size token for the source-format original preserved alongside a
  29       * client-generated derivative (e.g. the HEIC file kept next to its JPEG).
  30       *
  31       * Used both in the `/sideload` route schema and when dispatching the
  32       * sideloaded file to its metadata key, so the two never drift apart.
  33       *
  34       * @since 7.1.0
  35       * @var string
  36       */
  37      const IMAGE_SIZE_SOURCE_ORIGINAL = 'source_original';
  38  
  39      /**
  40       * Metadata key holding the basename of the source-format original.
  41       *
  42       * Deliberately specific so it never collides with the generic `original`
  43       * or `original_image` keys other flows write to.
  44       *
  45       * @since 7.1.0
  46       * @var string
  47       */
  48      const META_KEY_SOURCE_IMAGE = 'source_image';
  49  
  50      /**
  51       * Registers the routes for attachments.
  52       *
  53       * @since 5.3.0
  54       *
  55       * @see register_rest_route()
  56       */
  57  	public function register_routes() {
  58          parent::register_routes();
  59          register_rest_route(
  60              $this->namespace,
  61              '/' . $this->rest_base . '/(?P<id>[\d]+)/post-process',
  62              array(
  63                  'methods'             => WP_REST_Server::CREATABLE,
  64                  'callback'            => array( $this, 'post_process_item' ),
  65                  'permission_callback' => array( $this, 'post_process_item_permissions_check' ),
  66                  'args'                => array(
  67                      'id'     => array(
  68                          'description' => __( 'Unique identifier for the attachment.' ),
  69                          'type'        => 'integer',
  70                      ),
  71                      'action' => array(
  72                          'type'     => 'string',
  73                          'enum'     => array( 'create-image-subsizes' ),
  74                          'required' => true,
  75                      ),
  76                  ),
  77              )
  78          );
  79          register_rest_route(
  80              $this->namespace,
  81              '/' . $this->rest_base . '/(?P<id>[\d]+)/edit',
  82              array(
  83                  'methods'             => WP_REST_Server::CREATABLE,
  84                  'callback'            => array( $this, 'edit_media_item' ),
  85                  'permission_callback' => array( $this, 'edit_media_item_permissions_check' ),
  86                  'args'                => $this->get_edit_media_item_args(),
  87              )
  88          );
  89  
  90          if ( wp_is_client_side_media_processing_enabled() ) {
  91              register_rest_route(
  92                  $this->namespace,
  93                  '/' . $this->rest_base . '/(?P<id>[\d]+)/sideload',
  94                  array(
  95                      array(
  96                          'methods'             => WP_REST_Server::CREATABLE,
  97                          'callback'            => array( $this, 'sideload_item' ),
  98                          'permission_callback' => array( $this, 'sideload_item_permissions_check' ),
  99                          'args'                => array(
 100                              'id'             => array(
 101                                  'description' => __( 'Unique identifier for the attachment.' ),
 102                                  'type'        => 'integer',
 103                              ),
 104                              'image_size'     => array(
 105                                  'description'       => __( 'Image size. Can be a single size name or an array of size names to register the same file under multiple sizes.' ),
 106                                  'type'              => array( 'string', 'array' ),
 107                                  'items'             => array(
 108                                      'type' => 'string',
 109                                  ),
 110                                  'required'          => true,
 111                                  /*
 112                                   * A custom callback is used instead of the default enum validation
 113                                   * because rest_is_array() treats scalar strings as single-element
 114                                   * lists (via wp_parse_list()), so a [ 'string', 'array' ] type alone
 115                                   * cannot enforce the enum. The callback validates each item against
 116                                   * the current list of registered sizes, which reflects sizes added
 117                                   * after route registration (e.g. via add_image_size()).
 118                                   */
 119                                  'validate_callback' => static function ( $value, $request, $param ) {
 120                                      $valid_sizes   = array_keys( wp_get_registered_image_subsizes() );
 121                                      $valid_sizes[] = 'original';
 122                                      $valid_sizes[] = 'scaled';
 123                                      $valid_sizes[] = 'full';
 124                                      // Source-format original (e.g. the HEIC kept alongside its JPEG derivative).
 125                                      $valid_sizes[] = self::IMAGE_SIZE_SOURCE_ORIGINAL;
 126                                      // Converted-video companions for an animated GIF (the MP4/WebM and its poster).
 127                                      $valid_sizes[] = 'animated_video';
 128                                      $valid_sizes[] = 'animated_video_poster';
 129  
 130                                      $items = is_string( $value ) ? array( $value ) : ( is_array( $value ) ? $value : null );
 131                                      if ( null === $items ) {
 132                                          return new WP_Error(
 133                                              'rest_invalid_type',
 134                                              /* translators: %s: Parameter name. */
 135                                              sprintf( __( '%s must be a string or an array of strings.' ), $param )
 136                                          );
 137                                      }
 138  
 139                                      foreach ( $items as $item ) {
 140                                          if ( ! is_string( $item ) || ! in_array( $item, $valid_sizes, true ) ) {
 141                                              return new WP_Error(
 142                                                  'rest_not_in_enum',
 143                                                  /* translators: %s: Parameter name. */
 144                                                  sprintf( __( '%s contains an invalid image size.' ), $param )
 145                                              );
 146                                          }
 147                                      }
 148  
 149                                      return true;
 150                                  },
 151                              ),
 152                              'convert_format' => array(
 153                                  'type'        => 'boolean',
 154                                  'default'     => true,
 155                                  'description' => __( 'Whether to convert image formats.' ),
 156                              ),
 157                          ),
 158                      ),
 159                      'allow_batch' => $this->allow_batch,
 160                      'schema'      => array( $this, 'get_public_item_schema' ),
 161                  )
 162              );
 163  
 164              register_rest_route(
 165                  $this->namespace,
 166                  '/' . $this->rest_base . '/(?P<id>[\d]+)/finalize',
 167                  array(
 168                      array(
 169                          'methods'             => WP_REST_Server::CREATABLE,
 170                          'callback'            => array( $this, 'finalize_item' ),
 171                          'permission_callback' => array( $this, 'edit_media_item_permissions_check' ),
 172                          'args'                => array(
 173                              'id'        => array(
 174                                  'description' => __( 'Unique identifier for the attachment.' ),
 175                                  'type'        => 'integer',
 176                              ),
 177                              'sub_sizes' => array(
 178                                  'description' => __( 'Array of sub-size metadata collected from sideload responses.' ),
 179                                  'type'        => 'array',
 180                                  'default'     => array(),
 181                                  'items'       => array(
 182                                      'type'       => 'object',
 183                                      'properties' => array(
 184                                          'image_size'     => array(
 185                                              'description' => __( 'Size name, or an array of size names when a single file is registered under multiple sizes with matching dimensions.' ),
 186                                              'type'        => array( 'string', 'array' ),
 187                                              'items'       => array(
 188                                                  'type' => 'string',
 189                                              ),
 190                                              'required'    => true,
 191                                          ),
 192                                          'width'          => array(
 193                                              'type'    => 'integer',
 194                                              'minimum' => 1,
 195                                          ),
 196                                          'height'         => array(
 197                                              'type'    => 'integer',
 198                                              'minimum' => 1,
 199                                          ),
 200                                          'file'           => array(
 201                                              'type' => 'string',
 202                                          ),
 203                                          'mime_type'      => array(
 204                                              'type'    => 'string',
 205                                              'pattern' => '^image/.*',
 206                                          ),
 207                                          'filesize'       => array(
 208                                              'type'    => 'integer',
 209                                              'minimum' => 1,
 210                                          ),
 211                                          'original_image' => array(
 212                                              'type' => 'string',
 213                                          ),
 214                                      ),
 215                                  ),
 216                              ),
 217                          ),
 218                      ),
 219                      'allow_batch' => $this->allow_batch,
 220                      'schema'      => array( $this, 'get_public_item_schema' ),
 221                  )
 222              );
 223          }
 224      }
 225  
 226      /**
 227       * Retrieves the query params for the attachments collection.
 228       *
 229       * @since 7.1.0
 230       *
 231       * @param string $method Optional. HTTP method of the request.
 232       *                       The arguments for `CREATABLE` requests are
 233       *                       checked for required values and may fall-back to a given default.
 234       *                       Default WP_REST_Server::CREATABLE.
 235       * @return array<string, array<string, mixed>> Endpoint arguments.
 236       */
 237  	public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CREATABLE ) {
 238          $args = parent::get_endpoint_args_for_item_schema( $method );
 239  
 240          if ( WP_REST_Server::CREATABLE === $method && wp_is_client_side_media_processing_enabled() ) {
 241              $args['generate_sub_sizes'] = array(
 242                  'type'        => 'boolean',
 243                  'default'     => true,
 244                  'description' => __( 'Whether to generate image sub sizes.' ),
 245              );
 246              $args['convert_format']     = array(
 247                  'type'        => 'boolean',
 248                  'default'     => true,
 249                  'description' => __( 'Whether to convert image formats.' ),
 250              );
 251              $args['url']                = array(
 252                  'type'              => 'string',
 253                  'format'            => 'uri',
 254                  'description'       => __( 'URL of an external image to sideload into the media library, instead of uploading a file.' ),
 255                  'sanitize_callback' => 'sanitize_url',
 256                  'validate_callback' => static function ( $url, $request, $param ) {
 257                      /*
 258                       * A custom validate_callback replaces the default
 259                       * rest_validate_request_arg(), so re-apply it first to keep
 260                       * the schema checks (string type, uri format) enforced.
 261                       */
 262                      $valid = rest_validate_request_arg( $url, $request, $param );
 263                      if ( is_wp_error( $valid ) ) {
 264                          return $valid;
 265                      }
 266  
 267                      /*
 268                       * Reject URLs that are not safe to request server-side. wp_http_validate_url()
 269                       * enforces an HTTP(S) scheme and blocks private, local, and otherwise
 270                       * disallowed hosts, guarding the sideload against SSRF.
 271                       */
 272                      if ( false === wp_http_validate_url( $url ) ) {
 273                          return new WP_Error(
 274                              'rest_invalid_url',
 275                              __( 'Invalid URL. Provide a valid, publicly reachable HTTP or HTTPS image URL.' ),
 276                              array( 'status' => 400 )
 277                          );
 278                      }
 279  
 280                      return true;
 281                  },
 282              );
 283          }
 284  
 285          return $args;
 286      }
 287  
 288      /**
 289       * Determines the allowed query_vars for a get_items() response and
 290       * prepares for WP_Query.
 291       *
 292       * @since 4.7.0
 293       * @since 6.9.0 Extends the `media_type` and `mime_type` request arguments to support array values.
 294       *
 295       * @param array           $prepared_args Optional. Array of prepared arguments. Default empty array.
 296       * @param WP_REST_Request $request       Optional. Request to prepare items for.
 297       * @return array Array of query arguments.
 298       */
 299  	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
 300          $query_args = parent::prepare_items_query( $prepared_args, $request );
 301  
 302          if ( empty( $query_args['post_status'] ) ) {
 303              $query_args['post_status'] = 'inherit';
 304          }
 305  
 306          $all_mime_types = array();
 307          $media_types    = $this->get_media_types();
 308  
 309          if ( ! empty( $request['media_type'] ) && is_array( $request['media_type'] ) ) {
 310              foreach ( $request['media_type'] as $type ) {
 311                  if ( isset( $media_types[ $type ] ) ) {
 312                      $all_mime_types = array_merge( $all_mime_types, $media_types[ $type ] );
 313                  }
 314              }
 315          }
 316  
 317          if ( ! empty( $request['mime_type'] ) && is_array( $request['mime_type'] ) ) {
 318              foreach ( $request['mime_type'] as $mime_type ) {
 319                  $parts = explode( '/', $mime_type );
 320                  if ( isset( $media_types[ $parts[0] ] ) && in_array( $mime_type, $media_types[ $parts[0] ], true ) ) {
 321                      $all_mime_types[] = $mime_type;
 322                  }
 323              }
 324          }
 325  
 326          if ( ! empty( $all_mime_types ) ) {
 327              $query_args['post_mime_type'] = array_values( array_unique( $all_mime_types ) );
 328          }
 329  
 330          // Filter query clauses to include filenames.
 331          if ( isset( $query_args['s'] ) ) {
 332              add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' );
 333          }
 334  
 335          return $query_args;
 336      }
 337  
 338      /**
 339       * Checks if a given request has access to create an attachment.
 340       *
 341       * @since 4.7.0
 342       *
 343       * @param WP_REST_Request $request Full details about the request.
 344       * @return true|WP_Error Boolean true if the attachment may be created, or a WP_Error if not.
 345       */
 346  	public function create_item_permissions_check( $request ) {
 347          $ret = parent::create_item_permissions_check( $request );
 348  
 349          if ( ! $ret || is_wp_error( $ret ) ) {
 350              return $ret;
 351          }
 352  
 353          if ( ! current_user_can( 'upload_files' ) ) {
 354              return new WP_Error(
 355                  'rest_cannot_create',
 356                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 357                  array( 'status' => 400 )
 358              );
 359          }
 360  
 361          // Attaching media to a post requires ability to edit said post.
 362          if ( ! empty( $request['post'] ) && ! current_user_can( 'edit_post', (int) $request['post'] ) ) {
 363              return new WP_Error(
 364                  'rest_cannot_edit',
 365                  __( 'Sorry, you are not allowed to upload media to this post.' ),
 366                  array( 'status' => rest_authorization_required_code() )
 367              );
 368          }
 369          $files = $request->get_file_params();
 370  
 371          /**
 372           * Filter whether the server should prevent uploads for image types it doesn't support. Default true.
 373           *
 374           * Developers can use this filter to enable uploads of certain image types. By default image types that are not
 375           * supported by the server are prevented from being uploaded.
 376           *
 377           * @since 6.8.0
 378           *
 379           * @param bool        $check_mime Whether to prevent uploads of unsupported image types.
 380           * @param string|null $mime_type  The mime type of the file being uploaded (if available).
 381           */
 382          $prevent_unsupported_uploads = apply_filters( 'wp_prevent_unsupported_mime_type_uploads', true, $files['file']['type'] ?? null );
 383  
 384          // When the client handles image processing (generate_sub_sizes is false),
 385          // skip the server-side image editor support check.
 386          if ( false === $request['generate_sub_sizes'] ) {
 387              $prevent_unsupported_uploads = false;
 388          }
 389  
 390          /*
 391           * Always allow still HEIC/HEIF uploads through even if the server's
 392           * image editor doesn't support them. The client-side canvas fallback
 393           * handles processing using the browser's native HEVC decoder.
 394           *
 395           * The '-sequence' variants (multi-frame Live Photos) are deliberately
 396           * excluded: neither the server nor the browser fallback can process
 397           * them yet, so they should fall through to the standard unsupported
 398           * mime-type error rather than be stored unprocessable.
 399           */
 400          $still_heic_mime_types = array( 'image/heic', 'image/heif' );
 401  
 402          if (
 403              $prevent_unsupported_uploads &&
 404              ! empty( $files['file']['type'] ) &&
 405              in_array( $files['file']['type'], $still_heic_mime_types, true )
 406          ) {
 407              $prevent_unsupported_uploads = false;
 408          }
 409  
 410          // If the upload is an image, check if the server can handle the mime type.
 411          if (
 412              $prevent_unsupported_uploads &&
 413              isset( $files['file']['type'] ) &&
 414              str_starts_with( $files['file']['type'], 'image/' )
 415          ) {
 416              // List of non-resizable image formats.
 417              $editor_non_resizable_formats = array(
 418                  'image/svg+xml',
 419              );
 420  
 421              // Check if the image editor supports the type or ignore if it isn't a format resizable by an editor.
 422              if (
 423                  ! in_array( $files['file']['type'], $editor_non_resizable_formats, true ) &&
 424                  ! wp_image_editor_supports( array( 'mime_type' => $files['file']['type'] ) )
 425              ) {
 426                  return new WP_Error(
 427                      'rest_upload_image_type_not_supported',
 428                      __( 'The web server cannot generate responsive image sizes for this image. Convert it to JPEG or PNG before uploading.' ),
 429                      array( 'status' => 400 )
 430                  );
 431              }
 432          }
 433  
 434          return true;
 435      }
 436  
 437      /**
 438       * Creates a single attachment.
 439       *
 440       * @since 4.7.0
 441       * @since 7.1.0 Added the `generate_sub_sizes`, `convert_format`, and `url` parameters.
 442       *
 443       * @param WP_REST_Request $request Full details about the request.
 444       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 445       */
 446  	public function create_item( $request ) {
 447          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 448              return new WP_Error(
 449                  'rest_invalid_param',
 450                  __( 'Invalid parent type.' ),
 451                  array( 'status' => 400 )
 452              );
 453          }
 454  
 455          // Handle generate_sub_sizes parameter.
 456          if ( false === $request['generate_sub_sizes'] ) {
 457              add_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 );
 458              add_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
 459              // Disable server-side EXIF rotation so the client can handle it.
 460              // This preserves the original orientation value in the metadata.
 461              add_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 );
 462          }
 463  
 464          // Handle convert_format parameter.
 465          if ( false === $request['convert_format'] ) {
 466              add_filter( 'image_editor_output_format', '__return_empty_array', 100 );
 467          }
 468  
 469          /*
 470           * When a URL is supplied instead of an uploaded file, sideload the
 471           * remote image on the server. This avoids a cross-origin browser fetch,
 472           * which fails under cross-origin isolation. The sub-size and scaling
 473           * filters applied above still govern whether derivatives are generated.
 474           */
 475          if ( ! empty( $request['url'] ) ) {
 476              $response = $this->create_item_from_url( $request );
 477              $this->remove_client_side_media_processing_filters();
 478              return $response;
 479          }
 480  
 481          $insert = $this->insert_attachment( $request );
 482  
 483          if ( is_wp_error( $insert ) ) {
 484              $this->remove_client_side_media_processing_filters();
 485              return $insert;
 486          }
 487  
 488          $schema = $this->get_item_schema();
 489  
 490          // Extract by name.
 491          $attachment_id = $insert['attachment_id'];
 492          $file          = $insert['file'];
 493  
 494          if ( isset( $request['alt_text'] ) ) {
 495              update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
 496          }
 497  
 498          if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
 499              $thumbnail_update = $this->handle_featured_media( $request['featured_media'], $attachment_id );
 500  
 501              if ( is_wp_error( $thumbnail_update ) ) {
 502                  $this->remove_client_side_media_processing_filters();
 503                  return $thumbnail_update;
 504              }
 505          }
 506  
 507          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 508              $meta_update = $this->meta->update_value( $request['meta'], $attachment_id );
 509  
 510              if ( is_wp_error( $meta_update ) ) {
 511                  $this->remove_client_side_media_processing_filters();
 512                  return $meta_update;
 513              }
 514          }
 515  
 516          $attachment    = get_post( $attachment_id );
 517          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 518  
 519          if ( is_wp_error( $fields_update ) ) {
 520              $this->remove_client_side_media_processing_filters();
 521              return $fields_update;
 522          }
 523  
 524          $terms_update = $this->handle_terms( $attachment_id, $request );
 525  
 526          if ( is_wp_error( $terms_update ) ) {
 527              $this->remove_client_side_media_processing_filters();
 528              return $terms_update;
 529          }
 530  
 531          $request->set_param( 'context', 'edit' );
 532  
 533          /**
 534           * Fires after a single attachment is completely created or updated via the REST API.
 535           *
 536           * @since 5.0.0
 537           *
 538           * @param WP_Post         $attachment Inserted or updated attachment object.
 539           * @param WP_REST_Request $request    Request object.
 540           * @param bool            $creating   True when creating an attachment, false when updating.
 541           */
 542          do_action( 'rest_after_insert_attachment', $attachment, $request, true );
 543  
 544          wp_after_insert_post( $attachment, false, null );
 545  
 546          if ( wp_is_serving_rest_request() ) {
 547              /*
 548               * Set a custom header with the attachment_id.
 549               * Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
 550               */
 551              header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id );
 552          }
 553  
 554          // Include media and image functions to get access to wp_generate_attachment_metadata().
 555          require_once  ABSPATH . 'wp-admin/includes/media.php';
 556          require_once  ABSPATH . 'wp-admin/includes/image.php';
 557  
 558          /*
 559           * Post-process the upload (create image sub-sizes, make PDF thumbnails, etc.) and insert attachment meta.
 560           * At this point the server may run out of resources and post-processing of uploaded images may fail.
 561           */
 562          wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
 563  
 564          $this->remove_client_side_media_processing_filters();
 565  
 566          $response = $this->prepare_item_for_response( $attachment, $request );
 567          $response = rest_ensure_response( $response );
 568          $response->set_status( 201 );
 569          $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $attachment_id ) ) );
 570  
 571          return $response;
 572      }
 573  
 574      /**
 575       * Sideloads an external image from a URL into the media library.
 576       *
 577       * Downloads the remote file on the server, avoiding a cross-origin browser
 578       * fetch that fails under cross-origin isolation. Whether sub-sizes are
 579       * generated is governed by the filters applied in create_item().
 580       *
 581       * @since 7.1.0
 582       *
 583       * @param WP_REST_Request $request Full details about the request.
 584       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 585       */
 586  	protected function create_item_from_url( $request ) {
 587          // Sideloading downloads and stores a file, so require the upload capability.
 588          if ( ! current_user_can( 'upload_files' ) ) {
 589              return new WP_Error(
 590                  'rest_cannot_create',
 591                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 592                  array( 'status' => rest_authorization_required_code() )
 593              );
 594          }
 595  
 596          require_once  ABSPATH . 'wp-admin/includes/file.php';
 597          require_once  ABSPATH . 'wp-admin/includes/media.php';
 598          require_once  ABSPATH . 'wp-admin/includes/image.php';
 599  
 600          $url     = $request['url'];
 601          $post_id = ! empty( $request['post'] ) ? (int) $request['post'] : 0;
 602  
 603          // Derive the filename from the URL path before downloading anything.
 604          $url_path = wp_parse_url( $url, PHP_URL_PATH );
 605          $filename = $url_path ? wp_basename( $url_path ) : '';
 606          if ( '' === $filename ) {
 607              return new WP_Error(
 608                  'rest_invalid_url',
 609                  __( 'Could not determine a filename from the provided URL.' ),
 610                  array( 'status' => 400 )
 611              );
 612          }
 613  
 614          /*
 615           * Only download URLs whose extension maps to an allowed image MIME type.
 616           * The sideload handler would reject other types anyway (via
 617           * wp_check_filetype_and_ext()), but checking first avoids downloading
 618           * files that can never be accepted, such as PHP scripts.
 619           */
 620          $filetype = wp_check_filetype( $filename );
 621          if ( ! $filetype['type'] || ! str_starts_with( $filetype['type'], 'image/' ) ) {
 622              return new WP_Error(
 623                  'rest_invalid_url',
 624                  __( 'The provided URL does not point to a supported image file.' ),
 625                  array( 'status' => 400 )
 626              );
 627          }
 628  
 629          /*
 630           * Download the remote file with WordPress's HTTP API, which validates
 631           * the host and blocks requests to private or local addresses. This is
 632           * the same primitive core's media_sideload_image() relies on.
 633           */
 634          $tmp_file = download_url( $url );
 635          if ( is_wp_error( $tmp_file ) ) {
 636              return $tmp_file;
 637          }
 638  
 639          $file_array = array(
 640              'name'     => $filename,
 641              'tmp_name' => $tmp_file,
 642          );
 643  
 644          $size_check = self::check_upload_size( $file_array );
 645          if ( is_wp_error( $size_check ) ) {
 646              if ( file_exists( $tmp_file ) ) {
 647                  wp_delete_file( $tmp_file );
 648              }
 649              return $size_check;
 650          }
 651  
 652          $attachment_id = media_handle_sideload( $file_array, $post_id );
 653  
 654          if ( is_wp_error( $attachment_id ) ) {
 655              /*
 656               * media_handle_sideload() deletes the temp file on success; remove
 657               * it explicitly when the sideload fails.
 658               */
 659              if ( file_exists( $tmp_file ) ) {
 660                  wp_delete_file( $tmp_file );
 661              }
 662              return $attachment_id;
 663          }
 664  
 665          $attachment = get_post( $attachment_id );
 666  
 667          $request->set_param( 'context', 'edit' );
 668  
 669          /*
 670           * media_handle_sideload() fires the standard insert hooks (including
 671           * wp_after_insert_post), but not the REST-specific action, so fire it
 672           * here for parity with the uploaded-file path in create_item().
 673           */
 674          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
 675          do_action( 'rest_after_insert_attachment', $attachment, $request, true );
 676  
 677          $response = $this->prepare_item_for_response( $attachment, $request );
 678          $response->set_status( 201 );
 679          $response->header( 'Location', rest_url( rest_get_route_for_post( $attachment_id ) ) );
 680  
 681          return $response;
 682      }
 683  
 684      /**
 685       * Removes filters added for client-side media processing.
 686       *
 687       * @since 7.1.0
 688       */
 689  	private function remove_client_side_media_processing_filters(): void {
 690          remove_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 );
 691          remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
 692          remove_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 );
 693          remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );
 694      }
 695  
 696      /**
 697       * Inserts the attachment post in the database. Does not update the attachment meta.
 698       *
 699       * @since 5.3.0
 700       *
 701       * @param WP_REST_Request $request
 702       * @return array|WP_Error
 703       */
 704  	protected function insert_attachment( $request ) {
 705          // Get the file via $_FILES or raw data.
 706          $files   = $request->get_file_params();
 707          $headers = $request->get_headers();
 708  
 709          $time = null;
 710  
 711          // Matches logic in media_handle_upload().
 712          if ( ! empty( $request['post'] ) ) {
 713              $post = get_post( $request['post'] );
 714              // The post date doesn't usually matter for pages, so don't backdate this upload.
 715              if ( $post && 'page' !== $post->post_type && substr( $post->post_date, 0, 4 ) > 0 ) {
 716                  $time = $post->post_date;
 717              }
 718          }
 719  
 720          if ( ! empty( $files ) ) {
 721              $file = $this->upload_from_file( $files, $headers, $time );
 722          } else {
 723              $file = $this->upload_from_data( $request->get_body(), $headers, $time );
 724          }
 725  
 726          if ( is_wp_error( $file ) ) {
 727              return $file;
 728          }
 729  
 730          $name       = wp_basename( $file['file'] );
 731          $name_parts = pathinfo( $name );
 732          $name       = trim( substr( $name, 0, -( 1 + strlen( $name_parts['extension'] ) ) ) );
 733  
 734          $url  = $file['url'];
 735          $type = $file['type'];
 736          $file = $file['file'];
 737          $alt  = '';
 738  
 739          // Include image functions to get access to wp_read_image_metadata().
 740          require_once  ABSPATH . 'wp-admin/includes/image.php';
 741  
 742          // Use image exif/iptc data for title and caption defaults if possible.
 743          $image_meta = wp_read_image_metadata( $file );
 744  
 745          if ( ! empty( $image_meta ) ) {
 746              if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
 747                  $request['title'] = $image_meta['title'];
 748              }
 749  
 750              if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
 751                  $request['caption'] = $image_meta['caption'];
 752              }
 753  
 754              if ( empty( $request['alt'] ) && trim( $image_meta['alt'] ) ) {
 755                  $alt = $image_meta['alt'];
 756              }
 757          }
 758  
 759          $attachment = $this->prepare_item_for_database( $request );
 760  
 761          $attachment->post_mime_type = $type;
 762          $attachment->guid           = $url;
 763  
 764          // If the title was not set, use the original filename.
 765          if ( empty( $attachment->post_title ) && ! empty( $files['file']['name'] ) ) {
 766              // Remove the file extension (after the last `.`)
 767              $tmp_title = substr( $files['file']['name'], 0, strrpos( $files['file']['name'], '.' ) );
 768  
 769              if ( ! empty( $tmp_title ) ) {
 770                  $attachment->post_title = $tmp_title;
 771              }
 772          }
 773  
 774          // Fall back to the original approach.
 775          if ( empty( $attachment->post_title ) ) {
 776              $attachment->post_title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) );
 777          }
 778  
 779          // $post_parent is inherited from $attachment['post_parent'].
 780          $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true, false );
 781  
 782          if ( trim( $alt ) ) {
 783              update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $alt ) );
 784          }
 785  
 786          if ( is_wp_error( $id ) ) {
 787              if ( 'db_update_error' === $id->get_error_code() ) {
 788                  $id->add_data( array( 'status' => 500 ) );
 789              } else {
 790                  $id->add_data( array( 'status' => 400 ) );
 791              }
 792  
 793              return $id;
 794          }
 795  
 796          $attachment = get_post( $id );
 797  
 798          /**
 799           * Fires after a single attachment is created or updated via the REST API.
 800           *
 801           * @since 4.7.0
 802           *
 803           * @param WP_Post         $attachment Inserted or updated attachment object.
 804           * @param WP_REST_Request $request    The request sent to the API.
 805           * @param bool            $creating   True when creating an attachment, false when updating.
 806           */
 807          do_action( 'rest_insert_attachment', $attachment, $request, true );
 808  
 809          return array(
 810              'attachment_id' => $id,
 811              'file'          => $file,
 812          );
 813      }
 814  
 815      /**
 816       * Determines the featured media based on a request param.
 817       *
 818       * @since 6.5.0
 819       *
 820       * @param int $featured_media Featured Media ID.
 821       * @param int $post_id        Post ID.
 822       * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
 823       */
 824  	protected function handle_featured_media( $featured_media, $post_id ) {
 825          $post_type         = get_post_type( $post_id );
 826          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' );
 827  
 828          // Similar check as in wp_insert_post().
 829          if ( ! $thumbnail_support && get_post_mime_type( $post_id ) ) {
 830              if ( wp_attachment_is( 'audio', $post_id ) ) {
 831                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
 832              } elseif ( wp_attachment_is( 'video', $post_id ) ) {
 833                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
 834              }
 835          }
 836  
 837          if ( $thumbnail_support ) {
 838              return parent::handle_featured_media( $featured_media, $post_id );
 839          }
 840  
 841          return new WP_Error(
 842              'rest_no_featured_media',
 843              sprintf(
 844                  /* translators: %s: attachment mime type */
 845                  __( 'This site does not support post thumbnails on attachments with MIME type %s.' ),
 846                  get_post_mime_type( $post_id )
 847              ),
 848              array( 'status' => 400 )
 849          );
 850      }
 851  
 852      /**
 853       * Updates a single attachment.
 854       *
 855       * @since 4.7.0
 856       *
 857       * @param WP_REST_Request $request Full details about the request.
 858       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 859       */
 860  	public function update_item( $request ) {
 861          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 862              return new WP_Error(
 863                  'rest_invalid_param',
 864                  __( 'Invalid parent type.' ),
 865                  array( 'status' => 400 )
 866              );
 867          }
 868  
 869          $attachment_before = get_post( $request['id'] );
 870          $response          = parent::update_item( $request );
 871  
 872          if ( is_wp_error( $response ) ) {
 873              return $response;
 874          }
 875  
 876          $response = rest_ensure_response( $response );
 877          $data     = $response->get_data();
 878  
 879          if ( isset( $request['alt_text'] ) ) {
 880              update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
 881          }
 882  
 883          $attachment = get_post( $request['id'] );
 884  
 885          if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
 886              $thumbnail_update = $this->handle_featured_media( $request['featured_media'], $attachment->ID );
 887  
 888              if ( is_wp_error( $thumbnail_update ) ) {
 889                  return $thumbnail_update;
 890              }
 891          }
 892  
 893          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 894  
 895          if ( is_wp_error( $fields_update ) ) {
 896              return $fields_update;
 897          }
 898  
 899          $request->set_param( 'context', 'edit' );
 900  
 901          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
 902          do_action( 'rest_after_insert_attachment', $attachment, $request, false );
 903  
 904          wp_after_insert_post( $attachment, true, $attachment_before );
 905  
 906          $response = $this->prepare_item_for_response( $attachment, $request );
 907          $response = rest_ensure_response( $response );
 908  
 909          return $response;
 910      }
 911  
 912      /**
 913       * Performs post-processing on an attachment.
 914       *
 915       * @since 5.3.0
 916       *
 917       * @param WP_REST_Request $request Full details about the request.
 918       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 919       */
 920  	public function post_process_item( $request ) {
 921          switch ( $request['action'] ) {
 922              case 'create-image-subsizes':
 923                  require_once  ABSPATH . 'wp-admin/includes/image.php';
 924                  wp_update_image_subsizes( $request['id'] );
 925                  break;
 926          }
 927  
 928          $request['context'] = 'edit';
 929  
 930          return $this->prepare_item_for_response( get_post( $request['id'] ), $request );
 931      }
 932  
 933      /**
 934       * Checks if a given request can perform post-processing on an attachment.
 935       *
 936       * @since 5.3.0
 937       *
 938       * @param WP_REST_Request $request Full details about the request.
 939       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
 940       */
 941  	public function post_process_item_permissions_check( $request ) {
 942          return $this->update_item_permissions_check( $request );
 943      }
 944  
 945      /**
 946       * Checks if a given request has access to editing media.
 947       *
 948       * @since 5.5.0
 949       *
 950       * @param WP_REST_Request $request Full details about the request.
 951       * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
 952       */
 953  	public function edit_media_item_permissions_check( $request ) {
 954          if ( ! current_user_can( 'upload_files' ) ) {
 955              return new WP_Error(
 956                  'rest_cannot_edit_image',
 957                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 958                  array( 'status' => rest_authorization_required_code() )
 959              );
 960          }
 961  
 962          return $this->update_item_permissions_check( $request );
 963      }
 964  
 965      /**
 966       * Applies edits to a media item and creates a new attachment record.
 967       *
 968       * @since 5.5.0
 969       * @since 6.9.0 Adds flips capability and editable fields for the newly-created attachment post.
 970       * @since 7.1.0 Applies EXIF orientation correction before image modifications.
 971       *
 972       * @param WP_REST_Request $request Full details about the request.
 973       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 974       */
 975  	public function edit_media_item( $request ) {
 976          require_once  ABSPATH . 'wp-admin/includes/image.php';
 977  
 978          $attachment_id = $request['id'];
 979  
 980          // This also confirms the attachment is an image.
 981          $image_file = wp_get_original_image_path( $attachment_id );
 982          $image_meta = wp_get_attachment_metadata( $attachment_id );
 983  
 984          if (
 985              ! $image_meta ||
 986              ! $image_file ||
 987              ! wp_image_file_matches_image_meta( $request['src'], $image_meta, $attachment_id )
 988          ) {
 989              return new WP_Error(
 990                  'rest_unknown_attachment',
 991                  __( 'Unable to get meta information for file.' ),
 992                  array( 'status' => 404 )
 993              );
 994          }
 995  
 996          $supported_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif', 'image/heic' );
 997          $mime_type       = get_post_mime_type( $attachment_id );
 998          if ( ! in_array( $mime_type, $supported_types, true ) ) {
 999              return new WP_Error(
1000                  'rest_cannot_edit_file_type',
1001                  __( 'This type of file cannot be edited.' ),
1002                  array( 'status' => 400 )
1003              );
1004          }
1005  
1006          // The `modifiers` param takes precedence over the older format.
1007          if ( isset( $request['modifiers'] ) ) {
1008              $modifiers = $request['modifiers'];
1009          } else {
1010              $modifiers = array();
1011  
1012              if ( isset( $request['flip']['horizontal'] ) || isset( $request['flip']['vertical'] ) ) {
1013                  $flip_args = array(
1014                      'vertical'   => isset( $request['flip']['vertical'] ) ? (bool) $request['flip']['vertical'] : false,
1015                      'horizontal' => isset( $request['flip']['horizontal'] ) ? (bool) $request['flip']['horizontal'] : false,
1016                  );
1017  
1018                  $modifiers[] = array(
1019                      'type' => 'flip',
1020                      'args' => array(
1021                          'flip' => $flip_args,
1022                      ),
1023                  );
1024              }
1025  
1026              if ( ! empty( $request['rotation'] ) ) {
1027                  $modifiers[] = array(
1028                      'type' => 'rotate',
1029                      'args' => array(
1030                          'angle' => $request['rotation'],
1031                      ),
1032                  );
1033              }
1034  
1035              if ( isset( $request['x'], $request['y'], $request['width'], $request['height'] ) ) {
1036                  $modifiers[] = array(
1037                      'type' => 'crop',
1038                      'args' => array(
1039                          'left'   => $request['x'],
1040                          'top'    => $request['y'],
1041                          'width'  => $request['width'],
1042                          'height' => $request['height'],
1043                      ),
1044                  );
1045              }
1046  
1047              if ( 0 === count( $modifiers ) ) {
1048                  return new WP_Error(
1049                      'rest_image_not_edited',
1050                      __( 'The image was not edited. Edit the image before applying the changes.' ),
1051                      array( 'status' => 400 )
1052                  );
1053              }
1054          }
1055  
1056          /*
1057           * If the file doesn't exist, attempt a URL fopen on the src link.
1058           * This can occur with certain file replication plugins.
1059           * Keep the original file path to get a modified name later.
1060           */
1061          $image_file_to_edit = $image_file;
1062          if ( ! file_exists( $image_file_to_edit ) ) {
1063              $image_file_to_edit = _load_image_to_edit_path( $attachment_id );
1064          }
1065  
1066          $image_editor = wp_get_image_editor( $image_file_to_edit );
1067  
1068          if ( is_wp_error( $image_editor ) ) {
1069              return new WP_Error(
1070                  'rest_unknown_image_file_type',
1071                  __( 'Unable to edit this image.' ),
1072                  array( 'status' => 500 )
1073              );
1074          }
1075  
1076          // Apply any unapplied EXIF orientation so edits run in the upright frame the client previewed.
1077          $image_editor->maybe_exif_rotate();
1078  
1079          foreach ( $modifiers as $modifier ) {
1080              $args = $modifier['args'];
1081              switch ( $modifier['type'] ) {
1082                  case 'flip':
1083                      /*
1084                       * Flips the current image.
1085                       * The vertical flip is the first argument (flip along horizontal axis), the horizontal flip is the second argument (flip along vertical axis).
1086                       * See: WP_Image_Editor::flip()
1087                       */
1088                      $result = $image_editor->flip( $args['flip']['vertical'], $args['flip']['horizontal'] );
1089                      if ( is_wp_error( $result ) ) {
1090                          return new WP_Error(
1091                              'rest_image_flip_failed',
1092                              __( 'Unable to flip this image.' ),
1093                              array( 'status' => 500 )
1094                          );
1095                      }
1096                      break;
1097                  case 'rotate':
1098                      // Rotation direction: clockwise vs. counterclockwise.
1099                      $rotate = 0 - $args['angle'];
1100  
1101                      if ( 0 !== $rotate ) {
1102                          $result = $image_editor->rotate( $rotate );
1103  
1104                          if ( is_wp_error( $result ) ) {
1105                              return new WP_Error(
1106                                  'rest_image_rotation_failed',
1107                                  __( 'Unable to rotate this image.' ),
1108                                  array( 'status' => 500 )
1109                              );
1110                          }
1111                      }
1112  
1113                      break;
1114  
1115                  case 'crop':
1116                      $size = $image_editor->get_size();
1117  
1118                      $crop_x = (int) round( ( $size['width'] * $args['left'] ) / 100.0 );
1119                      $crop_y = (int) round( ( $size['height'] * $args['top'] ) / 100.0 );
1120                      $width  = (int) round( ( $size['width'] * $args['width'] ) / 100.0 );
1121                      $height = (int) round( ( $size['height'] * $args['height'] ) / 100.0 );
1122  
1123                      if ( $size['width'] !== $width || $size['height'] !== $height ) {
1124                          $result = $image_editor->crop( $crop_x, $crop_y, $width, $height );
1125  
1126                          if ( is_wp_error( $result ) ) {
1127                              return new WP_Error(
1128                                  'rest_image_crop_failed',
1129                                  __( 'Unable to crop this image.' ),
1130                                  array( 'status' => 500 )
1131                              );
1132                          }
1133                      }
1134  
1135                      break;
1136  
1137              }
1138          }
1139  
1140          // Calculate the file name.
1141          $image_ext  = pathinfo( $image_file, PATHINFO_EXTENSION );
1142          $image_name = wp_basename( $image_file, ".{$image_ext}" );
1143  
1144          /*
1145           * Do not append multiple `-edited` to the file name.
1146           * The user may be editing a previously edited image.
1147           */
1148          if ( preg_match( '/-edited(-\d+)?$/', $image_name ) ) {
1149              // Remove any `-1`, `-2`, etc. `wp_unique_filename()` will add the proper number.
1150              $image_name = preg_replace( '/-edited(-\d+)?$/', '-edited', $image_name );
1151          } else {
1152              // Append `-edited` before the extension.
1153              $image_name .= '-edited';
1154          }
1155  
1156          $filename = "{$image_name}.{$image_ext}";
1157  
1158          // Create the uploads subdirectory if needed.
1159          $uploads = wp_upload_dir();
1160  
1161          // Make the file name unique in the (new) upload directory.
1162          $filename = wp_unique_filename( $uploads['path'], $filename );
1163  
1164          // Save to disk.
1165          $saved = $image_editor->save( $uploads['path'] . "/$filename" );
1166  
1167          if ( is_wp_error( $saved ) ) {
1168              return $saved;
1169          }
1170  
1171          // Grab original attachment post so we can use it to set defaults.
1172          $original_attachment_post = get_post( $attachment_id );
1173  
1174          // Check request fields and assign default values.
1175          $new_attachment_post                 = $this->prepare_item_for_database( $request );
1176          $new_attachment_post->post_mime_type = $saved['mime-type'];
1177          $new_attachment_post->guid           = $uploads['url'] . "/$filename";
1178  
1179          // Unset ID so wp_insert_attachment generates a new ID.
1180          unset( $new_attachment_post->ID );
1181  
1182          // Set new attachment post title with fallbacks.
1183          $new_attachment_post->post_title = $new_attachment_post->post_title ?? $original_attachment_post->post_title ?? $image_name;
1184  
1185          // Set new attachment post caption (post_excerpt).
1186          $new_attachment_post->post_excerpt = $new_attachment_post->post_excerpt ?? $original_attachment_post->post_excerpt ?? '';
1187  
1188          // Set new attachment post description (post_content) with fallbacks.
1189          $new_attachment_post->post_content = $new_attachment_post->post_content ?? $original_attachment_post->post_content ?? '';
1190  
1191          // Set post parent if set in request, else the default of `0` (no parent).
1192          $new_attachment_post->post_parent = $new_attachment_post->post_parent ?? 0;
1193  
1194          // Insert the new attachment post.
1195          $new_attachment_id = wp_insert_attachment( wp_slash( (array) $new_attachment_post ), $saved['path'], 0, true );
1196  
1197          if ( is_wp_error( $new_attachment_id ) ) {
1198              if ( 'db_update_error' === $new_attachment_id->get_error_code() ) {
1199                  $new_attachment_id->add_data( array( 'status' => 500 ) );
1200              } else {
1201                  $new_attachment_id->add_data( array( 'status' => 400 ) );
1202              }
1203  
1204              return $new_attachment_id;
1205          }
1206  
1207          // First, try to use the alt text from the request. If not set, copy the image alt text from the original attachment.
1208          $image_alt = isset( $request['alt_text'] ) ? sanitize_text_field( $request['alt_text'] ) : get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
1209  
1210          if ( ! empty( $image_alt ) ) {
1211              // update_post_meta() expects slashed.
1212              update_post_meta( $new_attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
1213          }
1214  
1215          if ( wp_is_serving_rest_request() ) {
1216              /*
1217               * Set a custom header with the attachment_id.
1218               * Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
1219               */
1220              header( 'X-WP-Upload-Attachment-ID: ' . $new_attachment_id );
1221          }
1222  
1223          // Generate image sub-sizes and meta.
1224          $new_image_meta = wp_generate_attachment_metadata( $new_attachment_id, $saved['path'] );
1225  
1226          // Copy the EXIF metadata from the original attachment if not generated for the edited image.
1227          if ( isset( $image_meta['image_meta'] ) && isset( $new_image_meta['image_meta'] ) && is_array( $new_image_meta['image_meta'] ) ) {
1228              // Merge but skip empty values.
1229              foreach ( (array) $image_meta['image_meta'] as $key => $value ) {
1230                  if ( empty( $new_image_meta['image_meta'][ $key ] ) && ! empty( $value ) ) {
1231                      $new_image_meta['image_meta'][ $key ] = $value;
1232                  }
1233              }
1234          }
1235  
1236          // Reset orientation. At this point the image is edited and orientation is correct.
1237          if ( ! empty( $new_image_meta['image_meta']['orientation'] ) ) {
1238              $new_image_meta['image_meta']['orientation'] = 1;
1239          }
1240  
1241          // The attachment_id may change if the site is exported and imported.
1242          $new_image_meta['parent_image'] = array(
1243              'attachment_id' => $attachment_id,
1244              // Path to the originally uploaded image file relative to the uploads directory.
1245              'file'          => _wp_relative_upload_path( $image_file ),
1246          );
1247  
1248          /**
1249           * Filters the meta data for the new image created by editing an existing image.
1250           *
1251           * @since 5.5.0
1252           *
1253           * @param array $new_image_meta    Meta data for the new image.
1254           * @param int   $new_attachment_id Attachment post ID for the new image.
1255           * @param int   $attachment_id     Attachment post ID for the edited (parent) image.
1256           */
1257          $new_image_meta = apply_filters( 'wp_edited_image_metadata', $new_image_meta, $new_attachment_id, $attachment_id );
1258  
1259          wp_update_attachment_metadata( $new_attachment_id, $new_image_meta );
1260  
1261          $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request );
1262          $response->set_status( 201 );
1263          $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) );
1264  
1265          return $response;
1266      }
1267  
1268      /**
1269       * Prepares a single attachment for create or update.
1270       *
1271       * @since 4.7.0
1272       *
1273       * @param WP_REST_Request $request Request object.
1274       * @return stdClass|WP_Error Post object.
1275       */
1276  	protected function prepare_item_for_database( $request ) {
1277          $prepared_attachment = parent::prepare_item_for_database( $request );
1278  
1279          // Attachment caption (post_excerpt internally).
1280          if ( isset( $request['caption'] ) ) {
1281              if ( is_string( $request['caption'] ) ) {
1282                  $prepared_attachment->post_excerpt = $request['caption'];
1283              } elseif ( isset( $request['caption']['raw'] ) ) {
1284                  $prepared_attachment->post_excerpt = $request['caption']['raw'];
1285              }
1286          }
1287  
1288          // Attachment description (post_content internally).
1289          if ( isset( $request['description'] ) ) {
1290              if ( is_string( $request['description'] ) ) {
1291                  $prepared_attachment->post_content = $request['description'];
1292              } elseif ( isset( $request['description']['raw'] ) ) {
1293                  $prepared_attachment->post_content = $request['description']['raw'];
1294              }
1295          }
1296  
1297          if ( isset( $request['post'] ) ) {
1298              $prepared_attachment->post_parent = (int) $request['post'];
1299          }
1300  
1301          return $prepared_attachment;
1302      }
1303  
1304      /**
1305       * Prepares a single attachment output for response.
1306       *
1307       * @since 4.7.0
1308       * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
1309       *
1310       * @param WP_Post         $item    Attachment object.
1311       * @param WP_REST_Request $request Request object.
1312       * @return WP_REST_Response Response object.
1313       */
1314  	public function prepare_item_for_response( $item, $request ) {
1315          // Restores the more descriptive, specific name for use within this method.
1316          $post = $item;
1317  
1318          $response = parent::prepare_item_for_response( $post, $request );
1319          $fields   = $this->get_fields_for_response( $request );
1320          /** @var array<string, mixed> $data */
1321          $data = $response->get_data();
1322  
1323          if ( in_array( 'description', $fields, true ) ) {
1324              $data['description'] = array(
1325                  'raw'      => $post->post_content,
1326                  /** This filter is documented in wp-includes/post-template.php */
1327                  'rendered' => apply_filters( 'the_content', $post->post_content ),
1328              );
1329          }
1330  
1331          if ( in_array( 'caption', $fields, true ) ) {
1332              /** This filter is documented in wp-includes/post-template.php */
1333              $caption = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
1334  
1335              /** This filter is documented in wp-includes/post-template.php */
1336              $caption = apply_filters( 'the_excerpt', $caption );
1337  
1338              $data['caption'] = array(
1339                  'raw'      => $post->post_excerpt,
1340                  'rendered' => $caption,
1341              );
1342          }
1343  
1344          if ( in_array( 'alt_text', $fields, true ) ) {
1345              $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
1346          }
1347  
1348          if ( in_array( 'media_type', $fields, true ) ) {
1349              $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
1350          }
1351  
1352          if ( in_array( 'mime_type', $fields, true ) ) {
1353              $data['mime_type'] = $post->post_mime_type;
1354          }
1355  
1356          if ( in_array( 'media_details', $fields, true ) ) {
1357              $data['media_details'] = wp_get_attachment_metadata( $post->ID );
1358  
1359              // Ensure empty details is an empty object.
1360              if ( empty( $data['media_details'] ) ) {
1361                  $data['media_details'] = new stdClass();
1362              } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
1363  
1364                  foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
1365  
1366                      if ( isset( $size_data['mime-type'] ) ) {
1367                          $size_data['mime_type'] = $size_data['mime-type'];
1368                          unset( $size_data['mime-type'] );
1369                      }
1370  
1371                      // Use the same method image_downsize() does.
1372                      $image_src = wp_get_attachment_image_src( $post->ID, $size );
1373                      if ( ! $image_src ) {
1374                          continue;
1375                      }
1376  
1377                      $size_data['source_url'] = $image_src[0];
1378                  }
1379                  unset( $size_data );
1380  
1381                  $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
1382  
1383                  if ( ! empty( $full_src ) ) {
1384                      $data['media_details']['sizes']['full'] = array(
1385                          'file'       => wp_basename( $full_src[0] ),
1386                          'width'      => $full_src[1],
1387                          'height'     => $full_src[2],
1388                          'mime_type'  => $post->post_mime_type,
1389                          'source_url' => $full_src[0],
1390                      );
1391                  }
1392              } else {
1393                  $data['media_details']['sizes'] = new stdClass();
1394              }
1395          }
1396  
1397          if ( in_array( 'post', $fields, true ) ) {
1398              $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
1399          }
1400  
1401          if ( in_array( 'source_url', $fields, true ) ) {
1402              $data['source_url'] = wp_get_attachment_url( $post->ID );
1403          }
1404  
1405          if ( in_array( 'missing_image_sizes', $fields, true ) ) {
1406              require_once  ABSPATH . 'wp-admin/includes/image.php';
1407              $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) );
1408  
1409              // Handle PDFs which don't use wp_get_missing_image_subsizes().
1410              if ( empty( $data['missing_image_sizes'] ) && 'application/pdf' === get_post_mime_type( $post ) ) {
1411                  $metadata = wp_get_attachment_metadata( $post->ID, true );
1412  
1413                  if ( ! is_array( $metadata ) ) {
1414                      $metadata = array();
1415                  }
1416  
1417                  $metadata['sizes'] = $metadata['sizes'] ?? array();
1418  
1419                  $fallback_sizes = array(
1420                      'thumbnail',
1421                      'medium',
1422                      'large',
1423                  );
1424  
1425                  // The filter might have been added by ::create_item().
1426                  remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
1427  
1428                  /** This filter is documented in wp-admin/includes/image.php */
1429                  $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
1430  
1431                  $registered_sizes = wp_get_registered_image_subsizes();
1432                  $merged_sizes     = array_keys( array_intersect_key( $registered_sizes, array_flip( $fallback_sizes ) ) );
1433  
1434                  $data['missing_image_sizes'] = array_values( array_diff( $merged_sizes, array_keys( $metadata['sizes'] ) ) );
1435              }
1436          }
1437  
1438          if ( in_array( 'filename', $fields, true ) ) {
1439              $data['filename'] = $this->get_attachment_filename( $post->ID );
1440          }
1441  
1442          if ( in_array( 'filesize', $fields, true ) ) {
1443              $data['filesize'] = $this->get_attachment_filesize( $post->ID );
1444          }
1445  
1446          if ( in_array( 'exif_orientation', $fields, true ) && wp_attachment_is_image( $post ) ) {
1447              $metadata = wp_get_attachment_metadata( $post->ID, true );
1448  
1449              // Default to 1 (no rotation needed) if orientation not set.
1450              $orientation = 1;
1451  
1452              if (
1453                  is_array( $metadata ) &&
1454                  isset( $metadata['image_meta']['orientation'] ) &&
1455                  (int) $metadata['image_meta']['orientation'] > 0
1456              ) {
1457                  $orientation = (int) $metadata['image_meta']['orientation'];
1458              }
1459  
1460              $data['exif_orientation'] = $orientation;
1461          }
1462  
1463          if ( wp_attachment_is_image( $post ) ) {
1464              $mime_type = (string) get_post_mime_type( $post );
1465  
1466              /*
1467               * Per-file output format for images, evaluated with the real filename
1468               * and MIME type so plugins filtering image_editor_output_format can
1469               * make per-attachment decisions (e.g. JPEG -> WebP). Resolved the same
1470               * way WP_Image_Editor::set_quality() resolves the output format.
1471               */
1472              if ( in_array( 'image_output_format', $fields, true ) ) {
1473                  $filename = get_attached_file( $post->ID );
1474  
1475                  /** This filter is documented in wp-includes/media.php */
1476                  $output_formats = apply_filters(
1477                      'image_editor_output_format',
1478                      array( $mime_type => $mime_type ),
1479                      $filename ? $filename : '',
1480                      $mime_type
1481                  );
1482  
1483                  $output_mime                 = $output_formats[ $mime_type ] ?? $mime_type;
1484                  $data['image_output_format'] = ( $output_mime !== $mime_type ) ? $output_mime : null;
1485              }
1486  
1487              /*
1488               * Per-file progressive/interlaced encoding flag for images, evaluated
1489               * against the attachment's MIME type.
1490               */
1491              if ( in_array( 'image_save_progressive', $fields, true ) ) {
1492                  /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */
1493                  $data['image_save_progressive'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type );
1494              }
1495  
1496              if ( in_array( 'image_quality', $fields, true ) ) {
1497                  $filename = get_attached_file( $post->ID );
1498  
1499                  /** This filter is documented in wp-includes/media.php */
1500                  $output_formats = apply_filters(
1501                      'image_editor_output_format',
1502                      array( $mime_type => $mime_type ),
1503                      $filename ? $filename : '',
1504                      $mime_type
1505                  );
1506                  $output_mime    = $output_formats[ $mime_type ] ?? $mime_type;
1507  
1508                  $metadata    = wp_get_attachment_metadata( $post->ID, true );
1509                  $full_width  = max( 0, ( is_array( $metadata ) && isset( $metadata['width'] ) ) ? (int) $metadata['width'] : 0 );
1510                  $full_height = max( 0, ( is_array( $metadata ) && isset( $metadata['height'] ) ) ? (int) $metadata['height'] : 0 );
1511  
1512                  $full_quality = wp_get_image_encode_quality(
1513                      $output_mime,
1514                      array(
1515                          'width'  => $full_width,
1516                          'height' => $full_height,
1517                      )
1518                  );
1519  
1520                  $size_quality = array();
1521  
1522                  foreach ( wp_get_registered_image_subsizes() as $size_name => $size_data ) {
1523                      $quality = wp_get_image_encode_quality(
1524                          $output_mime,
1525                          array(
1526                              'width'  => (int) $size_data['width'],
1527                              'height' => (int) $size_data['height'],
1528                          )
1529                      );
1530  
1531                      // Only report sizes whose quality diverges from the full-size value.
1532                      if ( $quality !== $full_quality ) {
1533                          $size_quality[ $size_name ] = $quality;
1534                      }
1535                  }
1536  
1537                  $data['image_quality'] = array(
1538                      'default' => $full_quality,
1539                      'sizes'   => $size_quality,
1540                  );
1541              }
1542          }
1543  
1544          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1545  
1546          $data = $this->filter_response_by_context( $data, $context );
1547  
1548          $links = $response->get_links();
1549  
1550          // Wrap the data in a response object.
1551          $response = rest_ensure_response( $data );
1552  
1553          foreach ( $links as $rel => $rel_links ) {
1554              foreach ( $rel_links as $link ) {
1555                  $response->add_link( $rel, $link['href'], $link['attributes'] );
1556              }
1557          }
1558  
1559          /**
1560           * Filters an attachment returned from the REST API.
1561           *
1562           * Allows modification of the attachment right before it is returned.
1563           *
1564           * @since 4.7.0
1565           *
1566           * @param WP_REST_Response $response The response object.
1567           * @param WP_Post          $post     The original attachment post.
1568           * @param WP_REST_Request  $request  Request used to generate the response.
1569           */
1570          return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
1571      }
1572  
1573      /**
1574       * Prepares attachment links for the request.
1575       *
1576       * @since 6.9.0
1577       *
1578       * @param WP_Post $post Post object.
1579       * @return array Links for the given attachment.
1580       */
1581  	protected function prepare_links( $post ) {
1582          $links = parent::prepare_links( $post );
1583  
1584          if ( ! empty( $post->post_parent ) ) {
1585              $post = get_post( $post->post_parent );
1586  
1587              if ( ! empty( $post ) ) {
1588                  $links['https://api.w.org/attached-to'] = array(
1589                      'href'       => rest_url( rest_get_route_for_post( $post ) ),
1590                      'embeddable' => true,
1591                      'post_type'  => $post->post_type,
1592                      'id'         => $post->ID,
1593                  );
1594              }
1595          }
1596  
1597          return $links;
1598      }
1599  
1600      /**
1601       * Retrieves the attachment's schema, conforming to JSON Schema.
1602       *
1603       * @since 4.7.0
1604       *
1605       * @return array Item schema as an array.
1606       */
1607  	public function get_item_schema() {
1608          if ( $this->schema ) {
1609              return $this->add_additional_fields_schema( $this->schema );
1610          }
1611  
1612          $schema = parent::get_item_schema();
1613  
1614          $schema['properties']['alt_text'] = array(
1615              'description' => __( 'Alternative text to display when attachment is not displayed.' ),
1616              'type'        => 'string',
1617              'context'     => array( 'view', 'edit', 'embed' ),
1618              'arg_options' => array(
1619                  'sanitize_callback' => 'sanitize_text_field',
1620              ),
1621          );
1622  
1623          $schema['properties']['caption'] = array(
1624              'description' => __( 'The attachment caption.' ),
1625              'type'        => 'object',
1626              'context'     => array( 'view', 'edit', 'embed' ),
1627              'arg_options' => array(
1628                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
1629                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
1630              ),
1631              'properties'  => array(
1632                  'raw'      => array(
1633                      'description' => __( 'Caption for the attachment, as it exists in the database.' ),
1634                      'type'        => 'string',
1635                      'context'     => array( 'edit' ),
1636                  ),
1637                  'rendered' => array(
1638                      'description' => __( 'HTML caption for the attachment, transformed for display.' ),
1639                      'type'        => 'string',
1640                      'context'     => array( 'view', 'edit', 'embed' ),
1641                      'readonly'    => true,
1642                  ),
1643              ),
1644          );
1645  
1646          $schema['properties']['description'] = array(
1647              'description' => __( 'The attachment description.' ),
1648              'type'        => 'object',
1649              'context'     => array( 'view', 'edit' ),
1650              'arg_options' => array(
1651                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
1652                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
1653              ),
1654              'properties'  => array(
1655                  'raw'      => array(
1656                      'description' => __( 'Description for the attachment, as it exists in the database.' ),
1657                      'type'        => 'string',
1658                      'context'     => array( 'edit' ),
1659                  ),
1660                  'rendered' => array(
1661                      'description' => __( 'HTML description for the attachment, transformed for display.' ),
1662                      'type'        => 'string',
1663                      'context'     => array( 'view', 'edit' ),
1664                      'readonly'    => true,
1665                  ),
1666              ),
1667          );
1668  
1669          $schema['properties']['media_type'] = array(
1670              'description' => __( 'Attachment type.' ),
1671              'type'        => 'string',
1672              'enum'        => array( 'image', 'file' ),
1673              'context'     => array( 'view', 'edit', 'embed' ),
1674              'readonly'    => true,
1675          );
1676  
1677          $schema['properties']['mime_type'] = array(
1678              'description' => __( 'The attachment MIME type.' ),
1679              'type'        => 'string',
1680              'context'     => array( 'view', 'edit', 'embed' ),
1681              'readonly'    => true,
1682          );
1683  
1684          $schema['properties']['media_details'] = array(
1685              'description' => __( 'Details about the media file, specific to its type.' ),
1686              'type'        => 'object',
1687              'context'     => array( 'view', 'edit', 'embed' ),
1688              'readonly'    => true,
1689          );
1690  
1691          $schema['properties']['post'] = array(
1692              'description' => __( 'The ID for the associated post of the attachment.' ),
1693              'type'        => 'integer',
1694              'context'     => array( 'view', 'edit' ),
1695          );
1696  
1697          $schema['properties']['source_url'] = array(
1698              'description' => __( 'URL to the original attachment file.' ),
1699              'type'        => 'string',
1700              'format'      => 'uri',
1701              'context'     => array( 'view', 'edit', 'embed' ),
1702              'readonly'    => true,
1703          );
1704  
1705          $schema['properties']['missing_image_sizes'] = array(
1706              'description' => __( 'List of the missing image sizes of the attachment.' ),
1707              'type'        => 'array',
1708              'items'       => array( 'type' => 'string' ),
1709              'context'     => array( 'edit' ),
1710              'readonly'    => true,
1711          );
1712  
1713          $schema['properties']['filename'] = array(
1714              'description' => __( 'Original attachment file name.' ),
1715              'type'        => 'string',
1716              'context'     => array( 'view', 'edit' ),
1717              'readonly'    => true,
1718          );
1719  
1720          $schema['properties']['filesize'] = array(
1721              'description' => __( 'Attachment file size in bytes.' ),
1722              'type'        => array( 'integer', 'null' ),
1723              'context'     => array( 'view', 'edit' ),
1724              'readonly'    => true,
1725          );
1726  
1727          $schema['properties']['exif_orientation'] = array(
1728              'description' => __( 'EXIF orientation value. Values 1-8 follow the EXIF specification, where 1 means no rotation needed.' ),
1729              'type'        => 'integer',
1730              'context'     => array( 'edit' ),
1731              'readonly'    => true,
1732          );
1733  
1734          // Enumerate the registered sub-sizes so the schema documents exactly which
1735          // keys may appear under "sizes".
1736          $size_quality_properties = array();
1737          foreach ( array_keys( wp_get_registered_image_subsizes() ) as $size_name ) {
1738              $size_quality_properties[ $size_name ] = array(
1739                  'type'    => 'integer',
1740                  'minimum' => 1,
1741                  'maximum' => 100,
1742              );
1743          }
1744  
1745          $schema['properties']['image_quality'] = array(
1746              'description' => __( 'Encode quality (1-100) from the wp_editor_set_quality filter, resolved against the output MIME type. The "default" value applies to the full-size image; "sizes" lists per-registered-size overrides where the filtered value differs from "default".' ),
1747              'type'        => 'object',
1748              'context'     => array( 'edit' ),
1749              'readonly'    => true,
1750              'properties'  => array(
1751                  'default' => array(
1752                      'type'    => 'integer',
1753                      'minimum' => 1,
1754                      'maximum' => 100,
1755                  ),
1756                  'sizes'   => array(
1757                      'type'       => 'object',
1758                      'properties' => $size_quality_properties,
1759                  ),
1760              ),
1761          );
1762  
1763          $schema['properties']['image_output_format'] = array(
1764              'description' => __( 'The output MIME type this image should be converted to, based on the image_editor_output_format filter. Null if no conversion is needed.' ),
1765              'type'        => array( 'string', 'null' ),
1766              'context'     => array( 'edit' ),
1767              'readonly'    => true,
1768          );
1769  
1770          $schema['properties']['image_save_progressive'] = array(
1771              'description' => __( 'Whether to use progressive/interlaced encoding when saving this image.' ),
1772              'type'        => 'boolean',
1773              'context'     => array( 'edit' ),
1774              'readonly'    => true,
1775          );
1776  
1777          unset( $schema['properties']['password'] );
1778  
1779          $this->schema = $schema;
1780  
1781          return $this->add_additional_fields_schema( $this->schema );
1782      }
1783  
1784      /**
1785       * Handles an upload via raw POST data.
1786       *
1787       * @since 4.7.0
1788       * @since 6.6.0 Added the `$time` parameter.
1789       *
1790       * @param string      $data    Supplied file data.
1791       * @param array       $headers HTTP headers from the request.
1792       * @param string|null $time    Optional. Time formatted in 'yyyy/mm'. Default null.
1793       * @return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string }|WP_Error Data from wp_handle_sideload().
1794       */
1795  	protected function upload_from_data( $data, $headers, $time = null ) {
1796          if ( empty( $data ) ) {
1797              return new WP_Error(
1798                  'rest_upload_no_data',
1799                  __( 'No data supplied.' ),
1800                  array( 'status' => 400 )
1801              );
1802          }
1803  
1804          if ( empty( $headers['content_type'] ) ) {
1805              return new WP_Error(
1806                  'rest_upload_no_content_type',
1807                  __( 'No Content-Type supplied.' ),
1808                  array( 'status' => 400 )
1809              );
1810          }
1811  
1812          if ( empty( $headers['content_disposition'] ) ) {
1813              return new WP_Error(
1814                  'rest_upload_no_content_disposition',
1815                  __( 'No Content-Disposition supplied.' ),
1816                  array( 'status' => 400 )
1817              );
1818          }
1819  
1820          $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
1821  
1822          if ( empty( $filename ) ) {
1823              return new WP_Error(
1824                  'rest_upload_invalid_disposition',
1825                  __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ),
1826                  array( 'status' => 400 )
1827              );
1828          }
1829  
1830          if ( ! empty( $headers['content_md5'] ) ) {
1831              $content_md5 = array_shift( $headers['content_md5'] );
1832              $expected    = trim( $content_md5 );
1833              $actual      = md5( $data );
1834  
1835              if ( $expected !== $actual ) {
1836                  return new WP_Error(
1837                      'rest_upload_hash_mismatch',
1838                      __( 'Content hash did not match expected.' ),
1839                      array( 'status' => 412 )
1840                  );
1841              }
1842          }
1843  
1844          // Get the content-type.
1845          $type = array_shift( $headers['content_type'] );
1846  
1847          // Include filesystem functions to get access to wp_tempnam() and wp_handle_sideload().
1848          require_once  ABSPATH . 'wp-admin/includes/file.php';
1849  
1850          // Save the file.
1851          $tmpfname = wp_tempnam( $filename );
1852  
1853          $fp = fopen( $tmpfname, 'w+' );
1854  
1855          if ( ! $fp ) {
1856              return new WP_Error(
1857                  'rest_upload_file_error',
1858                  __( 'Could not open file handle.' ),
1859                  array( 'status' => 500 )
1860              );
1861          }
1862  
1863          fwrite( $fp, $data );
1864          fclose( $fp );
1865  
1866          // Now, sideload it in.
1867          $file_data = array(
1868              'error'    => null,
1869              'tmp_name' => $tmpfname,
1870              'name'     => $filename,
1871              'type'     => $type,
1872          );
1873  
1874          $size_check = self::check_upload_size( $file_data );
1875          if ( is_wp_error( $size_check ) ) {
1876              return $size_check;
1877          }
1878  
1879          $overrides = array(
1880              'test_form' => false,
1881          );
1882  
1883          $sideloaded = wp_handle_sideload( $file_data, $overrides, $time );
1884  
1885          if ( isset( $sideloaded['error'] ) ) {
1886              @unlink( $tmpfname );
1887  
1888              return new WP_Error(
1889                  'rest_upload_sideload_error',
1890                  $sideloaded['error'],
1891                  array( 'status' => 500 )
1892              );
1893          }
1894  
1895          return $sideloaded;
1896      }
1897  
1898      /**
1899       * Parses filename from a Content-Disposition header value.
1900       *
1901       * As per RFC6266:
1902       *
1903       *     content-disposition = "Content-Disposition" ":"
1904       *                            disposition-type *( ";" disposition-parm )
1905       *
1906       *     disposition-type    = "inline" | "attachment" | disp-ext-type
1907       *                         ; case-insensitive
1908       *     disp-ext-type       = token
1909       *
1910       *     disposition-parm    = filename-parm | disp-ext-parm
1911       *
1912       *     filename-parm       = "filename" "=" value
1913       *                         | "filename*" "=" ext-value
1914       *
1915       *     disp-ext-parm       = token "=" value
1916       *                         | ext-token "=" ext-value
1917       *     ext-token           = <the characters in token, followed by "*">
1918       *
1919       * @since 4.7.0
1920       *
1921       * @link https://tools.ietf.org/html/rfc2388
1922       * @link https://tools.ietf.org/html/rfc6266
1923       *
1924       * @param string[] $disposition_header List of Content-Disposition header values.
1925       * @return string|null Filename if available, or null if not found.
1926       */
1927  	public static function get_filename_from_disposition( $disposition_header ) {
1928          // Get the filename.
1929          $filename = null;
1930  
1931          foreach ( $disposition_header as $value ) {
1932              $value = trim( $value );
1933  
1934              if ( ! str_contains( $value, ';' ) ) {
1935                  continue;
1936              }
1937  
1938              list( , $attr_parts ) = explode( ';', $value, 2 );
1939  
1940              $attr_parts = explode( ';', $attr_parts );
1941              $attributes = array();
1942  
1943              foreach ( $attr_parts as $part ) {
1944                  if ( ! str_contains( $part, '=' ) ) {
1945                      continue;
1946                  }
1947  
1948                  list( $key, $value ) = explode( '=', $part, 2 );
1949  
1950                  $attributes[ trim( $key ) ] = trim( $value );
1951              }
1952  
1953              if ( empty( $attributes['filename'] ) ) {
1954                  continue;
1955              }
1956  
1957              $filename = trim( $attributes['filename'] );
1958  
1959              // Unquote quoted filename, but after trimming.
1960              if ( str_starts_with( $filename, '"' ) && str_ends_with( $filename, '"' ) ) {
1961                  $filename = substr( $filename, 1, -1 );
1962              }
1963          }
1964  
1965          return $filename;
1966      }
1967  
1968      /**
1969       * Retrieves the query params for collections of attachments.
1970       *
1971       * @since 4.7.0
1972       * @since 6.9.0 Extends the `media_type` and `mime_type` request arguments to support array values.
1973       *
1974       * @return array Query parameters for the attachment collection as an array.
1975       */
1976  	public function get_collection_params() {
1977          $params                            = parent::get_collection_params();
1978          $params['status']['default']       = 'inherit';
1979          $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
1980          $media_types                       = array_keys( $this->get_media_types() );
1981  
1982          $params['media_type'] = array(
1983              'default'     => null,
1984              'description' => __( 'Limit result set to attachments of a particular media type or media types.' ),
1985              'type'        => 'array',
1986              'items'       => array(
1987                  'type' => 'string',
1988                  'enum' => $media_types,
1989              ),
1990          );
1991  
1992          $params['mime_type'] = array(
1993              'default'     => null,
1994              'description' => __( 'Limit result set to attachments of a particular MIME type or MIME types.' ),
1995              'type'        => 'array',
1996              'items'       => array(
1997                  'type' => 'string',
1998              ),
1999          );
2000  
2001          return $params;
2002      }
2003  
2004      /**
2005       * Handles an upload via multipart/form-data ($_FILES).
2006       *
2007       * @since 4.7.0
2008       * @since 6.6.0 Added the `$time` parameter.
2009       *
2010       * @param array       $files   Data from the `$_FILES` superglobal.
2011       * @param array       $headers HTTP headers from the request.
2012       * @param string|null $time    Optional. Time formatted in 'yyyy/mm'. Default null.
2013       * @return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string }|WP_Error Data from wp_handle_upload().
2014       */
2015  	protected function upload_from_file( $files, $headers, $time = null ) {
2016          if ( empty( $files ) ) {
2017              return new WP_Error(
2018                  'rest_upload_no_data',
2019                  __( 'No data supplied.' ),
2020                  array( 'status' => 400 )
2021              );
2022          }
2023  
2024          // Verify hash, if given.
2025          if ( ! empty( $headers['content_md5'] ) ) {
2026              $content_md5 = array_shift( $headers['content_md5'] );
2027              $expected    = trim( $content_md5 );
2028              $actual      = md5_file( $files['file']['tmp_name'] );
2029  
2030              if ( $expected !== $actual ) {
2031                  return new WP_Error(
2032                      'rest_upload_hash_mismatch',
2033                      __( 'Content hash did not match expected.' ),
2034                      array( 'status' => 412 )
2035                  );
2036              }
2037          }
2038  
2039          // Pass off to WP to handle the actual upload.
2040          $overrides = array(
2041              'test_form' => false,
2042          );
2043  
2044          // Bypasses is_uploaded_file() when running unit tests.
2045          if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
2046              $overrides['action'] = 'wp_handle_mock_upload';
2047          }
2048  
2049          $size_check = self::check_upload_size( $files['file'] );
2050          if ( is_wp_error( $size_check ) ) {
2051              return $size_check;
2052          }
2053  
2054          // Include filesystem functions to get access to wp_handle_upload().
2055          require_once  ABSPATH . 'wp-admin/includes/file.php';
2056  
2057          $file = wp_handle_upload( $files['file'], $overrides, $time );
2058  
2059          if ( isset( $file['error'] ) ) {
2060              return new WP_Error(
2061                  'rest_upload_unknown_error',
2062                  $file['error'],
2063                  array( 'status' => 500 )
2064              );
2065          }
2066  
2067          return $file;
2068      }
2069  
2070      /**
2071       * Retrieves the supported media types.
2072       *
2073       * Media types are considered the MIME type category.
2074       *
2075       * @since 4.7.0
2076       *
2077       * @return array Array of supported media types.
2078       */
2079  	protected function get_media_types() {
2080          $media_types = array();
2081  
2082          foreach ( get_allowed_mime_types() as $mime_type ) {
2083              $parts = explode( '/', $mime_type );
2084  
2085              if ( ! isset( $media_types[ $parts[0] ] ) ) {
2086                  $media_types[ $parts[0] ] = array();
2087              }
2088  
2089              $media_types[ $parts[0] ][] = $mime_type;
2090          }
2091  
2092          return $media_types;
2093      }
2094  
2095      /**
2096       * Determine if uploaded file exceeds space quota on multisite.
2097       *
2098       * Replicates check_upload_size().
2099       *
2100       * @since 4.9.8
2101       *
2102       * @param array $file $_FILES array for a given file.
2103       * @return true|WP_Error True if can upload, error for errors.
2104       */
2105  	protected function check_upload_size( $file ) {
2106          if ( ! is_multisite() ) {
2107              return true;
2108          }
2109  
2110          if ( get_site_option( 'upload_space_check_disabled' ) ) {
2111              return true;
2112          }
2113  
2114          $space_left = get_upload_space_available();
2115  
2116          $file_size = filesize( $file['tmp_name'] );
2117  
2118          if ( $space_left < $file_size ) {
2119              return new WP_Error(
2120                  'rest_upload_limited_space',
2121                  /* translators: %s: Required disk space in kilobytes. */
2122                  sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ),
2123                  array( 'status' => 400 )
2124              );
2125          }
2126  
2127          if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
2128              return new WP_Error(
2129                  'rest_upload_file_too_big',
2130                  /* translators: %s: Maximum allowed file size in kilobytes. */
2131                  sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ),
2132                  array( 'status' => 400 )
2133              );
2134          }
2135  
2136          // Include multisite admin functions to get access to upload_is_user_over_quota().
2137          require_once  ABSPATH . 'wp-admin/includes/ms.php';
2138  
2139          if ( upload_is_user_over_quota( false ) ) {
2140              return new WP_Error(
2141                  'rest_upload_user_quota_exceeded',
2142                  __( 'You have used your space quota. Please delete files before uploading.' ),
2143                  array( 'status' => 400 )
2144              );
2145          }
2146  
2147          return true;
2148      }
2149  
2150      /**
2151       * Gets the request args for the edit item route.
2152       *
2153       * @since 5.5.0
2154       * @since 6.9.0 Adds flips capability and editable fields for the newly-created attachment post.
2155       *
2156       * @return array
2157       */
2158  	protected function get_edit_media_item_args() {
2159          $args = array(
2160              'src'       => array(
2161                  'description' => __( 'URL to the edited image file.' ),
2162                  'type'        => 'string',
2163                  'format'      => 'uri',
2164                  'required'    => true,
2165              ),
2166              // The `modifiers` param takes precedence over the older format.
2167              'modifiers' => array(
2168                  'description' => __( 'Array of image edits.' ),
2169                  'type'        => 'array',
2170                  'minItems'    => 1,
2171                  'items'       => array(
2172                      'description' => __( 'Image edit.' ),
2173                      'type'        => 'object',
2174                      'required'    => array(
2175                          'type',
2176                          'args',
2177                      ),
2178                      'oneOf'       => array(
2179                          array(
2180                              'title'      => __( 'Flip' ),
2181                              'properties' => array(
2182                                  'type' => array(
2183                                      'description' => __( 'Flip type.' ),
2184                                      'type'        => 'string',
2185                                      'enum'        => array( 'flip' ),
2186                                  ),
2187                                  'args' => array(
2188                                      'description' => __( 'Flip arguments.' ),
2189                                      'type'        => 'object',
2190                                      'required'    => array(
2191                                          'flip',
2192                                      ),
2193                                      'properties'  => array(
2194                                          'flip' => array(
2195                                              'description' => __( 'Flip direction.' ),
2196                                              'type'        => 'object',
2197                                              'required'    => array(
2198                                                  'horizontal',
2199                                                  'vertical',
2200                                              ),
2201                                              'properties'  => array(
2202                                                  'horizontal' => array(
2203                                                      'description' => __( 'Whether to flip in the horizontal direction.' ),
2204                                                      'type' => 'boolean',
2205                                                  ),
2206                                                  'vertical' => array(
2207                                                      'description' => __( 'Whether to flip in the vertical direction.' ),
2208                                                      'type' => 'boolean',
2209                                                  ),
2210                                              ),
2211                                          ),
2212                                      ),
2213                                  ),
2214                              ),
2215                          ),
2216                          array(
2217                              'title'      => __( 'Rotation' ),
2218                              'properties' => array(
2219                                  'type' => array(
2220                                      'description' => __( 'Rotation type.' ),
2221                                      'type'        => 'string',
2222                                      'enum'        => array( 'rotate' ),
2223                                  ),
2224                                  'args' => array(
2225                                      'description' => __( 'Rotation arguments.' ),
2226                                      'type'        => 'object',
2227                                      'required'    => array(
2228                                          'angle',
2229                                      ),
2230                                      'properties'  => array(
2231                                          'angle' => array(
2232                                              'description' => __( 'Angle to rotate clockwise in degrees.' ),
2233                                              'type'        => 'number',
2234                                          ),
2235                                      ),
2236                                  ),
2237                              ),
2238                          ),
2239                          array(
2240                              'title'      => __( 'Crop' ),
2241                              'properties' => array(
2242                                  'type' => array(
2243                                      'description' => __( 'Crop type.' ),
2244                                      'type'        => 'string',
2245                                      'enum'        => array( 'crop' ),
2246                                  ),
2247                                  'args' => array(
2248                                      'description' => __( 'Crop arguments.' ),
2249                                      'type'        => 'object',
2250                                      'required'    => array(
2251                                          'left',
2252                                          'top',
2253                                          'width',
2254                                          'height',
2255                                      ),
2256                                      'properties'  => array(
2257                                          'left'   => array(
2258                                              'description' => __( 'Horizontal position from the left to begin the crop as a percentage of the image width.' ),
2259                                              'type'        => 'number',
2260                                          ),
2261                                          'top'    => array(
2262                                              'description' => __( 'Vertical position from the top to begin the crop as a percentage of the image height.' ),
2263                                              'type'        => 'number',
2264                                          ),
2265                                          'width'  => array(
2266                                              'description' => __( 'Width of the crop as a percentage of the image width.' ),
2267                                              'type'        => 'number',
2268                                          ),
2269                                          'height' => array(
2270                                              'description' => __( 'Height of the crop as a percentage of the image height.' ),
2271                                              'type'        => 'number',
2272                                          ),
2273                                      ),
2274                                  ),
2275                              ),
2276                          ),
2277                      ),
2278                  ),
2279              ),
2280              'rotation'  => array(
2281                  'description'      => __( 'The amount to rotate the image clockwise in degrees. DEPRECATED: Use `modifiers` instead.' ),
2282                  'type'             => 'integer',
2283                  'minimum'          => 0,
2284                  'exclusiveMinimum' => true,
2285                  'maximum'          => 360,
2286                  'exclusiveMaximum' => true,
2287              ),
2288              'x'         => array(
2289                  'description' => __( 'As a percentage of the image, the x position to start the crop from. DEPRECATED: Use `modifiers` instead.' ),
2290                  'type'        => 'number',
2291                  'minimum'     => 0,
2292                  'maximum'     => 100,
2293              ),
2294              'y'         => array(
2295                  'description' => __( 'As a percentage of the image, the y position to start the crop from. DEPRECATED: Use `modifiers` instead.' ),
2296                  'type'        => 'number',
2297                  'minimum'     => 0,
2298                  'maximum'     => 100,
2299              ),
2300              'width'     => array(
2301                  'description' => __( 'As a percentage of the image, the width to crop the image to. DEPRECATED: Use `modifiers` instead.' ),
2302                  'type'        => 'number',
2303                  'minimum'     => 0,
2304                  'maximum'     => 100,
2305              ),
2306              'height'    => array(
2307                  'description' => __( 'As a percentage of the image, the height to crop the image to. DEPRECATED: Use `modifiers` instead.' ),
2308                  'type'        => 'number',
2309                  'minimum'     => 0,
2310                  'maximum'     => 100,
2311              ),
2312          );
2313  
2314          /*
2315           * Get the args based on the post schema. This calls `rest_get_endpoint_args_for_schema()`,
2316           * which also takes care of sanitization and validation.
2317           */
2318          $update_item_args = $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE );
2319  
2320          if ( isset( $update_item_args['caption'] ) ) {
2321              $args['caption'] = $update_item_args['caption'];
2322          }
2323  
2324          if ( isset( $update_item_args['description'] ) ) {
2325              $args['description'] = $update_item_args['description'];
2326          }
2327  
2328          if ( isset( $update_item_args['title'] ) ) {
2329              $args['title'] = $update_item_args['title'];
2330          }
2331  
2332          if ( isset( $update_item_args['post'] ) ) {
2333              $args['post'] = $update_item_args['post'];
2334          }
2335  
2336          if ( isset( $update_item_args['alt_text'] ) ) {
2337              $args['alt_text'] = $update_item_args['alt_text'];
2338          }
2339  
2340          return $args;
2341      }
2342  
2343      /**
2344       * Gets the attachment's original file name.
2345       *
2346       * @since 7.0.0
2347       *
2348       * @param int $attachment_id Attachment ID.
2349       * @return string|null Attachment file name, or null if not found.
2350       */
2351  	protected function get_attachment_filename( int $attachment_id ): ?string {
2352          $path = wp_get_original_image_path( $attachment_id );
2353  
2354          if ( $path ) {
2355              return wp_basename( $path );
2356          }
2357  
2358          $path = get_attached_file( $attachment_id );
2359  
2360          if ( $path ) {
2361              return wp_basename( $path );
2362          }
2363  
2364          return null;
2365      }
2366  
2367      /**
2368       * Gets the attachment's file size in bytes.
2369       *
2370       * @since 7.0.0
2371       *
2372       * @param int $attachment_id Attachment ID.
2373       * @return int|null Attachment file size in bytes, or null if not available.
2374       * @phpstan-return non-negative-int|null
2375       */
2376  	protected function get_attachment_filesize( int $attachment_id ): ?int {
2377          $meta = wp_get_attachment_metadata( $attachment_id );
2378  
2379          if ( isset( $meta['filesize'] ) && is_numeric( $meta['filesize'] ) && $meta['filesize'] > 0 ) {
2380              return (int) $meta['filesize'];
2381          }
2382  
2383          $original_path = wp_get_original_image_path( $attachment_id );
2384          $attached_file = $original_path ? $original_path : get_attached_file( $attachment_id );
2385  
2386          if ( is_string( $attached_file ) && is_readable( $attached_file ) ) {
2387              return wp_filesize( $attached_file );
2388          }
2389  
2390          return null;
2391      }
2392  
2393      /**
2394       * Checks if a given request has access to sideload a file.
2395       *
2396       * Sideloading a file for an existing attachment
2397       * requires both update and create permissions.
2398       *
2399       * @since 7.1.0
2400       *
2401       * @param WP_REST_Request $request Full details about the request.
2402       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
2403       */
2404  	public function sideload_item_permissions_check( $request ) {
2405          return $this->edit_media_item_permissions_check( $request );
2406      }
2407  
2408      /**
2409       * Validates that uploaded image dimensions are appropriate for the specified image size.
2410       *
2411       * @since 7.1.0
2412       *
2413       * @param int    $width         Uploaded image width.
2414       * @param int    $height        Uploaded image height.
2415       * @param string $image_size    The target image size name.
2416       * @param int    $attachment_id The attachment ID.
2417       * @return true|WP_Error True if valid, WP_Error if invalid.
2418       */
2419  	private function validate_image_dimensions( int $width, int $height, string $image_size, int $attachment_id ) {
2420          // All image sizes require positive dimensions.
2421          if ( $width <= 0 || $height <= 0 ) {
2422              return new WP_Error(
2423                  'rest_upload_invalid_dimensions',
2424                  __( 'Uploaded image must have positive dimensions.' ),
2425                  array( 'status' => 400 )
2426              );
2427          }
2428  
2429          /*
2430           * 'original' size: the full-size image that replaces the main file (see
2431           * sideload_item()/finalize_item()). The endpoint expects any EXIF
2432           * orientation to be applied to the image already, which can swap width
2433           * and height, so the dimensions must match the stored dimensions or be
2434           * their transpose.
2435           */
2436          if ( 'original' === $image_size ) {
2437              $metadata = wp_get_attachment_metadata( $attachment_id, true );
2438              if ( is_array( $metadata ) && isset( $metadata['width'], $metadata['height'] ) ) {
2439                  $expected_width  = (int) $metadata['width'];
2440                  $expected_height = (int) $metadata['height'];
2441  
2442                  $matches_dimensions    = $width === $expected_width && $height === $expected_height;
2443                  $transposes_dimensions = $width === $expected_height && $height === $expected_width;
2444  
2445                  if ( ! $matches_dimensions && ! $transposes_dimensions ) {
2446                      return new WP_Error(
2447                          'rest_upload_dimension_mismatch',
2448                          sprintf(
2449                              /* translators: 1: Actual width, 2: actual height, 3: expected width, 4: expected height. */
2450                              __( 'Uploaded image dimensions (%1$dx%2$d) do not match original image dimensions (%3$dx%4$d).' ),
2451                              $width,
2452                              $height,
2453                              $expected_width,
2454                              $expected_height
2455                          ),
2456                          array( 'status' => 400 )
2457                      );
2458                  }
2459              }
2460              return true;
2461          }
2462  
2463          // 'full' size (PDF thumbnails) and 'scaled': no further constraints.
2464          if ( in_array( $image_size, array( 'full', 'scaled' ), true ) ) {
2465              return true;
2466          }
2467  
2468          /*
2469           * 'animated_video_poster' companion: a static poster image for the
2470           * converted video. It is a real image (so it has positive dimensions)
2471           * but is not a registered sub-size, so it has no dimension constraint.
2472           */
2473          if ( 'animated_video_poster' === $image_size ) {
2474              return true;
2475          }
2476  
2477          // Regular image sizes: validate against registered size constraints.
2478          $registered_sizes = wp_get_registered_image_subsizes();
2479  
2480          if ( ! isset( $registered_sizes[ $image_size ] ) ) {
2481              return new WP_Error(
2482                  'rest_upload_unknown_size',
2483                  __( 'Unknown image size.' ),
2484                  array( 'status' => 400 )
2485              );
2486          }
2487  
2488          $size_data  = $registered_sizes[ $image_size ];
2489          $max_width  = (int) $size_data['width'];
2490          $max_height = (int) $size_data['height'];
2491  
2492          // Validate dimensions don't exceed the registered size maximums.
2493          // Allow 1px tolerance for rounding differences.
2494          $tolerance = 1;
2495  
2496          if ( $this->dimension_exceeds_max( $width, $max_width, $tolerance ) ) {
2497              return new WP_Error(
2498                  'rest_upload_dimension_mismatch',
2499                  sprintf(
2500                      /* translators: 1: Image size name, 2: maximum width, 3: actual width. */
2501                      __( 'Uploaded image width (%3$d) exceeds maximum for "%1$s" size (%2$d).' ),
2502                      $image_size,
2503                      $max_width,
2504                      $width
2505                  ),
2506                  array( 'status' => 400 )
2507              );
2508          }
2509  
2510          if ( $this->dimension_exceeds_max( $height, $max_height, $tolerance ) ) {
2511              return new WP_Error(
2512                  'rest_upload_dimension_mismatch',
2513                  sprintf(
2514                      /* translators: 1: Image size name, 2: maximum height, 3: actual height. */
2515                      __( 'Uploaded image height (%3$d) exceeds maximum for "%1$s" size (%2$d).' ),
2516                      $image_size,
2517                      $max_height,
2518                      $height
2519                  ),
2520                  array( 'status' => 400 )
2521              );
2522          }
2523  
2524          return true;
2525      }
2526  
2527      /**
2528       * Checks whether a dimension exceeds the maximum allowed value.
2529       *
2530       * A maximum of zero means the dimension is unconstrained.
2531       *
2532       * @since 7.1.0
2533       *
2534       * @param int $value     The actual dimension in pixels.
2535       * @param int $max       The maximum allowed dimension in pixels. Zero means no constraint.
2536       * @param int $tolerance Pixel tolerance allowed for rounding differences.
2537       * @return bool True if the value exceeds the maximum plus tolerance.
2538       */
2539  	private function dimension_exceeds_max( int $value, int $max, int $tolerance ): bool {
2540          return $max > 0 && $value > $max + $tolerance;
2541      }
2542  
2543      /**
2544       * Side-loads a media file without creating a new attachment.
2545       *
2546       * @since 7.1.0
2547       *
2548       * @param WP_REST_Request $request Full details about the request.
2549       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
2550       */
2551  	public function sideload_item( WP_REST_Request $request ) {
2552          $attachment_id = (int) $request['id'];
2553  
2554          $post = $this->get_post( $attachment_id );
2555  
2556          if ( is_wp_error( $post ) ) {
2557              return $post;
2558          }
2559  
2560          if (
2561              ! wp_attachment_is_image( $post ) &&
2562              ! wp_attachment_is( 'pdf', $post )
2563          ) {
2564              return new WP_Error(
2565                  'rest_post_invalid_id',
2566                  __( 'Invalid post ID. Only images and PDFs can be sideloaded.' ),
2567                  array( 'status' => 400 )
2568              );
2569          }
2570  
2571          if ( false === $request['convert_format'] ) {
2572              // Prevent image conversion as that is done client-side.
2573              add_filter( 'image_editor_output_format', '__return_empty_array', 100 );
2574          }
2575  
2576          // Get the file via $_FILES or raw data.
2577          $files   = $request->get_file_params();
2578          $headers = $request->get_headers();
2579  
2580          /*
2581           * wp_unique_filename() will always add numeric suffix if the name looks like a sub-size to avoid conflicts.
2582           * See /wp-includes/functions.php.
2583           * With the following filter we can work around this safeguard.
2584           */
2585          $attachment_filename = get_attached_file( $attachment_id, true );
2586          $attachment_filename = $attachment_filename ? wp_basename( $attachment_filename ) : null;
2587  
2588          $filter_filename = static function ( $filename, $ext, $dir, $unique_filename_callback, $alt_filenames, $number ) use ( $attachment_filename ) {
2589              return self::filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename );
2590          };
2591  
2592          add_filter( 'wp_unique_filename', $filter_filename, 10, 6 );
2593  
2594          $parent_post = get_post_parent( $attachment_id );
2595  
2596          $time = null;
2597  
2598          // Matches logic in media_handle_upload().
2599          // The post date doesn't usually matter for pages, so don't backdate this upload.
2600          if ( $parent_post && 'page' !== $parent_post->post_type && ! str_starts_with( $parent_post->post_date, '0000-00-00' ) ) {
2601              $time = $parent_post->post_date;
2602          }
2603  
2604          if ( ! empty( $files ) ) {
2605              $file = $this->upload_from_file( $files, $headers, $time );
2606          } else {
2607              $file = $this->upload_from_data( $request->get_body(), $headers, $time );
2608          }
2609  
2610          remove_filter( 'wp_unique_filename', $filter_filename );
2611          remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );
2612  
2613          if ( is_wp_error( $file ) ) {
2614              return $file;
2615          }
2616  
2617          $type = $file['type'];
2618          $path = $file['file'];
2619  
2620          /** @var non-empty-string $image_size */
2621          $image_size = $request['image_size'];
2622  
2623          /*
2624           * Validate raster sub-sizes before storing them. Two companion sizes
2625           * are exempt because wp_getimagesize() may not be able to read the
2626           * file at all: the 'animated_video' companion of an animated GIF is a
2627           * video (MP4/WebM), and a source-format original (e.g. a HEIC or JXL
2628           * kept next to its JPEG derivative) may be an unreadable format. Their
2629           * dimensions are neither validated nor recorded. The
2630           * 'animated_video_poster' companion is a real image, so it is still
2631           * read and rejected if unreadable; validate_image_dimensions() skips
2632           * only the registered-size constraint for it.
2633           */
2634          $skip_dimension_read = in_array( $image_size, array( self::IMAGE_SIZE_SOURCE_ORIGINAL, 'animated_video' ), true );
2635  
2636          if ( ! $skip_dimension_read ) {
2637              /*
2638               * Read the dimensions up front. A file whose dimensions cannot be
2639               * read is corrupted or an unsupported format and must be rejected
2640               * rather than silently stored with zero dimensions.
2641               */
2642              $size = wp_getimagesize( $path );
2643  
2644              if ( ! $size ) {
2645                  // Clean up the uploaded file.
2646                  wp_delete_file( $path );
2647                  return new WP_Error(
2648                      'rest_upload_invalid_image',
2649                      __( 'Could not read image dimensions. The file may be corrupted or an unsupported format.' ),
2650                      array( 'status' => 400 )
2651                  );
2652              }
2653  
2654              /*
2655               * Validate the dimensions match the expected size. An array
2656               * $image_size represents multiple registered sizes sharing a single
2657               * file; those are handled by the per-size branch below, so only
2658               * scalar sizes are validated here.
2659               */
2660              if ( ! is_array( $image_size ) ) {
2661                  $validation = $this->validate_image_dimensions( $size[0], $size[1], $image_size, $attachment_id );
2662                  if ( is_wp_error( $validation ) ) {
2663                      // Clean up the uploaded file.
2664                      wp_delete_file( $path );
2665                      return $validation;
2666                  }
2667              }
2668          }
2669  
2670          // Build sub-size data to return to the client.
2671          // The client accumulates these and sends them all to the finalize
2672          // endpoint, which writes the metadata in a single operation. This
2673          // avoids the read-modify-write race that concurrent sideloads for the
2674          // same attachment would otherwise hit.
2675          $sub_size_data = array(
2676              'image_size' => $image_size,
2677          );
2678  
2679          if ( is_array( $image_size ) ) {
2680              // Multiple registered sizes share these dimensions, so a single
2681              // sideloaded file is reused for all of them. Arrays only carry
2682              // regular sub-sizes; the special keys below are always scalar.
2683              $size = wp_getimagesize( $path );
2684  
2685              $sub_size_data['width']     = $size ? $size[0] : 0;
2686              $sub_size_data['height']    = $size ? $size[1] : 0;
2687              $sub_size_data['file']      = wp_basename( $path );
2688              $sub_size_data['mime_type'] = $type;
2689              $sub_size_data['filesize']  = wp_filesize( $path );
2690          } elseif ( self::IMAGE_SIZE_SOURCE_ORIGINAL === $image_size ) {
2691              /*
2692               * Source-format original (e.g. the HEIC kept next to its JPEG
2693               * derivative). Record the filename so finalize_item can store it
2694               * under the dedicated source-image meta key.
2695               */
2696              $sub_size_data['file'] = wp_basename( $path );
2697          } elseif ( 'animated_video' === $image_size || 'animated_video_poster' === $image_size ) {
2698              /*
2699               * Converted-video companion of an animated GIF (the MP4/WebM or
2700               * its static first-frame poster). Record the filename so
2701               * finalize_item can store it under its dedicated meta key.
2702               */
2703              $sub_size_data['file'] = wp_basename( $path );
2704          } elseif ( 'scaled' === $image_size || 'original' === $image_size ) {
2705              /*
2706               * 'scaled' and 'original' both replace the attachment's main file
2707               * with the supplied image and keep the file being replaced as
2708               * `original_image`, which is the untouched upload. A 'scaled'
2709               * image is downsized and an 'original' image has any EXIF
2710               * orientation already applied. This is the same swap WordPress
2711               * makes when it scales or rotates an image on upload; see
2712               * _wp_image_meta_replace_original().
2713               */
2714              $current_file = get_attached_file( $attachment_id, true );
2715  
2716              if ( ! $current_file ) {
2717                  return new WP_Error(
2718                      'rest_sideload_no_attached_file',
2719                      __( 'Unable to retrieve the attached file for this attachment.' ),
2720                      array( 'status' => 404 )
2721                  );
2722              }
2723  
2724              $sub_size_data['original_image'] = wp_basename( $current_file );
2725  
2726              // Validate the supplied image before updating the attached file.
2727              $size     = wp_getimagesize( $path );
2728              $filesize = wp_filesize( $path );
2729  
2730              if ( ! $size || ! $filesize ) {
2731                  return new WP_Error(
2732                      'rest_sideload_invalid_image',
2733                      __( 'Unable to read the sideloaded image file.' ),
2734                      array( 'status' => 500 )
2735                  );
2736              }
2737  
2738              // Update the attached file to point to the supplied image.
2739              // This writes to _wp_attached_file meta, not _wp_attachment_metadata.
2740              if (
2741                  get_attached_file( $attachment_id, true ) !== $path &&
2742                  ! update_attached_file( $attachment_id, $path )
2743              ) {
2744                  return new WP_Error(
2745                      'rest_sideload_update_attached_file_failed',
2746                      __( 'Unable to update the attached file for this attachment.' ),
2747                      array( 'status' => 500 )
2748                  );
2749              }
2750  
2751              $sub_size_data['width']    = $size[0];
2752              $sub_size_data['height']   = $size[1];
2753              $sub_size_data['filesize'] = $filesize;
2754              $sub_size_data['file']     = _wp_relative_upload_path( $path );
2755          } else {
2756              $size = wp_getimagesize( $path );
2757  
2758              $sub_size_data['width']     = $size ? $size[0] : 0;
2759              $sub_size_data['height']    = $size ? $size[1] : 0;
2760              $sub_size_data['file']      = wp_basename( $path );
2761              $sub_size_data['mime_type'] = $type;
2762              $sub_size_data['filesize']  = wp_filesize( $path );
2763          }
2764  
2765          return rest_ensure_response( $sub_size_data );
2766      }
2767  
2768      /**
2769       * Filters wp_unique_filename during sideloads.
2770       *
2771       * wp_unique_filename() will always add numeric suffix if the name looks like a sub-size to avoid conflicts.
2772       * Adding this closure to the filter helps work around this safeguard.
2773       *
2774       * Example: when uploading myphoto.jpeg, WordPress normally creates myphoto-150x150.jpeg,
2775       * and when uploading myphoto-150x150.jpeg, it will be renamed to myphoto-150x150-1.jpeg
2776       * However, here it is desired not to add the suffix in order to maintain the same
2777       * naming convention as if the file was uploaded regularly.
2778       *
2779       * @since 7.1.0
2780       *
2781       * @link https://github.com/WordPress/wordpress-develop/blob/30954f7ac0840cfdad464928021d7f380940c347/src/wp-includes/functions.php#L2576-L2582
2782       *
2783       * @param string      $filename            Unique file name.
2784       * @param string      $dir                 Directory path.
2785       * @param int|string  $number              The highest number that was used to make the file name unique
2786       *                                         or an empty string if unused.
2787       * @param string|null $attachment_filename Original attachment file name.
2788       * @return string Filtered file name.
2789       */
2790  	private static function filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename ) {
2791          if ( ! is_int( $number ) || ! $attachment_filename ) {
2792              return $filename;
2793          }
2794  
2795          $ext       = pathinfo( $filename, PATHINFO_EXTENSION );
2796          $name      = pathinfo( $filename, PATHINFO_FILENAME );
2797          $orig_name = pathinfo( $attachment_filename, PATHINFO_FILENAME );
2798  
2799          if ( ! $ext || ! $name ) {
2800              return $filename;
2801          }
2802  
2803          $matches = array();
2804          if ( preg_match( '/(.*)-(\d+x\d+|scaled)-' . $number . '$/', $name, $matches ) ) {
2805              $filename_without_suffix = $matches[1] . '-' . $matches[2] . ".$ext";
2806              if ( $matches[1] === $orig_name && ! file_exists( "$dir/$filename_without_suffix" ) ) {
2807                  return $filename_without_suffix;
2808              }
2809          }
2810  
2811          return $filename;
2812      }
2813  
2814      /**
2815       * Finalizes an attachment after client-side media processing.
2816       *
2817       * Applies the sub-size metadata collected from sideload responses in a
2818       * single metadata update, then triggers the 'wp_generate_attachment_metadata'
2819       * filter so that server-side plugins can process the attachment after all
2820       * client-side operations (upload, thumbnail generation, sideloads) are
2821       * complete.
2822       *
2823       * @since 7.1.0
2824       *
2825       * @param WP_REST_Request $request Full details about the request.
2826       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
2827       */
2828  	public function finalize_item( WP_REST_Request $request ) {
2829          $attachment_id = (int) $request['id'];
2830  
2831          $post = $this->get_post( $attachment_id );
2832          if ( is_wp_error( $post ) ) {
2833              return $post;
2834          }
2835  
2836          $metadata = wp_get_attachment_metadata( $attachment_id );
2837          if ( ! is_array( $metadata ) ) {
2838              $metadata = array();
2839          }
2840  
2841          // Apply all sub-size metadata collected from sideload responses.
2842          $sub_sizes = $request['sub_sizes'] ?? array();
2843  
2844          foreach ( $sub_sizes as $sub_size ) {
2845              $image_size = $sub_size['image_size'];
2846  
2847              // When multiple size names share identical dimensions the client
2848              // sends a single sub-size entry with an array of names. Register the
2849              // same file under each name. Arrays only contain regular sizes.
2850              if ( is_array( $image_size ) ) {
2851                  $metadata['sizes'] = $metadata['sizes'] ?? array();
2852  
2853                  foreach ( $image_size as $name ) {
2854                      $metadata['sizes'][ $name ] = array(
2855                          'width'     => $sub_size['width'] ?? 0,
2856                          'height'    => $sub_size['height'] ?? 0,
2857                          'file'      => $sub_size['file'] ?? '',
2858                          'mime-type' => $sub_size['mime_type'] ?? '',
2859                          'filesize'  => $sub_size['filesize'] ?? 0,
2860                      );
2861                  }
2862                  continue;
2863              }
2864  
2865              if ( 'original' === $image_size || 'scaled' === $image_size ) {
2866                  // Skip malformed entries so a bad payload cannot blank out the
2867                  // main file metadata.
2868                  if ( empty( $sub_size['file'] ) ) {
2869                      continue;
2870                  }
2871  
2872                  /*
2873                   * Record the supplied full-size image (from sideload_item()) as
2874                   * the main file, keeping the current attached file as
2875                   * `original_image`. A 'scaled' image is downsized and an
2876                   * 'original' image is rotated; both have any EXIF orientation
2877                   * already applied by the client.
2878                   */
2879                  if ( ! empty( $sub_size['original_image'] ) ) {
2880                      $metadata['original_image'] = $sub_size['original_image'];
2881                  }
2882                  $metadata['width']    = $sub_size['width'] ?? 0;
2883                  $metadata['height']   = $sub_size['height'] ?? 0;
2884                  $metadata['filesize'] = $sub_size['filesize'] ?? 0;
2885                  $metadata['file']     = $sub_size['file'];
2886  
2887                  /*
2888                   * The supplied image has its orientation applied already, so
2889                   * reset the stored value (from the upload) to 1, as
2890                   * wp_create_image_subsizes() does for both its scale and rotate
2891                   * paths. Otherwise exif_orientation would still report the
2892                   * pre-rotation value and the client would rotate the image
2893                   * again on a re-fetch.
2894                   */
2895                  if ( ! empty( $metadata['image_meta']['orientation'] ) ) {
2896                      $metadata['image_meta']['orientation'] = 1;
2897                  }
2898              } elseif ( self::IMAGE_SIZE_SOURCE_ORIGINAL === $image_size ) {
2899                  /*
2900                   * Source-format original: stored under its own meta key so the
2901                   * scaled-sideload flow (which writes 'original_image') cannot
2902                   * clobber it. 'original_image' keeps pointing at the
2903                   * web-viewable JPEG derivative. Cleanup on attachment delete
2904                   * is handled by wp_delete_attachment_files().
2905                   */
2906                  $metadata[ self::META_KEY_SOURCE_IMAGE ] = $sub_size['file'];
2907              } elseif ( 'animated_video' === $image_size ) {
2908                  /*
2909                   * Converted-video companion of an animated GIF. Stored under its
2910                   * own meta key; 'original_image' keeps pointing at the GIF. Cleanup
2911                   * on attachment delete is handled by wp_delete_attachment_files().
2912                   */
2913                  $metadata['animated_video'] = $sub_size['file'];
2914              } elseif ( 'animated_video_poster' === $image_size ) {
2915                  // Static first-frame poster for the converted video.
2916                  $metadata['animated_video_poster'] = $sub_size['file'];
2917              } else {
2918                  $metadata['sizes'] = $metadata['sizes'] ?? array();
2919  
2920                  $metadata['sizes'][ $image_size ] = array(
2921                      'width'     => $sub_size['width'] ?? 0,
2922                      'height'    => $sub_size['height'] ?? 0,
2923                      'file'      => $sub_size['file'] ?? '',
2924                      'mime-type' => $sub_size['mime_type'] ?? '',
2925                      'filesize'  => $sub_size['filesize'] ?? 0,
2926                  );
2927              }
2928          }
2929  
2930          /** This filter is documented in wp-admin/includes/image.php */
2931          $metadata = apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id, 'update' );
2932  
2933          wp_update_attachment_metadata( $attachment_id, $metadata );
2934  
2935          $response_request = new WP_REST_Request(
2936              WP_REST_Server::READABLE,
2937              rest_get_route_for_post( $attachment_id )
2938          );
2939  
2940          $response_request['context'] = 'edit';
2941  
2942          if ( isset( $request['_fields'] ) ) {
2943              $response_request['_fields'] = $request['_fields'];
2944          }
2945  
2946          return $this->prepare_item_for_response( $post, $response_request );
2947      }
2948  }


Generated : Sun Aug 2 08:20:19 2026 Cross-referenced by PHPXref