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


Generated : Tue Nov 3 08:20:36 2026 Cross-referenced by PHPXref