[ 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 ??= $original_attachment_post->post_title ?? $image_name;
1295  
1296          // Set new attachment post caption (post_excerpt).
1297          $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 ??= $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 ??= 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           * Record the attachment this chain of edits started from, so the edit root can be
1361           * found in one lookup from any image later in the chain. The new attachment inherits
1362           * the edit root recorded on the image being edited, or that image itself when it was
1363           * uploaded rather than edited.
1364           */
1365          $edit_root_id = wp_get_edit_root_attachment_id( $attachment_id );
1366  
1367          if ( ! $edit_root_id ) {
1368              $edit_root_id = (int) $attachment_id;
1369          }
1370  
1371          update_post_meta( $new_attachment_id, '_wp_attachment_edit_root_id', $edit_root_id );
1372  
1373          /**
1374           * Filters the meta data for the new image created by editing an existing image.
1375           *
1376           * @since 5.5.0
1377           *
1378           * @param array $new_image_meta    Meta data for the new image.
1379           * @param int   $new_attachment_id Attachment post ID for the new image.
1380           * @param int   $attachment_id     Attachment post ID for the edited (parent) image.
1381           */
1382          $new_image_meta = apply_filters( 'wp_edited_image_metadata', $new_image_meta, $new_attachment_id, $attachment_id );
1383  
1384          wp_update_attachment_metadata( $new_attachment_id, $new_image_meta );
1385  
1386          $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request );
1387          $response->set_status( 201 );
1388          $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) );
1389  
1390          return $response;
1391      }
1392  
1393      /**
1394       * Prepares a single attachment for create or update.
1395       *
1396       * @since 4.7.0
1397       *
1398       * @param WP_REST_Request $request Request object.
1399       * @return stdClass|WP_Error Post object.
1400       */
1401  	protected function prepare_item_for_database( $request ) {
1402          $prepared_attachment = parent::prepare_item_for_database( $request );
1403  
1404          // Attachment caption (post_excerpt internally).
1405          if ( isset( $request['caption'] ) ) {
1406              if ( is_string( $request['caption'] ) ) {
1407                  $prepared_attachment->post_excerpt = $request['caption'];
1408              } elseif ( isset( $request['caption']['raw'] ) ) {
1409                  $prepared_attachment->post_excerpt = $request['caption']['raw'];
1410              }
1411          }
1412  
1413          // Attachment description (post_content internally).
1414          if ( isset( $request['description'] ) ) {
1415              if ( is_string( $request['description'] ) ) {
1416                  $prepared_attachment->post_content = $request['description'];
1417              } elseif ( isset( $request['description']['raw'] ) ) {
1418                  $prepared_attachment->post_content = $request['description']['raw'];
1419              }
1420          }
1421  
1422          if ( isset( $request['post'] ) ) {
1423              $prepared_attachment->post_parent = (int) $request['post'];
1424          }
1425  
1426          return $prepared_attachment;
1427      }
1428  
1429      /**
1430       * Prepares a single attachment output for response.
1431       *
1432       * @since 4.7.0
1433       * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
1434       *
1435       * @param WP_Post         $item    Attachment object.
1436       * @param WP_REST_Request $request Request object.
1437       * @return WP_REST_Response Response object.
1438       */
1439  	public function prepare_item_for_response( $item, $request ) {
1440          // Restores the more descriptive, specific name for use within this method.
1441          $post = $item;
1442  
1443          $response = parent::prepare_item_for_response( $post, $request );
1444          $fields   = $this->get_fields_for_response( $request );
1445          /** @var array<string, mixed> $data */
1446          $data = $response->get_data();
1447  
1448          if ( in_array( 'description', $fields, true ) ) {
1449              $data['description'] = array(
1450                  'raw'      => $post->post_content,
1451                  /** This filter is documented in wp-includes/post-template.php */
1452                  'rendered' => apply_filters( 'the_content', $post->post_content ),
1453              );
1454          }
1455  
1456          if ( in_array( 'caption', $fields, true ) ) {
1457              /** This filter is documented in wp-includes/post-template.php */
1458              $caption = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
1459  
1460              /** This filter is documented in wp-includes/post-template.php */
1461              $caption = apply_filters( 'the_excerpt', $caption );
1462  
1463              $data['caption'] = array(
1464                  'raw'      => $post->post_excerpt,
1465                  'rendered' => $caption,
1466              );
1467          }
1468  
1469          if ( in_array( 'alt_text', $fields, true ) ) {
1470              $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
1471          }
1472  
1473          if ( in_array( 'media_type', $fields, true ) ) {
1474              $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
1475          }
1476  
1477          if ( in_array( 'mime_type', $fields, true ) ) {
1478              $data['mime_type'] = $post->post_mime_type;
1479          }
1480  
1481          if ( in_array( 'media_details', $fields, true ) ) {
1482              $data['media_details'] = wp_get_attachment_metadata( $post->ID );
1483  
1484              // Ensure empty details is an empty object.
1485              if ( empty( $data['media_details'] ) ) {
1486                  $data['media_details'] = new stdClass();
1487              } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
1488  
1489                  foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
1490  
1491                      if ( isset( $size_data['mime-type'] ) ) {
1492                          $size_data['mime_type'] = $size_data['mime-type'];
1493                          unset( $size_data['mime-type'] );
1494                      }
1495  
1496                      // Use the same method image_downsize() does.
1497                      $image_src = wp_get_attachment_image_src( $post->ID, $size );
1498                      if ( ! $image_src ) {
1499                          continue;
1500                      }
1501  
1502                      $size_data['source_url'] = $image_src[0];
1503                  }
1504                  unset( $size_data );
1505  
1506                  $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
1507  
1508                  if ( ! empty( $full_src ) ) {
1509                      $data['media_details']['sizes']['full'] = array(
1510                          'file'       => wp_basename( $full_src[0] ),
1511                          'width'      => $full_src[1],
1512                          'height'     => $full_src[2],
1513                          'mime_type'  => $post->post_mime_type,
1514                          'source_url' => $full_src[0],
1515                      );
1516                  }
1517              } else {
1518                  $data['media_details']['sizes'] = new stdClass();
1519              }
1520          }
1521  
1522          if ( in_array( 'post', $fields, true ) ) {
1523              $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
1524          }
1525  
1526          /*
1527           * ID of the attachment this image's chain of edits started from, or 0.
1528           * Edit context only, since only editors need it.
1529           * Not validated: deleting an attachment clears it from images edited from it.
1530           */
1531          if ( in_array( 'edit_root', $fields, true ) && 'edit' === $request['context'] ) {
1532              $data['edit_root'] = wp_get_edit_root_attachment_id( $post->ID );
1533          }
1534  
1535          if ( in_array( 'source_url', $fields, true ) ) {
1536              $data['source_url'] = wp_get_attachment_url( $post->ID );
1537          }
1538  
1539          if ( in_array( 'missing_image_sizes', $fields, true ) ) {
1540              require_once  ABSPATH . 'wp-admin/includes/image.php';
1541              $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) );
1542  
1543              // Handle PDFs which don't use wp_get_missing_image_subsizes().
1544              if ( empty( $data['missing_image_sizes'] ) && 'application/pdf' === get_post_mime_type( $post ) ) {
1545                  $metadata = wp_get_attachment_metadata( $post->ID, true );
1546  
1547                  if ( ! is_array( $metadata ) ) {
1548                      $metadata = array();
1549                  }
1550  
1551                  $metadata['sizes'] ??= array();
1552  
1553                  $fallback_sizes = array(
1554                      'thumbnail',
1555                      'medium',
1556                      'large',
1557                  );
1558  
1559                  // The filter might have been added by ::create_item().
1560                  remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
1561  
1562                  /** This filter is documented in wp-admin/includes/image.php */
1563                  $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
1564  
1565                  $registered_sizes = wp_get_registered_image_subsizes();
1566                  $merged_sizes     = array_keys( array_intersect_key( $registered_sizes, array_flip( $fallback_sizes ) ) );
1567  
1568                  $data['missing_image_sizes'] = array_values( array_diff( $merged_sizes, array_keys( $metadata['sizes'] ) ) );
1569              }
1570          }
1571  
1572          if ( in_array( 'filename', $fields, true ) ) {
1573              $data['filename'] = $this->get_attachment_filename( $post->ID );
1574          }
1575  
1576          if ( in_array( 'filesize', $fields, true ) ) {
1577              $data['filesize'] = $this->get_attachment_filesize( $post->ID );
1578          }
1579  
1580          if ( in_array( 'exif_orientation', $fields, true ) && wp_attachment_is_image( $post ) ) {
1581              $metadata = wp_get_attachment_metadata( $post->ID, true );
1582  
1583              // Default to 1 (no rotation needed) if orientation not set.
1584              $orientation = 1;
1585  
1586              if (
1587                  is_array( $metadata ) &&
1588                  isset( $metadata['image_meta']['orientation'] ) &&
1589                  (int) $metadata['image_meta']['orientation'] > 0
1590              ) {
1591                  $orientation = (int) $metadata['image_meta']['orientation'];
1592              }
1593  
1594              $data['exif_orientation'] = $orientation;
1595          }
1596  
1597          if ( wp_attachment_is_image( $post ) ) {
1598              $mime_type = (string) get_post_mime_type( $post );
1599  
1600              /*
1601               * Per-file output format for images, evaluated with the real filename
1602               * and MIME type so plugins filtering image_editor_output_format can
1603               * make per-attachment decisions (e.g. JPEG -> WebP). Resolved the same
1604               * way WP_Image_Editor::set_quality() resolves the output format.
1605               */
1606              if ( in_array( 'image_output_format', $fields, true ) ) {
1607                  $filename = get_attached_file( $post->ID );
1608  
1609                  /** This filter is documented in wp-includes/media.php */
1610                  $output_formats = apply_filters(
1611                      'image_editor_output_format',
1612                      array( $mime_type => $mime_type ),
1613                      $filename ? $filename : '',
1614                      $mime_type
1615                  );
1616  
1617                  $output_mime                 = $output_formats[ $mime_type ] ?? $mime_type;
1618                  $data['image_output_format'] = ( $output_mime !== $mime_type ) ? $output_mime : null;
1619              }
1620  
1621              /*
1622               * Per-file progressive/interlaced encoding flag for images, evaluated
1623               * against the attachment's MIME type.
1624               */
1625              if ( in_array( 'image_save_progressive', $fields, true ) ) {
1626                  /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */
1627                  $data['image_save_progressive'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type );
1628              }
1629  
1630              if ( in_array( 'image_quality', $fields, true ) ) {
1631                  $filename = get_attached_file( $post->ID );
1632  
1633                  /** This filter is documented in wp-includes/media.php */
1634                  $output_formats = apply_filters(
1635                      'image_editor_output_format',
1636                      array( $mime_type => $mime_type ),
1637                      $filename ? $filename : '',
1638                      $mime_type
1639                  );
1640                  $output_mime    = $output_formats[ $mime_type ] ?? $mime_type;
1641  
1642                  $metadata    = wp_get_attachment_metadata( $post->ID, true );
1643                  $full_width  = max( 0, ( is_array( $metadata ) && isset( $metadata['width'] ) ) ? (int) $metadata['width'] : 0 );
1644                  $full_height = max( 0, ( is_array( $metadata ) && isset( $metadata['height'] ) ) ? (int) $metadata['height'] : 0 );
1645  
1646                  $full_quality = wp_get_image_encode_quality(
1647                      $output_mime,
1648                      array(
1649                          'width'  => $full_width,
1650                          'height' => $full_height,
1651                      )
1652                  );
1653  
1654                  $size_quality = array();
1655  
1656                  foreach ( wp_get_registered_image_subsizes() as $size_name => $size_data ) {
1657                      $quality = wp_get_image_encode_quality(
1658                          $output_mime,
1659                          array(
1660                              'width'  => (int) $size_data['width'],
1661                              'height' => (int) $size_data['height'],
1662                          )
1663                      );
1664  
1665                      // Only report sizes whose quality diverges from the full-size value.
1666                      if ( $quality !== $full_quality ) {
1667                          $size_quality[ $size_name ] = $quality;
1668                      }
1669                  }
1670  
1671                  $data['image_quality'] = array(
1672                      'default' => $full_quality,
1673                      'sizes'   => $size_quality,
1674                  );
1675              }
1676          }
1677  
1678          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1679  
1680          $data = $this->filter_response_by_context( $data, $context );
1681  
1682          $links = $response->get_links();
1683  
1684          // Wrap the data in a response object.
1685          $response = rest_ensure_response( $data );
1686  
1687          foreach ( $links as $rel => $rel_links ) {
1688              foreach ( $rel_links as $link ) {
1689                  $response->add_link( $rel, $link['href'], $link['attributes'] );
1690              }
1691          }
1692  
1693          /*
1694           * Embeddable link to the edit root, like `featured_media`. Added here rather than
1695           * in `prepare_links()`, which cannot see the request, and gated like the parent
1696           * controller's own links so a `_fields` request is not handed a stray `_links`.
1697           * Like `featured_media`, the link is skipped when the edit root no longer exists
1698           * or the user cannot read it, although the `edit_root` field still reports the ID.
1699           */
1700          if (
1701              'edit' === $request['context'] &&
1702              ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) )
1703          ) {
1704              $edit_root_id = wp_get_edit_root_attachment_id( $post->ID );
1705  
1706              if (
1707                  $edit_root_id &&
1708                  ( 'publish' === get_post_status( $edit_root_id ) || current_user_can( 'read_post', $edit_root_id ) )
1709              ) {
1710                  $response->add_link(
1711                      'https://api.w.org/edit-root',
1712                      rest_url( rest_get_route_for_post( $edit_root_id ) ),
1713                      array( 'embeddable' => true )
1714                  );
1715              }
1716          }
1717  
1718          /**
1719           * Filters an attachment returned from the REST API.
1720           *
1721           * Allows modification of the attachment right before it is returned.
1722           *
1723           * @since 4.7.0
1724           *
1725           * @param WP_REST_Response $response The response object.
1726           * @param WP_Post          $post     The original attachment post.
1727           * @param WP_REST_Request  $request  Request used to generate the response.
1728           */
1729          return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
1730      }
1731  
1732      /**
1733       * Prepares attachment links for the request.
1734       *
1735       * @since 6.9.0
1736       *
1737       * @param WP_Post $post Post object.
1738       * @return array Links for the given attachment.
1739       */
1740  	protected function prepare_links( $post ) {
1741          $links = parent::prepare_links( $post );
1742  
1743          if ( ! empty( $post->post_parent ) ) {
1744              $post = get_post( $post->post_parent );
1745  
1746              if ( ! empty( $post ) ) {
1747                  $links['https://api.w.org/attached-to'] = array(
1748                      'href'       => rest_url( rest_get_route_for_post( $post ) ),
1749                      'embeddable' => true,
1750                      'post_type'  => $post->post_type,
1751                      'id'         => $post->ID,
1752                  );
1753              }
1754          }
1755  
1756          return $links;
1757      }
1758  
1759      /**
1760       * Retrieves the attachment's schema, conforming to JSON Schema.
1761       *
1762       * @since 4.7.0
1763       *
1764       * @return array Item schema as an array.
1765       */
1766  	public function get_item_schema() {
1767          if ( $this->schema ) {
1768              return $this->add_additional_fields_schema( $this->schema );
1769          }
1770  
1771          $schema = parent::get_item_schema();
1772  
1773          $schema['properties']['alt_text'] = array(
1774              'description' => __( 'Alternative text to display when attachment is not displayed.' ),
1775              'type'        => 'string',
1776              'context'     => array( 'view', 'edit', 'embed' ),
1777              'arg_options' => array(
1778                  'sanitize_callback' => 'sanitize_text_field',
1779              ),
1780          );
1781  
1782          $schema['properties']['caption'] = array(
1783              'description' => __( 'The attachment caption.' ),
1784              'type'        => 'object',
1785              'context'     => array( 'view', 'edit', 'embed' ),
1786              'arg_options' => array(
1787                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
1788                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
1789              ),
1790              'properties'  => array(
1791                  'raw'      => array(
1792                      'description' => __( 'Caption for the attachment, as it exists in the database.' ),
1793                      'type'        => 'string',
1794                      'context'     => array( 'edit' ),
1795                  ),
1796                  'rendered' => array(
1797                      'description' => __( 'HTML caption for the attachment, transformed for display.' ),
1798                      'type'        => 'string',
1799                      'context'     => array( 'view', 'edit', 'embed' ),
1800                      'readonly'    => true,
1801                  ),
1802              ),
1803          );
1804  
1805          $schema['properties']['description'] = array(
1806              'description' => __( 'The attachment description.' ),
1807              'type'        => 'object',
1808              'context'     => array( 'view', 'edit' ),
1809              'arg_options' => array(
1810                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
1811                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
1812              ),
1813              'properties'  => array(
1814                  'raw'      => array(
1815                      'description' => __( 'Description for the attachment, as it exists in the database.' ),
1816                      'type'        => 'string',
1817                      'context'     => array( 'edit' ),
1818                  ),
1819                  'rendered' => array(
1820                      'description' => __( 'HTML description for the attachment, transformed for display.' ),
1821                      'type'        => 'string',
1822                      'context'     => array( 'view', 'edit' ),
1823                      'readonly'    => true,
1824                  ),
1825              ),
1826          );
1827  
1828          $schema['properties']['media_type'] = array(
1829              'description' => __( 'Attachment type.' ),
1830              'type'        => 'string',
1831              'enum'        => array( 'image', 'file' ),
1832              'context'     => array( 'view', 'edit', 'embed' ),
1833              'readonly'    => true,
1834          );
1835  
1836          $schema['properties']['mime_type'] = array(
1837              'description' => __( 'The attachment MIME type.' ),
1838              'type'        => 'string',
1839              'context'     => array( 'view', 'edit', 'embed' ),
1840              'readonly'    => true,
1841          );
1842  
1843          $schema['properties']['media_details'] = array(
1844              'description' => __( 'Details about the media file, specific to its type.' ),
1845              'type'        => 'object',
1846              'context'     => array( 'view', 'edit', 'embed' ),
1847              'readonly'    => true,
1848          );
1849  
1850          $schema['properties']['post'] = array(
1851              'description' => __( 'The ID for the associated post of the attachment.' ),
1852              'type'        => 'integer',
1853              'context'     => array( 'view', 'edit' ),
1854          );
1855  
1856          $schema['properties']['edit_root'] = array(
1857              'description' => __( 'The ID of the attachment this attachment\'s chain of edits started from, or 0 if none is recorded.' ),
1858              'type'        => 'integer',
1859              'context'     => array( 'edit' ),
1860              'readonly'    => true,
1861          );
1862  
1863          $schema['properties']['source_url'] = array(
1864              'description' => __( 'URL to the original attachment file.' ),
1865              'type'        => 'string',
1866              'format'      => 'uri',
1867              'context'     => array( 'view', 'edit', 'embed' ),
1868              'readonly'    => true,
1869          );
1870  
1871          $schema['properties']['missing_image_sizes'] = array(
1872              'description' => __( 'List of the missing image sizes of the attachment.' ),
1873              'type'        => 'array',
1874              'items'       => array( 'type' => 'string' ),
1875              'context'     => array( 'edit' ),
1876              'readonly'    => true,
1877          );
1878  
1879          $schema['properties']['filename'] = array(
1880              'description' => __( 'Original attachment file name.' ),
1881              'type'        => 'string',
1882              'context'     => array( 'view', 'edit' ),
1883              'readonly'    => true,
1884          );
1885  
1886          $schema['properties']['filesize'] = array(
1887              'description' => __( 'Attachment file size in bytes.' ),
1888              'type'        => array( 'integer', 'null' ),
1889              'context'     => array( 'view', 'edit' ),
1890              'readonly'    => true,
1891          );
1892  
1893          $schema['properties']['exif_orientation'] = array(
1894              'description' => __( 'EXIF orientation value. Values 1-8 follow the EXIF specification, where 1 means no rotation needed.' ),
1895              'type'        => 'integer',
1896              'context'     => array( 'edit' ),
1897              'readonly'    => true,
1898          );
1899  
1900          // Enumerate the registered sub-sizes so the schema documents exactly which
1901          // keys may appear under "sizes".
1902          $size_quality_properties = array();
1903          foreach ( array_keys( wp_get_registered_image_subsizes() ) as $size_name ) {
1904              $size_quality_properties[ $size_name ] = array(
1905                  'type'    => 'integer',
1906                  'minimum' => 1,
1907                  'maximum' => 100,
1908              );
1909          }
1910  
1911          $schema['properties']['image_quality'] = array(
1912              '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".' ),
1913              'type'        => 'object',
1914              'context'     => array( 'edit' ),
1915              'readonly'    => true,
1916              'properties'  => array(
1917                  'default' => array(
1918                      'type'    => 'integer',
1919                      'minimum' => 1,
1920                      'maximum' => 100,
1921                  ),
1922                  'sizes'   => array(
1923                      'type'       => 'object',
1924                      'properties' => $size_quality_properties,
1925                  ),
1926              ),
1927          );
1928  
1929          $schema['properties']['image_output_format'] = array(
1930              '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.' ),
1931              'type'        => array( 'string', 'null' ),
1932              'context'     => array( 'edit' ),
1933              'readonly'    => true,
1934          );
1935  
1936          $schema['properties']['image_save_progressive'] = array(
1937              'description' => __( 'Whether to use progressive/interlaced encoding when saving this image.' ),
1938              'type'        => 'boolean',
1939              'context'     => array( 'edit' ),
1940              'readonly'    => true,
1941          );
1942  
1943          unset( $schema['properties']['password'] );
1944  
1945          $this->schema = $schema;
1946  
1947          return $this->add_additional_fields_schema( $this->schema );
1948      }
1949  
1950      /**
1951       * Handles an upload via raw POST data.
1952       *
1953       * @since 4.7.0
1954       * @since 6.6.0 Added the `$time` parameter.
1955       *
1956       * @param string      $data    Supplied file data.
1957       * @param array       $headers HTTP headers from the request.
1958       * @param string|null $time    Optional. Time formatted in 'yyyy/mm'. Default null.
1959       * @return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string }|WP_Error Data from wp_handle_sideload().
1960       */
1961  	protected function upload_from_data( $data, $headers, $time = null ) {
1962          if ( empty( $data ) ) {
1963              return new WP_Error(
1964                  'rest_upload_no_data',
1965                  __( 'No data supplied.' ),
1966                  array( 'status' => 400 )
1967              );
1968          }
1969  
1970          if ( empty( $headers['content_type'] ) ) {
1971              return new WP_Error(
1972                  'rest_upload_no_content_type',
1973                  __( 'No Content-Type supplied.' ),
1974                  array( 'status' => 400 )
1975              );
1976          }
1977  
1978          if ( empty( $headers['content_disposition'] ) ) {
1979              return new WP_Error(
1980                  'rest_upload_no_content_disposition',
1981                  __( 'No Content-Disposition supplied.' ),
1982                  array( 'status' => 400 )
1983              );
1984          }
1985  
1986          $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
1987  
1988          if ( empty( $filename ) ) {
1989              return new WP_Error(
1990                  'rest_upload_invalid_disposition',
1991                  __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ),
1992                  array( 'status' => 400 )
1993              );
1994          }
1995  
1996          if ( ! empty( $headers['content_md5'] ) ) {
1997              $content_md5 = array_shift( $headers['content_md5'] );
1998              $expected    = trim( $content_md5 );
1999              $actual      = md5( $data );
2000  
2001              if ( $expected !== $actual ) {
2002                  return new WP_Error(
2003                      'rest_upload_hash_mismatch',
2004                      __( 'Content hash did not match expected.' ),
2005                      array( 'status' => 412 )
2006                  );
2007              }
2008          }
2009  
2010          // Get the content-type.
2011          $type = array_shift( $headers['content_type'] );
2012  
2013          // Include filesystem functions to get access to wp_tempnam() and wp_handle_sideload().
2014          require_once  ABSPATH . 'wp-admin/includes/file.php';
2015  
2016          // Save the file.
2017          $tmpfname = wp_tempnam( $filename );
2018  
2019          $fp = fopen( $tmpfname, 'w+' );
2020  
2021          if ( ! $fp ) {
2022              return new WP_Error(
2023                  'rest_upload_file_error',
2024                  __( 'Could not open file handle.' ),
2025                  array( 'status' => 500 )
2026              );
2027          }
2028  
2029          fwrite( $fp, $data );
2030          fclose( $fp );
2031  
2032          // Now, sideload it in.
2033          $file_data = array(
2034              'error'    => null,
2035              'tmp_name' => $tmpfname,
2036              'name'     => $filename,
2037              'type'     => $type,
2038          );
2039  
2040          $size_check = self::check_upload_size( $file_data );
2041          if ( is_wp_error( $size_check ) ) {
2042              return $size_check;
2043          }
2044  
2045          $overrides = array(
2046              'test_form' => false,
2047          );
2048  
2049          $sideloaded = wp_handle_sideload( $file_data, $overrides, $time );
2050  
2051          if ( isset( $sideloaded['error'] ) ) {
2052              @unlink( $tmpfname );
2053  
2054              return new WP_Error(
2055                  'rest_upload_sideload_error',
2056                  $sideloaded['error'],
2057                  array( 'status' => 500 )
2058              );
2059          }
2060  
2061          return $sideloaded;
2062      }
2063  
2064      /**
2065       * Parses filename from a Content-Disposition header value.
2066       *
2067       * As per RFC6266:
2068       *
2069       *     content-disposition = "Content-Disposition" ":"
2070       *                            disposition-type *( ";" disposition-parm )
2071       *
2072       *     disposition-type    = "inline" | "attachment" | disp-ext-type
2073       *                         ; case-insensitive
2074       *     disp-ext-type       = token
2075       *
2076       *     disposition-parm    = filename-parm | disp-ext-parm
2077       *
2078       *     filename-parm       = "filename" "=" value
2079       *                         | "filename*" "=" ext-value
2080       *
2081       *     disp-ext-parm       = token "=" value
2082       *                         | ext-token "=" ext-value
2083       *     ext-token           = <the characters in token, followed by "*">
2084       *
2085       * @since 4.7.0
2086       *
2087       * @link https://tools.ietf.org/html/rfc2388
2088       * @link https://tools.ietf.org/html/rfc6266
2089       *
2090       * @param string[] $disposition_header List of Content-Disposition header values.
2091       * @return string|null Filename if available, or null if not found.
2092       */
2093  	public static function get_filename_from_disposition( $disposition_header ) {
2094          // Get the filename.
2095          $filename = null;
2096  
2097          foreach ( $disposition_header as $value ) {
2098              $value = trim( $value );
2099  
2100              if ( ! str_contains( $value, ';' ) ) {
2101                  continue;
2102              }
2103  
2104              list( , $attr_parts ) = explode( ';', $value, 2 );
2105  
2106              $attr_parts = explode( ';', $attr_parts );
2107              $attributes = array();
2108  
2109              foreach ( $attr_parts as $part ) {
2110                  if ( ! str_contains( $part, '=' ) ) {
2111                      continue;
2112                  }
2113  
2114                  list( $key, $value ) = explode( '=', $part, 2 );
2115  
2116                  $attributes[ trim( $key ) ] = trim( $value );
2117              }
2118  
2119              if ( empty( $attributes['filename'] ) ) {
2120                  continue;
2121              }
2122  
2123              $filename = trim( $attributes['filename'] );
2124  
2125              // Unquote quoted filename, but after trimming.
2126              if ( str_starts_with( $filename, '"' ) && str_ends_with( $filename, '"' ) ) {
2127                  $filename = substr( $filename, 1, -1 );
2128              }
2129          }
2130  
2131          return $filename;
2132      }
2133  
2134      /**
2135       * Retrieves the query params for collections of attachments.
2136       *
2137       * @since 4.7.0
2138       * @since 6.9.0 Extends the `media_type` and `mime_type` request arguments to support array values.
2139       *
2140       * @return array Query parameters for the attachment collection as an array.
2141       */
2142  	public function get_collection_params() {
2143          $params                            = parent::get_collection_params();
2144          $params['status']['default']       = 'inherit';
2145          $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
2146          $media_types                       = array_keys( $this->get_media_types() );
2147  
2148          $params['media_type'] = array(
2149              'default'     => null,
2150              'description' => __( 'Limit result set to attachments of a particular media type or media types.' ),
2151              'type'        => 'array',
2152              'items'       => array(
2153                  'type' => 'string',
2154                  'enum' => $media_types,
2155              ),
2156          );
2157  
2158          $params['mime_type'] = array(
2159              'default'     => null,
2160              'description' => __( 'Limit result set to attachments of a particular MIME type or MIME types.' ),
2161              'type'        => 'array',
2162              'items'       => array(
2163                  'type' => 'string',
2164              ),
2165          );
2166  
2167          return $params;
2168      }
2169  
2170      /**
2171       * Handles an upload via multipart/form-data ($_FILES).
2172       *
2173       * @since 4.7.0
2174       * @since 6.6.0 Added the `$time` parameter.
2175       *
2176       * @param array       $files   Data from the `$_FILES` superglobal.
2177       * @param array       $headers HTTP headers from the request.
2178       * @param string|null $time    Optional. Time formatted in 'yyyy/mm'. Default null.
2179       * @return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string }|WP_Error Data from wp_handle_upload().
2180       */
2181  	protected function upload_from_file( $files, $headers, $time = null ) {
2182          if ( empty( $files ) ) {
2183              return new WP_Error(
2184                  'rest_upload_no_data',
2185                  __( 'No data supplied.' ),
2186                  array( 'status' => 400 )
2187              );
2188          }
2189  
2190          // Verify hash, if given.
2191          if ( ! empty( $headers['content_md5'] ) ) {
2192              $content_md5 = array_shift( $headers['content_md5'] );
2193              $expected    = trim( $content_md5 );
2194              $actual      = md5_file( $files['file']['tmp_name'] );
2195  
2196              if ( $expected !== $actual ) {
2197                  return new WP_Error(
2198                      'rest_upload_hash_mismatch',
2199                      __( 'Content hash did not match expected.' ),
2200                      array( 'status' => 412 )
2201                  );
2202              }
2203          }
2204  
2205          // Pass off to WP to handle the actual upload.
2206          $overrides = array(
2207              'test_form' => false,
2208          );
2209  
2210          // Bypasses is_uploaded_file() when running unit tests.
2211          if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
2212              $overrides['action'] = 'wp_handle_mock_upload';
2213          }
2214  
2215          $size_check = self::check_upload_size( $files['file'] );
2216          if ( is_wp_error( $size_check ) ) {
2217              return $size_check;
2218          }
2219  
2220          // Include filesystem functions to get access to wp_handle_upload().
2221          require_once  ABSPATH . 'wp-admin/includes/file.php';
2222  
2223          $file = wp_handle_upload( $files['file'], $overrides, $time );
2224  
2225          if ( isset( $file['error'] ) ) {
2226              return new WP_Error(
2227                  'rest_upload_unknown_error',
2228                  $file['error'],
2229                  array( 'status' => 500 )
2230              );
2231          }
2232  
2233          return $file;
2234      }
2235  
2236      /**
2237       * Retrieves the supported media types.
2238       *
2239       * Media types are considered the MIME type category.
2240       *
2241       * @since 4.7.0
2242       *
2243       * @return array Array of supported media types.
2244       */
2245  	protected function get_media_types() {
2246          $media_types = array();
2247  
2248          foreach ( get_allowed_mime_types() as $mime_type ) {
2249              $parts = explode( '/', $mime_type );
2250  
2251              if ( ! isset( $media_types[ $parts[0] ] ) ) {
2252                  $media_types[ $parts[0] ] = array();
2253              }
2254  
2255              $media_types[ $parts[0] ][] = $mime_type;
2256          }
2257  
2258          return $media_types;
2259      }
2260  
2261      /**
2262       * Determine if uploaded file exceeds space quota on multisite.
2263       *
2264       * Replicates check_upload_size().
2265       *
2266       * @since 4.9.8
2267       *
2268       * @param array $file $_FILES array for a given file.
2269       * @return true|WP_Error True if can upload, error for errors.
2270       */
2271  	protected function check_upload_size( $file ) {
2272          if ( ! is_multisite() ) {
2273              return true;
2274          }
2275  
2276          if ( get_site_option( 'upload_space_check_disabled' ) ) {
2277              return true;
2278          }
2279  
2280          $space_left = get_upload_space_available();
2281  
2282          $file_size = filesize( $file['tmp_name'] );
2283  
2284          if ( $space_left < $file_size ) {
2285              return new WP_Error(
2286                  'rest_upload_limited_space',
2287                  /* translators: %s: Required disk space in kilobytes. */
2288                  sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ),
2289                  array( 'status' => 400 )
2290              );
2291          }
2292  
2293          if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
2294              return new WP_Error(
2295                  'rest_upload_file_too_big',
2296                  /* translators: %s: Maximum allowed file size in kilobytes. */
2297                  sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ),
2298                  array( 'status' => 400 )
2299              );
2300          }
2301  
2302          // Include multisite admin functions to get access to upload_is_user_over_quota().
2303          require_once  ABSPATH . 'wp-admin/includes/ms.php';
2304  
2305          if ( upload_is_user_over_quota( false ) ) {
2306              return new WP_Error(
2307                  'rest_upload_user_quota_exceeded',
2308                  __( 'You have used your space quota. Please delete files before uploading.' ),
2309                  array( 'status' => 400 )
2310              );
2311          }
2312  
2313          return true;
2314      }
2315  
2316      /**
2317       * Gets the request args for the edit item route.
2318       *
2319       * @since 5.5.0
2320       * @since 6.9.0 Adds flips capability and editable fields for the newly-created attachment post.
2321       *
2322       * @return array
2323       */
2324  	protected function get_edit_media_item_args() {
2325          $args = array(
2326              'src'       => array(
2327                  'description' => __( 'URL to the edited image file.' ),
2328                  'type'        => 'string',
2329                  'format'      => 'uri',
2330                  'required'    => true,
2331              ),
2332              // The `modifiers` param takes precedence over the older format.
2333              'modifiers' => array(
2334                  'description' => __( 'Array of image edits.' ),
2335                  'type'        => 'array',
2336                  'minItems'    => 1,
2337                  'items'       => array(
2338                      'description' => __( 'Image edit.' ),
2339                      'type'        => 'object',
2340                      'required'    => array(
2341                          'type',
2342                          'args',
2343                      ),
2344                      'oneOf'       => array(
2345                          array(
2346                              'title'      => __( 'Flip' ),
2347                              'properties' => array(
2348                                  'type' => array(
2349                                      'description' => __( 'Flip type.' ),
2350                                      'type'        => 'string',
2351                                      'enum'        => array( 'flip' ),
2352                                  ),
2353                                  'args' => array(
2354                                      'description' => __( 'Flip arguments.' ),
2355                                      'type'        => 'object',
2356                                      'required'    => array(
2357                                          'flip',
2358                                      ),
2359                                      'properties'  => array(
2360                                          'flip' => array(
2361                                              'description' => __( 'Flip direction.' ),
2362                                              'type'        => 'object',
2363                                              'required'    => array(
2364                                                  'horizontal',
2365                                                  'vertical',
2366                                              ),
2367                                              'properties'  => array(
2368                                                  'horizontal' => array(
2369                                                      'description' => __( 'Whether to flip in the horizontal direction.' ),
2370                                                      'type' => 'boolean',
2371                                                  ),
2372                                                  'vertical' => array(
2373                                                      'description' => __( 'Whether to flip in the vertical direction.' ),
2374                                                      'type' => 'boolean',
2375                                                  ),
2376                                              ),
2377                                          ),
2378                                      ),
2379                                  ),
2380                              ),
2381                          ),
2382                          array(
2383                              'title'      => __( 'Rotation' ),
2384                              'properties' => array(
2385                                  'type' => array(
2386                                      'description' => __( 'Rotation type.' ),
2387                                      'type'        => 'string',
2388                                      'enum'        => array( 'rotate' ),
2389                                  ),
2390                                  'args' => array(
2391                                      'description' => __( 'Rotation arguments.' ),
2392                                      'type'        => 'object',
2393                                      'required'    => array(
2394                                          'angle',
2395                                      ),
2396                                      'properties'  => array(
2397                                          'angle' => array(
2398                                              'description' => __( 'Angle to rotate clockwise in degrees.' ),
2399                                              'type'        => 'number',
2400                                          ),
2401                                      ),
2402                                  ),
2403                              ),
2404                          ),
2405                          array(
2406                              'title'      => __( 'Crop' ),
2407                              'properties' => array(
2408                                  'type' => array(
2409                                      'description' => __( 'Crop type.' ),
2410                                      'type'        => 'string',
2411                                      'enum'        => array( 'crop' ),
2412                                  ),
2413                                  'args' => array(
2414                                      'description' => __( 'Crop arguments.' ),
2415                                      'type'        => 'object',
2416                                      'required'    => array(
2417                                          'left',
2418                                          'top',
2419                                          'width',
2420                                          'height',
2421                                      ),
2422                                      'properties'  => array(
2423                                          'left'   => array(
2424                                              'description' => __( 'Horizontal position from the left to begin the crop as a percentage of the image width.' ),
2425                                              'type'        => 'number',
2426                                          ),
2427                                          'top'    => array(
2428                                              'description' => __( 'Vertical position from the top to begin the crop as a percentage of the image height.' ),
2429                                              'type'        => 'number',
2430                                          ),
2431                                          'width'  => array(
2432                                              'description' => __( 'Width of the crop as a percentage of the image width.' ),
2433                                              'type'        => 'number',
2434                                          ),
2435                                          'height' => array(
2436                                              'description' => __( 'Height of the crop as a percentage of the image height.' ),
2437                                              'type'        => 'number',
2438                                          ),
2439                                      ),
2440                                  ),
2441                              ),
2442                          ),
2443                      ),
2444                  ),
2445              ),
2446              'rotation'  => array(
2447                  'description'      => __( 'The amount to rotate the image clockwise in degrees. DEPRECATED: Use `modifiers` instead.' ),
2448                  'type'             => 'integer',
2449                  'minimum'          => 0,
2450                  'exclusiveMinimum' => true,
2451                  'maximum'          => 360,
2452                  'exclusiveMaximum' => true,
2453              ),
2454              'x'         => array(
2455                  'description' => __( 'As a percentage of the image, the x position to start the crop from. DEPRECATED: Use `modifiers` instead.' ),
2456                  'type'        => 'number',
2457                  'minimum'     => 0,
2458                  'maximum'     => 100,
2459              ),
2460              'y'         => array(
2461                  'description' => __( 'As a percentage of the image, the y position to start the crop from. DEPRECATED: Use `modifiers` instead.' ),
2462                  'type'        => 'number',
2463                  'minimum'     => 0,
2464                  'maximum'     => 100,
2465              ),
2466              'width'     => array(
2467                  'description' => __( 'As a percentage of the image, the width to crop the image to. DEPRECATED: Use `modifiers` instead.' ),
2468                  'type'        => 'number',
2469                  'minimum'     => 0,
2470                  'maximum'     => 100,
2471              ),
2472              'height'    => array(
2473                  'description' => __( 'As a percentage of the image, the height to crop the image to. DEPRECATED: Use `modifiers` instead.' ),
2474                  'type'        => 'number',
2475                  'minimum'     => 0,
2476                  'maximum'     => 100,
2477              ),
2478          );
2479  
2480          /*
2481           * Get the args based on the post schema. This calls `rest_get_endpoint_args_for_schema()`,
2482           * which also takes care of sanitization and validation.
2483           */
2484          $update_item_args = $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE );
2485  
2486          if ( isset( $update_item_args['caption'] ) ) {
2487              $args['caption'] = $update_item_args['caption'];
2488          }
2489  
2490          if ( isset( $update_item_args['description'] ) ) {
2491              $args['description'] = $update_item_args['description'];
2492          }
2493  
2494          if ( isset( $update_item_args['title'] ) ) {
2495              $args['title'] = $update_item_args['title'];
2496          }
2497  
2498          if ( isset( $update_item_args['post'] ) ) {
2499              $args['post'] = $update_item_args['post'];
2500          }
2501  
2502          if ( isset( $update_item_args['alt_text'] ) ) {
2503              $args['alt_text'] = $update_item_args['alt_text'];
2504          }
2505  
2506          return $args;
2507      }
2508  
2509      /**
2510       * Gets the attachment's original file name.
2511       *
2512       * @since 7.0.0
2513       *
2514       * @param int $attachment_id Attachment ID.
2515       * @return string|null Attachment file name, or null if not found.
2516       */
2517  	protected function get_attachment_filename( int $attachment_id ): ?string {
2518          $path = wp_get_original_image_path( $attachment_id );
2519  
2520          if ( $path ) {
2521              return wp_basename( $path );
2522          }
2523  
2524          $path = get_attached_file( $attachment_id );
2525  
2526          if ( $path ) {
2527              return wp_basename( $path );
2528          }
2529  
2530          return null;
2531      }
2532  
2533      /**
2534       * Gets the attachment's file size in bytes.
2535       *
2536       * @since 7.0.0
2537       *
2538       * @param int $attachment_id Attachment ID.
2539       * @return int|null Attachment file size in bytes, or null if not available.
2540       * @phpstan-return non-negative-int|null
2541       */
2542  	protected function get_attachment_filesize( int $attachment_id ): ?int {
2543          $meta = wp_get_attachment_metadata( $attachment_id );
2544  
2545          if ( isset( $meta['filesize'] ) && is_numeric( $meta['filesize'] ) && $meta['filesize'] > 0 ) {
2546              return (int) $meta['filesize'];
2547          }
2548  
2549          $original_path = wp_get_original_image_path( $attachment_id );
2550          $attached_file = $original_path ? $original_path : get_attached_file( $attachment_id );
2551  
2552          if ( is_string( $attached_file ) && is_readable( $attached_file ) ) {
2553              return wp_filesize( $attached_file );
2554          }
2555  
2556          return null;
2557      }
2558  
2559      /**
2560       * Checks if a given request has access to sideload a file.
2561       *
2562       * Sideloading a file for an existing attachment
2563       * requires both update and create permissions.
2564       *
2565       * @since 7.1.0
2566       *
2567       * @param WP_REST_Request $request Full details about the request.
2568       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
2569       */
2570  	public function sideload_item_permissions_check( $request ) {
2571          return $this->edit_media_item_permissions_check( $request );
2572      }
2573  
2574      /**
2575       * Validates an image size name, or an array of names sharing a single file.
2576       *
2577       * Shared by the sideload endpoint, which names the size a file is produced
2578       * for, and the finalize endpoint, which names the size each submitted entry
2579       * is stored under. Both need the same set, and finalize accepts a payload of
2580       * its own rather than one this class produced, so leaving it unconstrained
2581       * there would let a submission write an arbitrary key into the metadata
2582       * 'sizes' array or route a file into a branch it was never produced for.
2583       *
2584       * @since 7.1.0
2585       *
2586       * @param mixed  $value The image size name, or an array of names.
2587       * @param string $param Parameter name, used in the error messages.
2588       * @return true|WP_Error True when every name is valid, WP_Error otherwise.
2589       */
2590  	private static function validate_image_size_names( $value, string $param ) {
2591          $special_sizes = self::get_special_image_sizes();
2592          $regular_sizes = array_values(
2593              array_diff(
2594                  array_merge(
2595                      array_keys( wp_get_registered_image_subsizes() ),
2596                      // Not a registered sub-size, but stored as an ordinary
2597                      // entry in the metadata 'sizes' array (PDF thumbnails).
2598                      array( 'full' )
2599                  ),
2600                  $special_sizes
2601              )
2602          );
2603  
2604          if ( is_string( $value ) ) {
2605              $items       = array( $value );
2606              $valid_sizes = array_merge( $regular_sizes, $special_sizes );
2607          } elseif ( is_array( $value ) ) {
2608              /**
2609               * An array registers one sideloaded file under several size names,
2610               * which only makes sense for regular sub-sizes: each special size
2611               * names a single file with its own handling in
2612               * {@see self::sideload_item()} and its own metadata key in
2613               * {@see self::finalize_item()}. Rejecting them here is what lets the
2614               * array branches in both methods treat an array as regular sizes.
2615               */
2616              $items       = $value;
2617              $valid_sizes = $regular_sizes;
2618          } else {
2619              return new WP_Error(
2620                  'rest_invalid_type',
2621                  /* translators: %s: Parameter name. */
2622                  sprintf( __( '%s must be a string or an array of strings.' ), $param )
2623              );
2624          }
2625  
2626          foreach ( $items as $item ) {
2627              if ( ! in_array( $item, $valid_sizes, true ) ) {
2628                  return new WP_Error(
2629                      'rest_not_in_enum',
2630                      /* translators: %s: Parameter name. */
2631                      sprintf( __( '%s contains an invalid image size.' ), $param )
2632                  );
2633              }
2634          }
2635  
2636          return true;
2637      }
2638  
2639      /**
2640       * Returns the image size names which name a single file rather than a sub-size.
2641       *
2642       * Each of these is handled on its own in {@see self::sideload_item()} and stored
2643       * under its own key by {@see self::finalize_item()}, so unlike a regular
2644       * sub-size none of them may appear in an array of names sharing one file.
2645       *
2646       * @since 7.1.0
2647       *
2648       * @return string[] Special image size names.
2649       *
2650       * @phpstan-return non-empty-list<non-empty-string>
2651       */
2652  	private static function get_special_image_sizes(): array {
2653          return array(
2654              'original',
2655              'scaled',
2656              // Source-format original (e.g. the HEIC kept alongside its JPEG derivative).
2657              self::IMAGE_SIZE_SOURCE_ORIGINAL,
2658              // Converted-video companions for an animated GIF (the MP4/WebM and its poster).
2659              'animated_video',
2660              'animated_video_poster',
2661          );
2662      }
2663  
2664      /**
2665       * Validates that uploaded image dimensions are appropriate for the specified image size.
2666       *
2667       * @since 7.1.0
2668       *
2669       * @param int    $width         Uploaded image width.
2670       * @param int    $height        Uploaded image height.
2671       * @param string $image_size    The target image size name.
2672       * @param int    $attachment_id The attachment ID.
2673       * @return true|WP_Error True if valid, WP_Error if invalid.
2674       */
2675  	private function validate_image_dimensions( int $width, int $height, string $image_size, int $attachment_id ) {
2676          // All image sizes require positive dimensions.
2677          if ( $width <= 0 || $height <= 0 ) {
2678              return new WP_Error(
2679                  'rest_upload_invalid_dimensions',
2680                  __( 'Uploaded image must have positive dimensions.' ),
2681                  array( 'status' => 400 )
2682              );
2683          }
2684  
2685          /*
2686           * 'original' size: the full-size image that replaces the main file (see
2687           * sideload_item()/finalize_item()). The endpoint expects any EXIF
2688           * orientation to be applied to the image already, which can swap width
2689           * and height, so the dimensions must match the stored dimensions or be
2690           * their transpose.
2691           */
2692          if ( 'original' === $image_size ) {
2693              $metadata = wp_get_attachment_metadata( $attachment_id, true );
2694              if ( is_array( $metadata ) && isset( $metadata['width'], $metadata['height'] ) ) {
2695                  $expected_width  = (int) $metadata['width'];
2696                  $expected_height = (int) $metadata['height'];
2697  
2698                  $matches_dimensions    = $width === $expected_width && $height === $expected_height;
2699                  $transposes_dimensions = $width === $expected_height && $height === $expected_width;
2700  
2701                  if ( ! $matches_dimensions && ! $transposes_dimensions ) {
2702                      return new WP_Error(
2703                          'rest_upload_dimension_mismatch',
2704                          sprintf(
2705                              /* translators: 1: Actual width, 2: actual height, 3: expected width, 4: expected height. */
2706                              __( 'Uploaded image dimensions (%1$dx%2$d) do not match original image dimensions (%3$dx%4$d).' ),
2707                              $width,
2708                              $height,
2709                              $expected_width,
2710                              $expected_height
2711                          ),
2712                          array( 'status' => 400 )
2713                      );
2714                  }
2715              }
2716              return true;
2717          }
2718  
2719          // 'full' size (PDF thumbnails) and 'scaled': no further constraints.
2720          if ( in_array( $image_size, array( 'full', 'scaled' ), true ) ) {
2721              return true;
2722          }
2723  
2724          /*
2725           * 'animated_video_poster' companion: a static poster image for the
2726           * converted video. It is a real image (so it has positive dimensions)
2727           * but is not a registered sub-size, so it has no dimension constraint.
2728           */
2729          if ( 'animated_video_poster' === $image_size ) {
2730              return true;
2731          }
2732  
2733          // Regular image sizes: validate against registered size constraints.
2734          $registered_sizes = wp_get_registered_image_subsizes();
2735  
2736          if ( ! isset( $registered_sizes[ $image_size ] ) ) {
2737              return new WP_Error(
2738                  'rest_upload_unknown_size',
2739                  __( 'Unknown image size.' ),
2740                  array( 'status' => 400 )
2741              );
2742          }
2743  
2744          $size_data  = $registered_sizes[ $image_size ];
2745          $max_width  = (int) $size_data['width'];
2746          $max_height = (int) $size_data['height'];
2747  
2748          // Validate dimensions don't exceed the registered size maximums.
2749          // Allow 1px tolerance for rounding differences.
2750          $tolerance = 1;
2751  
2752          if ( $this->dimension_exceeds_max( $width, $max_width, $tolerance ) ) {
2753              return new WP_Error(
2754                  'rest_upload_dimension_mismatch',
2755                  sprintf(
2756                      /* translators: 1: Image size name, 2: maximum width, 3: actual width. */
2757                      __( 'Uploaded image width (%3$d) exceeds maximum for "%1$s" size (%2$d).' ),
2758                      $image_size,
2759                      $max_width,
2760                      $width
2761                  ),
2762                  array( 'status' => 400 )
2763              );
2764          }
2765  
2766          if ( $this->dimension_exceeds_max( $height, $max_height, $tolerance ) ) {
2767              return new WP_Error(
2768                  'rest_upload_dimension_mismatch',
2769                  sprintf(
2770                      /* translators: 1: Image size name, 2: maximum height, 3: actual height. */
2771                      __( 'Uploaded image height (%3$d) exceeds maximum for "%1$s" size (%2$d).' ),
2772                      $image_size,
2773                      $max_height,
2774                      $height
2775                  ),
2776                  array( 'status' => 400 )
2777              );
2778          }
2779  
2780          return true;
2781      }
2782  
2783      /**
2784       * Checks whether a dimension exceeds the maximum allowed value.
2785       *
2786       * A maximum of zero means the dimension is unconstrained.
2787       *
2788       * @since 7.1.0
2789       *
2790       * @param int $value     The actual dimension in pixels.
2791       * @param int $max       The maximum allowed dimension in pixels. Zero means no constraint.
2792       * @param int $tolerance Pixel tolerance allowed for rounding differences.
2793       * @return bool True if the value exceeds the maximum plus tolerance.
2794       */
2795  	private function dimension_exceeds_max( int $value, int $max, int $tolerance ): bool {
2796          return $max > 0 && $value > $max + $tolerance;
2797      }
2798  
2799      /**
2800       * Side-loads a media file without creating a new attachment.
2801       *
2802       * @since 7.1.0
2803       *
2804       * @param WP_REST_Request $request Full details about the request.
2805       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
2806       */
2807  	public function sideload_item( WP_REST_Request $request ) {
2808          $attachment_id = (int) $request['id'];
2809  
2810          $post = $this->get_post( $attachment_id );
2811  
2812          if ( is_wp_error( $post ) ) {
2813              return $post;
2814          }
2815  
2816          if (
2817              ! wp_attachment_is_image( $post ) &&
2818              ! wp_attachment_is( 'pdf', $post )
2819          ) {
2820              return new WP_Error(
2821                  'rest_post_invalid_id',
2822                  __( 'Invalid post ID. Only images and PDFs can be sideloaded.' ),
2823                  array( 'status' => 400 )
2824              );
2825          }
2826  
2827          /*
2828           * Sideloaded files are placed in the same directory as the attachment
2829           * they extend, because the file names produced here are later resolved
2830           * against that directory. An attachment stored outside the uploads
2831           * directory has no such directory to use, so there is nowhere the names
2832           * this would produce could resolve.
2833           */
2834          $attached_file = get_attached_file( $attachment_id, true );
2835          $subdir        = is_string( $attached_file ) && '' !== $attached_file
2836              ? $this->get_attachment_upload_subdir( $attached_file )
2837              : null;
2838  
2839          if ( ! is_string( $attached_file ) || '' === $attached_file || null === $subdir ) {
2840              return new WP_Error(
2841                  'rest_sideload_attachment_not_in_uploads',
2842                  __( 'The attachment is not stored in the uploads directory, so a file cannot be sideloaded for it.' ),
2843                  array( 'status' => 403 )
2844              );
2845          }
2846  
2847          if ( false === $request['convert_format'] ) {
2848              // Prevent image conversion as that is done client-side.
2849              add_filter( 'image_editor_output_format', '__return_empty_array', 100 );
2850          }
2851  
2852          // Get the file via $_FILES or raw data.
2853          $files   = $request->get_file_params();
2854          $headers = $request->get_headers();
2855  
2856          /*
2857           * wp_unique_filename() will always add numeric suffix if the name looks like a sub-size to avoid conflicts.
2858           * See /wp-includes/functions.php.
2859           * With the following filter we can work around this safeguard.
2860           */
2861          $attachment_filename = wp_basename( $attached_file );
2862  
2863          $filter_filename = static function ( $filename, $ext, $dir, $unique_filename_callback, $alt_filenames, $number ) use ( $attachment_filename ) {
2864              return self::filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename );
2865          };
2866  
2867          add_filter( 'wp_unique_filename', $filter_filename, 10, 6 );
2868  
2869          // Pin the upload to the attachment's own directory, rather than deriving
2870          // it from the parent post's date as media_handle_upload() does for a
2871          // brand new upload. See the note above where $subdir is resolved.
2872          $filter_upload_dir = static function ( $uploads ) use ( $subdir ) {
2873              if (
2874                  is_array( $uploads ) &&
2875                  isset( $uploads['basedir'], $uploads['baseurl'] ) &&
2876                  is_string( $uploads['basedir'] ) &&
2877                  is_string( $uploads['baseurl'] )
2878              ) {
2879                  $uploads['subdir'] = $subdir;
2880                  $uploads['path']   = $uploads['basedir'] . $subdir;
2881                  $uploads['url']    = $uploads['baseurl'] . $subdir;
2882              }
2883              return $uploads;
2884          };
2885  
2886          add_filter( 'upload_dir', $filter_upload_dir, 100 );
2887  
2888          if ( ! empty( $files ) ) {
2889              $file = $this->upload_from_file( $files, $headers );
2890          } else {
2891              $file = $this->upload_from_data( $request->get_body(), $headers );
2892          }
2893  
2894          remove_filter( 'wp_unique_filename', $filter_filename );
2895          remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );
2896          remove_filter( 'upload_dir', $filter_upload_dir, 100 );
2897  
2898          if ( is_wp_error( $file ) ) {
2899              return $file;
2900          }
2901  
2902          $type = $file['type'];
2903          $path = $file['file'];
2904  
2905          /** @var non-empty-string|non-empty-list<non-empty-string> $image_size */
2906          $image_size = $request['image_size'];
2907  
2908          /*
2909           * Validate raster sub-sizes before storing them. Two companion sizes
2910           * are exempt because wp_getimagesize() may not be able to read the
2911           * file at all: the 'animated_video' companion of an animated GIF is a
2912           * video (MP4/WebM), and a source-format original (e.g. a HEIC or JXL
2913           * kept next to its JPEG derivative) may be an unreadable format. Their
2914           * dimensions are neither validated nor recorded. The
2915           * 'animated_video_poster' companion is a real image, so it is still
2916           * read and rejected if unreadable; validate_image_dimensions() skips
2917           * only the registered-size constraint for it.
2918           */
2919          $skip_dimension_read = self::IMAGE_SIZE_SOURCE_ORIGINAL === $image_size || 'animated_video' === $image_size;
2920          $size                = false;
2921  
2922          if ( ! $skip_dimension_read ) {
2923              /*
2924               * Read the dimensions up front. A file whose dimensions cannot be
2925               * read is corrupted or an unsupported format and must be rejected
2926               * rather than silently stored with zero dimensions.
2927               */
2928              $size = wp_getimagesize( $path );
2929  
2930              if ( ! $size ) {
2931                  // Clean up the uploaded file.
2932                  wp_delete_file( $path );
2933                  return new WP_Error(
2934                      'rest_upload_invalid_image',
2935                      __( 'Could not read image dimensions. The file may be corrupted or an unsupported format.' ),
2936                      array( 'status' => 400 )
2937                  );
2938              }
2939  
2940              /*
2941               * Validate the dimensions against every size the file is being
2942               * registered under. An array $image_size shares one file among
2943               * several registered sizes, so the file has to satisfy each of
2944               * them; validating only the scalar case would let a name wrapped
2945               * in a one-element array skip the constraint entirely.
2946               */
2947              foreach ( (array) $image_size as $size_name ) {
2948                  $validation = $this->validate_image_dimensions( $size[0], $size[1], $size_name, $attachment_id );
2949                  if ( is_wp_error( $validation ) ) {
2950                      // Clean up the uploaded file.
2951                      wp_delete_file( $path );
2952                      return $validation;
2953                  }
2954              }
2955          }
2956  
2957          // Build sub-size data to return to the client.
2958          // The client accumulates these and sends them all to the finalize
2959          // endpoint, which writes the metadata in a single operation. This
2960          // avoids the read-modify-write race that concurrent sideloads for the
2961          // same attachment would otherwise hit.
2962          $sub_size_data = array(
2963              'image_size' => $image_size,
2964          );
2965  
2966          if ( is_array( $image_size ) ) {
2967              /**
2968               * Multiple registered sizes share these dimensions, so a single
2969               * sideloaded file is reused for all of them. Arrays only carry
2970               * regular sub-sizes; the special keys below are always scalar
2971               * (ref. {@see self::get_special_image_sizes()}). Those never skip
2972               * the read above, so $size already holds the dimensions.
2973               */
2974              $sub_size_data['width']     = $size ? $size[0] : 0;
2975              $sub_size_data['height']    = $size ? $size[1] : 0;
2976              $sub_size_data['file']      = wp_basename( $path );
2977              $sub_size_data['mime_type'] = $type;
2978              $sub_size_data['filesize']  = wp_filesize( $path );
2979          } elseif ( self::IMAGE_SIZE_SOURCE_ORIGINAL === $image_size ) {
2980              /*
2981               * Source-format original (e.g. the HEIC kept next to its JPEG
2982               * derivative). Record the filename so finalize_item can store it
2983               * under the dedicated source-image meta key.
2984               */
2985              $sub_size_data['file'] = wp_basename( $path );
2986          } elseif ( 'animated_video' === $image_size || 'animated_video_poster' === $image_size ) {
2987              /*
2988               * Converted-video companion of an animated GIF (the MP4/WebM or
2989               * its static first-frame poster). Record the filename so
2990               * finalize_item can store it under its dedicated meta key.
2991               */
2992              $sub_size_data['file'] = wp_basename( $path );
2993          } elseif ( 'scaled' === $image_size || 'original' === $image_size ) {
2994              /*
2995               * 'scaled' and 'original' both replace the attachment's main file
2996               * with the supplied image and keep the file being replaced as
2997               * `original_image`, which is the untouched upload. A 'scaled'
2998               * image is downsized and an 'original' image has any EXIF
2999               * orientation already applied. This is the same swap WordPress
3000               * makes when it scales or rotates an image on upload; see
3001               * _wp_image_meta_replace_original().
3002               */
3003              $sub_size_data['original_image'] = $attachment_filename;
3004  
3005              // Validate the supplied image before updating the attached file.
3006              // $size was read above: neither of these sizes skips that read.
3007              $filesize = wp_filesize( $path );
3008  
3009              if ( ! $size || ! $filesize ) {
3010                  // Clean up the uploaded file, which nothing references yet.
3011                  wp_delete_file( $path );
3012                  return new WP_Error(
3013                      'rest_sideload_invalid_image',
3014                      __( 'Unable to read the sideloaded image file.' ),
3015                      array( 'status' => 500 )
3016                  );
3017              }
3018  
3019              // Update the attached file to point to the supplied image.
3020              // This writes to _wp_attached_file meta, not _wp_attachment_metadata.
3021              if (
3022                  $attached_file !== $path &&
3023                  ! update_attached_file( $attachment_id, $path )
3024              ) {
3025                  // Clean up the uploaded file, which nothing references yet.
3026                  wp_delete_file( $path );
3027                  return new WP_Error(
3028                      'rest_sideload_update_attached_file_failed',
3029                      __( 'Unable to update the attached file for this attachment.' ),
3030                      array( 'status' => 500 )
3031                  );
3032              }
3033  
3034              $sub_size_data['width']    = $size[0];
3035              $sub_size_data['height']   = $size[1];
3036              $sub_size_data['filesize'] = $filesize;
3037              $sub_size_data['file']     = _wp_relative_upload_path( $path );
3038          } else {
3039              // As above, $size was already read for every size reaching here.
3040              $sub_size_data['width']     = $size ? $size[0] : 0;
3041              $sub_size_data['height']    = $size ? $size[1] : 0;
3042              $sub_size_data['file']      = wp_basename( $path );
3043              $sub_size_data['mime_type'] = $type;
3044              $sub_size_data['filesize']  = wp_filesize( $path );
3045          }
3046  
3047          /*
3048           * Record the file names produced for this attachment so finalize can
3049           * confirm every stored sub-size was actually sideloaded here. The
3050           * values recorded are exactly the ones handed back to the client, so
3051           * finalize accepts a submission only when it echoes what was produced.
3052           */
3053          foreach ( array( 'file', 'original_image' ) as $provenance_key ) {
3054              if (
3055                  isset( $sub_size_data[ $provenance_key ] ) &&
3056                  is_string( $sub_size_data[ $provenance_key ] ) &&
3057                  '' !== $sub_size_data[ $provenance_key ]
3058              ) {
3059                  add_post_meta( $attachment_id, self::META_KEY_SIDELOAD_FILE_NAME, wp_slash( $sub_size_data[ $provenance_key ] ) );
3060              }
3061          }
3062  
3063          return rest_ensure_response( $sub_size_data );
3064      }
3065  
3066      /**
3067       * Filters wp_unique_filename during sideloads.
3068       *
3069       * wp_unique_filename() will always add numeric suffix if the name looks like a sub-size to avoid conflicts.
3070       * Adding this closure to the filter helps work around this safeguard.
3071       *
3072       * Example: when uploading myphoto.jpeg, WordPress normally creates myphoto-150x150.jpeg,
3073       * and when uploading myphoto-150x150.jpeg, it will be renamed to myphoto-150x150-1.jpeg
3074       * However, here it is desired not to add the suffix in order to maintain the same
3075       * naming convention as if the file was uploaded regularly.
3076       *
3077       * The suffix is only dropped when no file of that name already exists in $dir,
3078       * so this never returns a name that would overwrite one. The unsuffixed name
3079       * must also derive from the attachment's own file name, and
3080       * {@see self::sideload_item()} pins the upload to the attachment's own
3081       * directory, so any name returned here belongs to the attachment being
3082       * extended.
3083       *
3084       * @since 7.1.0
3085       *
3086       * @link https://github.com/WordPress/wordpress-develop/blob/30954f7ac0840cfdad464928021d7f380940c347/src/wp-includes/functions.php#L2576-L2582
3087       *
3088       * @param string      $filename            Unique file name.
3089       * @param string      $dir                 Directory path.
3090       * @param int|string  $number              The highest number that was used to make the file name unique
3091       *                                         or an empty string if unused.
3092       * @param string|null $attachment_filename Original attachment file name.
3093       * @return string Filtered file name.
3094       */
3095  	private static function filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename ) {
3096          if ( ! is_int( $number ) || ! $attachment_filename ) {
3097              return $filename;
3098          }
3099  
3100          $ext       = pathinfo( $filename, PATHINFO_EXTENSION );
3101          $name      = pathinfo( $filename, PATHINFO_FILENAME );
3102          $orig_name = pathinfo( $attachment_filename, PATHINFO_FILENAME );
3103  
3104          if ( ! $ext || ! $name ) {
3105              return $filename;
3106          }
3107  
3108          $matches = array();
3109          if ( preg_match( '/(.*)-(\d+x\d+|scaled)-' . $number . '$/', $name, $matches ) ) {
3110              $filename_without_suffix = $matches[1] . '-' . $matches[2] . ".$ext";
3111              if ( $matches[1] === $orig_name && ! file_exists( "$dir/$filename_without_suffix" ) ) {
3112                  return $filename_without_suffix;
3113              }
3114          }
3115  
3116          return $filename;
3117      }
3118  
3119      /**
3120       * Validates the `sub_sizes` file names against what this attachment produced.
3121       *
3122       * The {@see self::finalize_item()} method stores the client-supplied `file`
3123       * and `original_image` values in the attachment metadata, where they are
3124       * later resolved within the attachment's upload directory and read or deleted
3125       * (for example by {@see wp_get_original_image_path()}, {@see wp_getimagesize()},
3126       * and {@see wp_delete_attachment_files()}).
3127       *
3128       * Every file the sideload endpoint creates is recorded under
3129       * {@see self::META_KEY_SIDELOAD_FILE_NAME} as it is produced, using
3130       * server-generated names. finalize accepts a `file` or `original_image`
3131       * value only when it matches one of those recorded names (or the
3132       * attachment's own attached file, which it definitionally owns).
3133       *
3134       * @since 7.1.0
3135       *
3136       * @param int   $attachment_id The attachment being finalized.
3137       * @param array $sub_sizes     Sub-size metadata collected from sideloads.
3138       * @return true|WP_Error True if every file name was produced here, WP_Error otherwise.
3139       *
3140       * @phpstan-param list<Image_Sub_Size> $sub_sizes
3141       */
3142  	protected function validate_sub_size_provenance( int $attachment_id, array $sub_sizes ) {
3143          $allowed = $this->get_sideloaded_file_names( $attachment_id );
3144  
3145          foreach ( $sub_sizes as $sub_size ) {
3146              foreach ( array( 'file', 'original_image' ) as $key ) {
3147                  /*
3148                   * Every value that was sent is checked, no matter how unlikely
3149                   * a name it looks. A loose emptiness test would wave through
3150                   * '0', which is a valid one-character name as far as the schema
3151                   * is concerned and is stored like any other. A value the schema
3152                   * types as a string but which arrives as something else is
3153                   * rejected rather than skipped, so a subclass which widens the
3154                   * schema cannot pass an unchecked value on to the metadata.
3155                   */
3156                  if ( ! isset( $sub_size[ $key ] ) ) {
3157                      continue;
3158                  }
3159  
3160                  if ( ! is_string( $sub_size[ $key ] ) || ! in_array( $sub_size[ $key ], $allowed, true ) ) {
3161                      return new WP_Error(
3162                          'rest_invalid_sub_size_file',
3163                          __( 'Invalid sub-size file name. File names must have been produced by a prior sideload for this attachment.' ),
3164                          array( 'status' => 400 )
3165                      );
3166                  }
3167              }
3168          }
3169  
3170          return true;
3171      }
3172  
3173      /**
3174       * Returns the file names which a finalize request may store for an attachment.
3175       *
3176       * The set is the file names the sideload endpoint recorded as it produced
3177       * them (ref. {@see self::META_KEY_SIDELOAD_FILE_NAME}), plus the attachment's own
3178       * attached file - accepted in both its uploads-relative and basename form so
3179       * a scaled main-file pointer validates regardless of which the client
3180       * echoes - plus the names already stored in the attachment's own metadata.
3181       *
3182       * @since 7.1.0
3183       *
3184       * @param int  $attachment_id      The attachment being finalized.
3185       * @param bool $include_provenance Whether to include the sideload provenance rows.
3186       *                                 Pass false to get only the names recoverable from
3187       *                                 the attached file and stored metadata, e.g. to decide
3188       *                                 whether a provenance row is still needed. Default true.
3189       * @return string[] File names that may appear in the finalize submission.
3190       *
3191       * @phpstan-return list<string>
3192       */
3193  	protected function get_sideloaded_file_names( int $attachment_id, bool $include_provenance = true ): array {
3194          $allowed = array();
3195  
3196          if ( $include_provenance ) {
3197              foreach ( (array) get_post_meta( $attachment_id, self::META_KEY_SIDELOAD_FILE_NAME ) as $name ) {
3198                  if ( is_string( $name ) && '' !== $name ) {
3199                      $allowed[] = $name;
3200                  }
3201              }
3202          }
3203  
3204          $attached_file = get_post_meta( $attachment_id, '_wp_attached_file', true );
3205          if ( is_string( $attached_file ) && strlen( $attached_file ) > 0 ) {
3206              $allowed[] = $attached_file;
3207              $allowed[] = wp_basename( $attached_file );
3208          }
3209  
3210          /*
3211           * Names already stored in this attachment's metadata passed this same
3212           * check when they were written, so accepting them again introduces
3213           * nothing new.
3214           */
3215          $metadata = wp_get_attachment_metadata( $attachment_id, true );
3216          if ( is_array( $metadata ) ) {
3217              $stored = array(
3218                  $metadata['file'] ?? null,
3219                  $metadata['original_image'] ?? null,
3220                  $metadata[ self::META_KEY_SOURCE_IMAGE ] ?? null,
3221                  $metadata['animated_video'] ?? null,
3222                  $metadata['animated_video_poster'] ?? null,
3223              );
3224  
3225              if ( ! empty( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
3226                  foreach ( $metadata['sizes'] as $size ) {
3227                      $stored[] = is_array( $size ) ? ( $size['file'] ?? null ) : null;
3228                  }
3229              }
3230  
3231              foreach ( $stored as $name ) {
3232                  if ( is_string( $name ) && '' !== $name ) {
3233                      $allowed[] = $name;
3234                      $allowed[] = wp_basename( $name );
3235                  }
3236              }
3237          }
3238  
3239          return array_values( array_unique( $allowed ) );
3240      }
3241  
3242      /**
3243       * Returns the uploads subdirectory an attachment is stored in.
3244       *
3245       * Used to place a sideloaded file alongside the attachment it extends. The
3246       * result is concatenated into a filesystem path by the caller, so it is
3247       * returned only when the attachment resolves inside the uploads directory
3248       * and the stored path is well formed.
3249       *
3250       * @since 7.1.0
3251       *
3252       * @param string $attached_file Absolute path to the attached file.
3253       * @return string|null Subdirectory beginning with a slash, an empty string when the
3254       *                     attachment sits in the base directory, or null when the
3255       *                     attachment is not inside the uploads directory.
3256       *
3257       * @phpstan-param non-empty-string $attached_file
3258       */
3259  	protected function get_attachment_upload_subdir( string $attached_file ): ?string {
3260          $uploads = wp_get_upload_dir();
3261          if ( empty( $uploads['basedir'] ) ) {
3262              return null;
3263          }
3264  
3265          $basedir  = untrailingslashit( wp_normalize_path( $uploads['basedir'] ) );
3266          $file_dir = wp_normalize_path( dirname( $attached_file ) );
3267  
3268          /*
3269           * The attachment's directory must be the uploads base directory itself
3270           * or a directory inside it. The trailing slash in the prefix comparison
3271           * keeps a sibling directory that merely shares the prefix (for example
3272           * 'uploads-elsewhere' next to 'uploads') from matching.
3273           */
3274          if ( $file_dir !== $basedir && ! str_starts_with( $file_dir, trailingslashit( $basedir ) ) ) {
3275              return null;
3276          }
3277  
3278          $subdir = (string) substr( $file_dir, strlen( $basedir ) );
3279  
3280          // A prefix match alone does not rule out a path that climbs back out.
3281          if ( in_array( '..', explode( '/', $subdir ), true ) ) {
3282              return null;
3283          }
3284  
3285          return $subdir;
3286      }
3287  
3288      /**
3289       * Finalizes an attachment after client-side media processing.
3290       *
3291       * Applies the sub-size metadata collected from sideload responses in a
3292       * single metadata update, then triggers the 'wp_generate_attachment_metadata'
3293       * filter so that server-side plugins can process the attachment after all
3294       * client-side operations (upload, thumbnail generation, sideloads) are
3295       * complete.
3296       *
3297       * @since 7.1.0
3298       *
3299       * @param WP_REST_Request $request Full details about the request.
3300       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
3301       */
3302  	public function finalize_item( WP_REST_Request $request ) {
3303          $attachment_id = (int) $request['id'];
3304  
3305          $post = $this->get_post( $attachment_id );
3306          if ( is_wp_error( $post ) ) {
3307              return $post;
3308          }
3309  
3310          /**
3311           * Sub-size metadata collected from sideload responses. Confirm every
3312           * file name was produced by a prior sideload for this attachment before
3313           * storing it, so a client cannot make finalize record (and later read or
3314           * delete) another attachment's files.
3315           *
3316           * @var list<Image_Sub_Size> $sub_sizes
3317           */
3318          $sub_sizes  = $request['sub_sizes'] ?? array();
3319          $provenance = $this->validate_sub_size_provenance( $attachment_id, $sub_sizes );
3320          if ( is_wp_error( $provenance ) ) {
3321              return $provenance;
3322          }
3323  
3324          $metadata = wp_get_attachment_metadata( $attachment_id );
3325          if ( ! is_array( $metadata ) ) {
3326              $metadata = array();
3327          }
3328  
3329          // Apply all sub-size metadata collected from sideload responses.
3330          foreach ( $sub_sizes as $sub_size ) {
3331              $image_size = $sub_size['image_size'];
3332  
3333              // When multiple size names share identical dimensions the client
3334              // sends a single sub-size entry with an array of names. Register the
3335              // same file under each name.
3336              if ( is_array( $image_size ) ) {
3337                  /*
3338                   * Arrays carry regular sizes only, as the sideload endpoint
3339                   * enforces. Each special size names a single file handled by one
3340                   * of the branches below, so grouping one under a shared file
3341                   * would write it to the wrong place; reject rather than guess.
3342                   */
3343                  if ( array_intersect( $image_size, self::get_special_image_sizes() ) ) {
3344                      return new WP_Error(
3345                          'rest_invalid_sub_size_name',
3346                          __( 'A grouped sub-size entry may only name regular image sizes.' ),
3347                          array( 'status' => 400 )
3348                      );
3349                  }
3350  
3351                  // As below: `file` is not required by the schema, and a size
3352                  // entry that names no file is not worth recording.
3353                  if ( empty( $sub_size['file'] ) ) {
3354                      continue;
3355                  }
3356  
3357                  $metadata['sizes'] ??= array();
3358  
3359                  foreach ( $image_size as $name ) {
3360                      $metadata['sizes'][ $name ] = array(
3361                          'width'     => $sub_size['width'] ?? 0,
3362                          'height'    => $sub_size['height'] ?? 0,
3363                          'file'      => $sub_size['file'],
3364                          'mime-type' => $sub_size['mime_type'] ?? '',
3365                          'filesize'  => $sub_size['filesize'] ?? 0,
3366                      );
3367                  }
3368                  continue;
3369              }
3370  
3371              if ( 'original' === $image_size || 'scaled' === $image_size ) {
3372                  // Skip malformed entries so a bad payload cannot blank out the
3373                  // main file metadata.
3374                  if ( empty( $sub_size['file'] ) ) {
3375                      continue;
3376                  }
3377  
3378                  /*
3379                   * Record the supplied full-size image (from sideload_item()) as
3380                   * the main file, keeping the current attached file as
3381                   * `original_image`. A 'scaled' image is downsized and an
3382                   * 'original' image is rotated; both have any EXIF orientation
3383                   * already applied by the client.
3384                   */
3385                  if ( ! empty( $sub_size['original_image'] ) ) {
3386                      $metadata['original_image'] = $sub_size['original_image'];
3387                  }
3388                  $metadata['width']    = $sub_size['width'] ?? 0;
3389                  $metadata['height']   = $sub_size['height'] ?? 0;
3390                  $metadata['filesize'] = $sub_size['filesize'] ?? 0;
3391                  $metadata['file']     = $sub_size['file'];
3392  
3393                  /*
3394                   * The supplied image has its orientation applied already, so
3395                   * reset the stored value (from the upload) to 1, as
3396                   * wp_create_image_subsizes() does for both its scale and rotate
3397                   * paths. Otherwise exif_orientation would still report the
3398                   * pre-rotation value and the client would rotate the image
3399                   * again on a re-fetch.
3400                   */
3401                  if ( ! empty( $metadata['image_meta']['orientation'] ) ) {
3402                      $metadata['image_meta']['orientation'] = 1;
3403                  }
3404              } elseif ( self::IMAGE_SIZE_SOURCE_ORIGINAL === $image_size ) {
3405                  // As above: `file` is not required by the schema, and each of
3406                  // these sizes is nothing but the file it names.
3407                  if ( empty( $sub_size['file'] ) ) {
3408                      continue;
3409                  }
3410  
3411                  /*
3412                   * Source-format original: stored under its own meta key so the
3413                   * scaled-sideload flow (which writes 'original_image') cannot
3414                   * clobber it. 'original_image' keeps pointing at the
3415                   * web-viewable JPEG derivative. Cleanup on attachment delete
3416                   * is handled by wp_delete_attachment_files().
3417                   */
3418                  $metadata[ self::META_KEY_SOURCE_IMAGE ] = $sub_size['file'];
3419              } elseif ( 'animated_video' === $image_size ) {
3420                  if ( empty( $sub_size['file'] ) ) {
3421                      continue;
3422                  }
3423  
3424                  /*
3425                   * Converted-video companion of an animated GIF. Stored under its
3426                   * own meta key; 'original_image' keeps pointing at the GIF. Cleanup
3427                   * on attachment delete is handled by wp_delete_attachment_files().
3428                   */
3429                  $metadata['animated_video'] = $sub_size['file'];
3430              } elseif ( 'animated_video_poster' === $image_size ) {
3431                  if ( empty( $sub_size['file'] ) ) {
3432                      continue;
3433                  }
3434  
3435                  // Static first-frame poster for the converted video.
3436                  $metadata['animated_video_poster'] = $sub_size['file'];
3437              } else {
3438                  if ( empty( $sub_size['file'] ) ) {
3439                      continue;
3440                  }
3441  
3442                  $metadata['sizes'] ??= array();
3443  
3444                  $metadata['sizes'][ $image_size ] = array(
3445                      'width'     => $sub_size['width'] ?? 0,
3446                      'height'    => $sub_size['height'] ?? 0,
3447                      'file'      => $sub_size['file'],
3448                      'mime-type' => $sub_size['mime_type'] ?? '',
3449                      'filesize'  => $sub_size['filesize'] ?? 0,
3450                  );
3451              }
3452          }
3453  
3454          /** This filter is documented in wp-admin/includes/image.php */
3455          $metadata = apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id, 'update' );
3456  
3457          wp_update_attachment_metadata( $attachment_id, $metadata );
3458  
3459          /*
3460           * Drop only the provenance rows this request consumed, now that the
3461           * names are recorded in the metadata itself. A row is dropped only once
3462           * its name is recoverable from the stored metadata, so a name the
3463           * 'wp_generate_attachment_metadata' filter removed - or that a failed
3464           * update never persisted - keeps its row and the retried request the
3465           * endpoint documents as idempotent still validates. Rows for sideloads
3466           * that have not been finalized yet survive for a later call, and passing
3467           * the value makes the delete a no-op when the row is already gone, so a
3468           * retried request cleans up without error. Any rows left behind by an
3469           * abandoned upload are removed with the attachment itself.
3470           *
3471           * Retrying is idempotent for the request as it was sent. A name is only
3472           * unavailable to a retry once a later finalize has overwritten the same
3473           * size with a newly sideloaded file, which drops the earlier name from
3474           * the metadata the retry recovers it from.
3475           *
3476           * The names are collected before deleting so a request which repeats
3477           * the same name across many sub-sizes still issues one query per
3478           * distinct name.
3479           */
3480          $recoverable = $this->get_sideloaded_file_names( $attachment_id, false );
3481          $consumed    = array();
3482          foreach ( $sub_sizes as $sub_size ) {
3483              foreach ( array( 'file', 'original_image' ) as $key ) {
3484                  // Matches the set validate_sub_size_provenance() checked, so
3485                  // every name a request was allowed to store is also cleaned up.
3486                  if (
3487                      isset( $sub_size[ $key ] ) &&
3488                      is_string( $sub_size[ $key ] ) &&
3489                      in_array( $sub_size[ $key ], $recoverable, true )
3490                  ) {
3491                      $consumed[] = $sub_size[ $key ];
3492                  }
3493              }
3494          }
3495  
3496          foreach ( array_unique( $consumed ) as $file_name ) {
3497              delete_post_meta( $attachment_id, self::META_KEY_SIDELOAD_FILE_NAME, wp_slash( $file_name ) );
3498          }
3499  
3500          $response_request = new WP_REST_Request(
3501              WP_REST_Server::READABLE,
3502              rest_get_route_for_post( $attachment_id )
3503          );
3504  
3505          $response_request['context'] = 'edit';
3506  
3507          if ( isset( $request['_fields'] ) ) {
3508              $response_request['_fields'] = $request['_fields'];
3509          }
3510  
3511          /*
3512           * Re-read the post. The 'wp_generate_attachment_metadata' filter above
3513           * runs long after $post was fetched, and a callback that rewrites the
3514           * post row - an optimizer changing post_mime_type once it has
3515           * converted the file, say - would otherwise be missing from this
3516           * response. The editor stores the response as its copy of the record
3517           * rather than reading the attachment again, so a stale row here is
3518           * what it keeps. A callback that deleted the attachment instead leaves
3519           * nothing to respond with, so that is reported as the error it is.
3520           */
3521          $post = $this->get_post( $attachment_id );
3522          if ( is_wp_error( $post ) ) {
3523              return $post;
3524          }
3525  
3526          return $this->prepare_item_for_response( $post, $response_request );
3527      }
3528  }


Generated : Wed Oct 14 08:20:33 2026 Cross-referenced by PHPXref