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


Generated : Mon Nov 23 08:20:01 2026 Cross-referenced by PHPXref