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


Generated : Fri Aug 14 08:20:23 2026 Cross-referenced by PHPXref