[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/rest-api/endpoints/ -> class-wp-rest-attachments-controller.php (source)

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


Generated : Mon Jul 13 08:20:15 2026 Cross-referenced by PHPXref