[ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
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 * Registers the routes for attachments. 29 * 30 * @since 5.3.0 31 * 32 * @see register_rest_route() 33 */ 34 public function register_routes() { 35 parent::register_routes(); 36 register_rest_route( 37 $this->namespace, 38 '/' . $this->rest_base . '/(?P<id>[\d]+)/post-process', 39 array( 40 'methods' => WP_REST_Server::CREATABLE, 41 'callback' => array( $this, 'post_process_item' ), 42 'permission_callback' => array( $this, 'post_process_item_permissions_check' ), 43 'args' => array( 44 'id' => array( 45 'description' => __( 'Unique identifier for the attachment.' ), 46 'type' => 'integer', 47 ), 48 'action' => array( 49 'type' => 'string', 50 'enum' => array( 'create-image-subsizes' ), 51 'required' => true, 52 ), 53 ), 54 ) 55 ); 56 register_rest_route( 57 $this->namespace, 58 '/' . $this->rest_base . '/(?P<id>[\d]+)/edit', 59 array( 60 'methods' => WP_REST_Server::CREATABLE, 61 'callback' => array( $this, 'edit_media_item' ), 62 'permission_callback' => array( $this, 'edit_media_item_permissions_check' ), 63 'args' => $this->get_edit_media_item_args(), 64 ) 65 ); 66 } 67 68 /** 69 * Determines the allowed query_vars for a get_items() response and 70 * prepares for WP_Query. 71 * 72 * @since 4.7.0 73 * @since 6.9.0 Extends the `media_type` and `mime_type` request arguments to support array values. 74 * 75 * @param array $prepared_args Optional. Array of prepared arguments. Default empty array. 76 * @param WP_REST_Request $request Optional. Request to prepare items for. 77 * @return array Array of query arguments. 78 */ 79 protected function prepare_items_query( $prepared_args = array(), $request = null ) { 80 $query_args = parent::prepare_items_query( $prepared_args, $request ); 81 82 if ( empty( $query_args['post_status'] ) ) { 83 $query_args['post_status'] = 'inherit'; 84 } 85 86 $all_mime_types = array(); 87 $media_types = $this->get_media_types(); 88 89 if ( ! empty( $request['media_type'] ) && is_array( $request['media_type'] ) ) { 90 foreach ( $request['media_type'] as $type ) { 91 if ( isset( $media_types[ $type ] ) ) { 92 $all_mime_types = array_merge( $all_mime_types, $media_types[ $type ] ); 93 } 94 } 95 } 96 97 if ( ! empty( $request['mime_type'] ) && is_array( $request['mime_type'] ) ) { 98 foreach ( $request['mime_type'] as $mime_type ) { 99 $parts = explode( '/', $mime_type ); 100 if ( isset( $media_types[ $parts[0] ] ) && in_array( $mime_type, $media_types[ $parts[0] ], true ) ) { 101 $all_mime_types[] = $mime_type; 102 } 103 } 104 } 105 106 if ( ! empty( $all_mime_types ) ) { 107 $query_args['post_mime_type'] = array_values( array_unique( $all_mime_types ) ); 108 } 109 110 // Filter query clauses to include filenames. 111 if ( isset( $query_args['s'] ) ) { 112 add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' ); 113 } 114 115 return $query_args; 116 } 117 118 /** 119 * Checks if a given request has access to create an attachment. 120 * 121 * @since 4.7.0 122 * 123 * @param WP_REST_Request $request Full details about the request. 124 * @return true|WP_Error Boolean true if the attachment may be created, or a WP_Error if not. 125 */ 126 public function create_item_permissions_check( $request ) { 127 $ret = parent::create_item_permissions_check( $request ); 128 129 if ( ! $ret || is_wp_error( $ret ) ) { 130 return $ret; 131 } 132 133 if ( ! current_user_can( 'upload_files' ) ) { 134 return new WP_Error( 135 'rest_cannot_create', 136 __( 'Sorry, you are not allowed to upload media on this site.' ), 137 array( 'status' => 400 ) 138 ); 139 } 140 141 // Attaching media to a post requires ability to edit said post. 142 if ( ! empty( $request['post'] ) && ! current_user_can( 'edit_post', (int) $request['post'] ) ) { 143 return new WP_Error( 144 'rest_cannot_edit', 145 __( 'Sorry, you are not allowed to upload media to this post.' ), 146 array( 'status' => rest_authorization_required_code() ) 147 ); 148 } 149 $files = $request->get_file_params(); 150 151 /** 152 * Filter whether the server should prevent uploads for image types it doesn't support. Default true. 153 * 154 * Developers can use this filter to enable uploads of certain image types. By default image types that are not 155 * supported by the server are prevented from being uploaded. 156 * 157 * @since 6.8.0 158 * 159 * @param bool $check_mime Whether to prevent uploads of unsupported image types. 160 * @param string|null $mime_type The mime type of the file being uploaded (if available). 161 */ 162 $prevent_unsupported_uploads = apply_filters( 'wp_prevent_unsupported_mime_type_uploads', true, isset( $files['file']['type'] ) ? $files['file']['type'] : null ); 163 164 // If the upload is an image, check if the server can handle the mime type. 165 if ( 166 $prevent_unsupported_uploads && 167 isset( $files['file']['type'] ) && 168 str_starts_with( $files['file']['type'], 'image/' ) 169 ) { 170 // List of non-resizable image formats. 171 $editor_non_resizable_formats = array( 172 'image/svg+xml', 173 ); 174 175 // Check if the image editor supports the type or ignore if it isn't a format resizable by an editor. 176 if ( 177 ! in_array( $files['file']['type'], $editor_non_resizable_formats, true ) && 178 ! wp_image_editor_supports( array( 'mime_type' => $files['file']['type'] ) ) 179 ) { 180 return new WP_Error( 181 'rest_upload_image_type_not_supported', 182 __( 'The web server cannot generate responsive image sizes for this image. Convert it to JPEG or PNG before uploading.' ), 183 array( 'status' => 400 ) 184 ); 185 } 186 } 187 188 return true; 189 } 190 191 /** 192 * Creates a single attachment. 193 * 194 * @since 4.7.0 195 * 196 * @param WP_REST_Request $request Full details about the request. 197 * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. 198 */ 199 public function create_item( $request ) { 200 if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) { 201 return new WP_Error( 202 'rest_invalid_param', 203 __( 'Invalid parent type.' ), 204 array( 'status' => 400 ) 205 ); 206 } 207 208 $insert = $this->insert_attachment( $request ); 209 210 if ( is_wp_error( $insert ) ) { 211 return $insert; 212 } 213 214 $schema = $this->get_item_schema(); 215 216 // Extract by name. 217 $attachment_id = $insert['attachment_id']; 218 $file = $insert['file']; 219 220 if ( isset( $request['alt_text'] ) ) { 221 update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) ); 222 } 223 224 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) { 225 $thumbnail_update = $this->handle_featured_media( $request['featured_media'], $attachment_id ); 226 227 if ( is_wp_error( $thumbnail_update ) ) { 228 return $thumbnail_update; 229 } 230 } 231 232 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { 233 $meta_update = $this->meta->update_value( $request['meta'], $attachment_id ); 234 235 if ( is_wp_error( $meta_update ) ) { 236 return $meta_update; 237 } 238 } 239 240 $attachment = get_post( $attachment_id ); 241 $fields_update = $this->update_additional_fields_for_object( $attachment, $request ); 242 243 if ( is_wp_error( $fields_update ) ) { 244 return $fields_update; 245 } 246 247 $terms_update = $this->handle_terms( $attachment_id, $request ); 248 249 if ( is_wp_error( $terms_update ) ) { 250 return $terms_update; 251 } 252 253 $request->set_param( 'context', 'edit' ); 254 255 /** 256 * Fires after a single attachment is completely created or updated via the REST API. 257 * 258 * @since 5.0.0 259 * 260 * @param WP_Post $attachment Inserted or updated attachment object. 261 * @param WP_REST_Request $request Request object. 262 * @param bool $creating True when creating an attachment, false when updating. 263 */ 264 do_action( 'rest_after_insert_attachment', $attachment, $request, true ); 265 266 wp_after_insert_post( $attachment, false, null ); 267 268 if ( wp_is_serving_rest_request() ) { 269 /* 270 * Set a custom header with the attachment_id. 271 * Used by the browser/client to resume creating image sub-sizes after a PHP fatal error. 272 */ 273 header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id ); 274 } 275 276 // Include media and image functions to get access to wp_generate_attachment_metadata(). 277 require_once ABSPATH . 'wp-admin/includes/media.php'; 278 require_once ABSPATH . 'wp-admin/includes/image.php'; 279 280 /* 281 * Post-process the upload (create image sub-sizes, make PDF thumbnails, etc.) and insert attachment meta. 282 * At this point the server may run out of resources and post-processing of uploaded images may fail. 283 */ 284 wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) ); 285 286 $response = $this->prepare_item_for_response( $attachment, $request ); 287 $response = rest_ensure_response( $response ); 288 $response->set_status( 201 ); 289 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $attachment_id ) ) ); 290 291 return $response; 292 } 293 294 /** 295 * Inserts the attachment post in the database. Does not update the attachment meta. 296 * 297 * @since 5.3.0 298 * 299 * @param WP_REST_Request $request 300 * @return array|WP_Error 301 */ 302 protected function insert_attachment( $request ) { 303 // Get the file via $_FILES or raw data. 304 $files = $request->get_file_params(); 305 $headers = $request->get_headers(); 306 307 $time = null; 308 309 // Matches logic in media_handle_upload(). 310 if ( ! empty( $request['post'] ) ) { 311 $post = get_post( $request['post'] ); 312 // The post date doesn't usually matter for pages, so don't backdate this upload. 313 if ( $post && 'page' !== $post->post_type && substr( $post->post_date, 0, 4 ) > 0 ) { 314 $time = $post->post_date; 315 } 316 } 317 318 if ( ! empty( $files ) ) { 319 $file = $this->upload_from_file( $files, $headers, $time ); 320 } else { 321 $file = $this->upload_from_data( $request->get_body(), $headers, $time ); 322 } 323 324 if ( is_wp_error( $file ) ) { 325 return $file; 326 } 327 328 $name = wp_basename( $file['file'] ); 329 $name_parts = pathinfo( $name ); 330 $name = trim( substr( $name, 0, -( 1 + strlen( $name_parts['extension'] ) ) ) ); 331 332 $url = $file['url']; 333 $type = $file['type']; 334 $file = $file['file']; 335 336 // Include image functions to get access to wp_read_image_metadata(). 337 require_once ABSPATH . 'wp-admin/includes/image.php'; 338 339 // Use image exif/iptc data for title and caption defaults if possible. 340 $image_meta = wp_read_image_metadata( $file ); 341 342 if ( ! empty( $image_meta ) ) { 343 if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) { 344 $request['title'] = $image_meta['title']; 345 } 346 347 if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) { 348 $request['caption'] = $image_meta['caption']; 349 } 350 } 351 352 $attachment = $this->prepare_item_for_database( $request ); 353 354 $attachment->post_mime_type = $type; 355 $attachment->guid = $url; 356 357 // If the title was not set, use the original filename. 358 if ( empty( $attachment->post_title ) && ! empty( $files['file']['name'] ) ) { 359 // Remove the file extension (after the last `.`) 360 $tmp_title = substr( $files['file']['name'], 0, strrpos( $files['file']['name'], '.' ) ); 361 362 if ( ! empty( $tmp_title ) ) { 363 $attachment->post_title = $tmp_title; 364 } 365 } 366 367 // Fall back to the original approach. 368 if ( empty( $attachment->post_title ) ) { 369 $attachment->post_title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) ); 370 } 371 372 // $post_parent is inherited from $attachment['post_parent']. 373 $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true, false ); 374 375 if ( is_wp_error( $id ) ) { 376 if ( 'db_update_error' === $id->get_error_code() ) { 377 $id->add_data( array( 'status' => 500 ) ); 378 } else { 379 $id->add_data( array( 'status' => 400 ) ); 380 } 381 382 return $id; 383 } 384 385 $attachment = get_post( $id ); 386 387 /** 388 * Fires after a single attachment is created or updated via the REST API. 389 * 390 * @since 4.7.0 391 * 392 * @param WP_Post $attachment Inserted or updated attachment object. 393 * @param WP_REST_Request $request The request sent to the API. 394 * @param bool $creating True when creating an attachment, false when updating. 395 */ 396 do_action( 'rest_insert_attachment', $attachment, $request, true ); 397 398 return array( 399 'attachment_id' => $id, 400 'file' => $file, 401 ); 402 } 403 404 /** 405 * Determines the featured media based on a request param. 406 * 407 * @since 6.5.0 408 * 409 * @param int $featured_media Featured Media ID. 410 * @param int $post_id Post ID. 411 * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error. 412 */ 413 protected function handle_featured_media( $featured_media, $post_id ) { 414 $post_type = get_post_type( $post_id ); 415 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ); 416 417 // Similar check as in wp_insert_post(). 418 if ( ! $thumbnail_support && get_post_mime_type( $post_id ) ) { 419 if ( wp_attachment_is( 'audio', $post_id ) ) { 420 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' ); 421 } elseif ( wp_attachment_is( 'video', $post_id ) ) { 422 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' ); 423 } 424 } 425 426 if ( $thumbnail_support ) { 427 return parent::handle_featured_media( $featured_media, $post_id ); 428 } 429 430 return new WP_Error( 431 'rest_no_featured_media', 432 sprintf( 433 /* translators: %s: attachment mime type */ 434 __( 'This site does not support post thumbnails on attachments with MIME type %s.' ), 435 get_post_mime_type( $post_id ) 436 ), 437 array( 'status' => 400 ) 438 ); 439 } 440 441 /** 442 * Updates a single attachment. 443 * 444 * @since 4.7.0 445 * 446 * @param WP_REST_Request $request Full details about the request. 447 * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. 448 */ 449 public function update_item( $request ) { 450 if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) { 451 return new WP_Error( 452 'rest_invalid_param', 453 __( 'Invalid parent type.' ), 454 array( 'status' => 400 ) 455 ); 456 } 457 458 $attachment_before = get_post( $request['id'] ); 459 $response = parent::update_item( $request ); 460 461 if ( is_wp_error( $response ) ) { 462 return $response; 463 } 464 465 $response = rest_ensure_response( $response ); 466 $data = $response->get_data(); 467 468 if ( isset( $request['alt_text'] ) ) { 469 update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] ); 470 } 471 472 $attachment = get_post( $request['id'] ); 473 474 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) { 475 $thumbnail_update = $this->handle_featured_media( $request['featured_media'], $attachment->ID ); 476 477 if ( is_wp_error( $thumbnail_update ) ) { 478 return $thumbnail_update; 479 } 480 } 481 482 $fields_update = $this->update_additional_fields_for_object( $attachment, $request ); 483 484 if ( is_wp_error( $fields_update ) ) { 485 return $fields_update; 486 } 487 488 $request->set_param( 'context', 'edit' ); 489 490 /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */ 491 do_action( 'rest_after_insert_attachment', $attachment, $request, false ); 492 493 wp_after_insert_post( $attachment, true, $attachment_before ); 494 495 $response = $this->prepare_item_for_response( $attachment, $request ); 496 $response = rest_ensure_response( $response ); 497 498 return $response; 499 } 500 501 /** 502 * Performs post-processing on an attachment. 503 * 504 * @since 5.3.0 505 * 506 * @param WP_REST_Request $request Full details about the request. 507 * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. 508 */ 509 public function post_process_item( $request ) { 510 switch ( $request['action'] ) { 511 case 'create-image-subsizes': 512 require_once ABSPATH . 'wp-admin/includes/image.php'; 513 wp_update_image_subsizes( $request['id'] ); 514 break; 515 } 516 517 $request['context'] = 'edit'; 518 519 return $this->prepare_item_for_response( get_post( $request['id'] ), $request ); 520 } 521 522 /** 523 * Checks if a given request can perform post-processing on an attachment. 524 * 525 * @since 5.3.0 526 * 527 * @param WP_REST_Request $request Full details about the request. 528 * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. 529 */ 530 public function post_process_item_permissions_check( $request ) { 531 return $this->update_item_permissions_check( $request ); 532 } 533 534 /** 535 * Checks if a given request has access to editing media. 536 * 537 * @since 5.5.0 538 * 539 * @param WP_REST_Request $request Full details about the request. 540 * @return true|WP_Error True if the request has read access, WP_Error object otherwise. 541 */ 542 public function edit_media_item_permissions_check( $request ) { 543 if ( ! current_user_can( 'upload_files' ) ) { 544 return new WP_Error( 545 'rest_cannot_edit_image', 546 __( 'Sorry, you are not allowed to upload media on this site.' ), 547 array( 'status' => rest_authorization_required_code() ) 548 ); 549 } 550 551 return $this->update_item_permissions_check( $request ); 552 } 553 554 /** 555 * Applies edits to a media item and creates a new attachment record. 556 * 557 * @since 5.5.0 558 * @since 6.9.0 Adds flips capability and editable fields for the newly-created attachment post. 559 * 560 * @param WP_REST_Request $request Full details about the request. 561 * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. 562 */ 563 public function edit_media_item( $request ) { 564 require_once ABSPATH . 'wp-admin/includes/image.php'; 565 566 $attachment_id = $request['id']; 567 568 // This also confirms the attachment is an image. 569 $image_file = wp_get_original_image_path( $attachment_id ); 570 $image_meta = wp_get_attachment_metadata( $attachment_id ); 571 572 if ( 573 ! $image_meta || 574 ! $image_file || 575 ! wp_image_file_matches_image_meta( $request['src'], $image_meta, $attachment_id ) 576 ) { 577 return new WP_Error( 578 'rest_unknown_attachment', 579 __( 'Unable to get meta information for file.' ), 580 array( 'status' => 404 ) 581 ); 582 } 583 584 $supported_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif', 'image/heic' ); 585 $mime_type = get_post_mime_type( $attachment_id ); 586 if ( ! in_array( $mime_type, $supported_types, true ) ) { 587 return new WP_Error( 588 'rest_cannot_edit_file_type', 589 __( 'This type of file cannot be edited.' ), 590 array( 'status' => 400 ) 591 ); 592 } 593 594 // The `modifiers` param takes precedence over the older format. 595 if ( isset( $request['modifiers'] ) ) { 596 $modifiers = $request['modifiers']; 597 } else { 598 $modifiers = array(); 599 600 if ( isset( $request['flip']['horizontal'] ) || isset( $request['flip']['vertical'] ) ) { 601 $flip_args = array( 602 'vertical' => isset( $request['flip']['vertical'] ) ? (bool) $request['flip']['vertical'] : false, 603 'horizontal' => isset( $request['flip']['horizontal'] ) ? (bool) $request['flip']['horizontal'] : false, 604 ); 605 606 $modifiers[] = array( 607 'type' => 'flip', 608 'args' => array( 609 'flip' => $flip_args, 610 ), 611 ); 612 } 613 614 if ( ! empty( $request['rotation'] ) ) { 615 $modifiers[] = array( 616 'type' => 'rotate', 617 'args' => array( 618 'angle' => $request['rotation'], 619 ), 620 ); 621 } 622 623 if ( isset( $request['x'], $request['y'], $request['width'], $request['height'] ) ) { 624 $modifiers[] = array( 625 'type' => 'crop', 626 'args' => array( 627 'left' => $request['x'], 628 'top' => $request['y'], 629 'width' => $request['width'], 630 'height' => $request['height'], 631 ), 632 ); 633 } 634 635 if ( 0 === count( $modifiers ) ) { 636 return new WP_Error( 637 'rest_image_not_edited', 638 __( 'The image was not edited. Edit the image before applying the changes.' ), 639 array( 'status' => 400 ) 640 ); 641 } 642 } 643 644 /* 645 * If the file doesn't exist, attempt a URL fopen on the src link. 646 * This can occur with certain file replication plugins. 647 * Keep the original file path to get a modified name later. 648 */ 649 $image_file_to_edit = $image_file; 650 if ( ! file_exists( $image_file_to_edit ) ) { 651 $image_file_to_edit = _load_image_to_edit_path( $attachment_id ); 652 } 653 654 $image_editor = wp_get_image_editor( $image_file_to_edit ); 655 656 if ( is_wp_error( $image_editor ) ) { 657 return new WP_Error( 658 'rest_unknown_image_file_type', 659 __( 'Unable to edit this image.' ), 660 array( 'status' => 500 ) 661 ); 662 } 663 664 foreach ( $modifiers as $modifier ) { 665 $args = $modifier['args']; 666 switch ( $modifier['type'] ) { 667 case 'flip': 668 /* 669 * Flips the current image. 670 * The vertical flip is the first argument (flip along horizontal axis), the horizontal flip is the second argument (flip along vertical axis). 671 * See: WP_Image_Editor::flip() 672 */ 673 $result = $image_editor->flip( $args['flip']['vertical'], $args['flip']['horizontal'] ); 674 if ( is_wp_error( $result ) ) { 675 return new WP_Error( 676 'rest_image_flip_failed', 677 __( 'Unable to flip this image.' ), 678 array( 'status' => 500 ) 679 ); 680 } 681 break; 682 case 'rotate': 683 // Rotation direction: clockwise vs. counterclockwise. 684 $rotate = 0 - $args['angle']; 685 686 if ( 0 !== $rotate ) { 687 $result = $image_editor->rotate( $rotate ); 688 689 if ( is_wp_error( $result ) ) { 690 return new WP_Error( 691 'rest_image_rotation_failed', 692 __( 'Unable to rotate this image.' ), 693 array( 'status' => 500 ) 694 ); 695 } 696 } 697 698 break; 699 700 case 'crop': 701 $size = $image_editor->get_size(); 702 703 $crop_x = (int) round( ( $size['width'] * $args['left'] ) / 100.0 ); 704 $crop_y = (int) round( ( $size['height'] * $args['top'] ) / 100.0 ); 705 $width = (int) round( ( $size['width'] * $args['width'] ) / 100.0 ); 706 $height = (int) round( ( $size['height'] * $args['height'] ) / 100.0 ); 707 708 if ( $size['width'] !== $width || $size['height'] !== $height ) { 709 $result = $image_editor->crop( $crop_x, $crop_y, $width, $height ); 710 711 if ( is_wp_error( $result ) ) { 712 return new WP_Error( 713 'rest_image_crop_failed', 714 __( 'Unable to crop this image.' ), 715 array( 'status' => 500 ) 716 ); 717 } 718 } 719 720 break; 721 722 } 723 } 724 725 // Calculate the file name. 726 $image_ext = pathinfo( $image_file, PATHINFO_EXTENSION ); 727 $image_name = wp_basename( $image_file, ".{$image_ext}" ); 728 729 /* 730 * Do not append multiple `-edited` to the file name. 731 * The user may be editing a previously edited image. 732 */ 733 if ( preg_match( '/-edited(-\d+)?$/', $image_name ) ) { 734 // Remove any `-1`, `-2`, etc. `wp_unique_filename()` will add the proper number. 735 $image_name = preg_replace( '/-edited(-\d+)?$/', '-edited', $image_name ); 736 } else { 737 // Append `-edited` before the extension. 738 $image_name .= '-edited'; 739 } 740 741 $filename = "{$image_name}.{$image_ext}"; 742 743 // Create the uploads subdirectory if needed. 744 $uploads = wp_upload_dir(); 745 746 // Make the file name unique in the (new) upload directory. 747 $filename = wp_unique_filename( $uploads['path'], $filename ); 748 749 // Save to disk. 750 $saved = $image_editor->save( $uploads['path'] . "/$filename" ); 751 752 if ( is_wp_error( $saved ) ) { 753 return $saved; 754 } 755 756 // Grab original attachment post so we can use it to set defaults. 757 $original_attachment_post = get_post( $attachment_id ); 758 759 // Check request fields and assign default values. 760 $new_attachment_post = $this->prepare_item_for_database( $request ); 761 $new_attachment_post->post_mime_type = $saved['mime-type']; 762 $new_attachment_post->guid = $uploads['url'] . "/$filename"; 763 764 // Unset ID so wp_insert_attachment generates a new ID. 765 unset( $new_attachment_post->ID ); 766 767 // Set new attachment post title with fallbacks. 768 $new_attachment_post->post_title = $new_attachment_post->post_title ?? $original_attachment_post->post_title ?? $image_name; 769 770 // Set new attachment post caption (post_excerpt). 771 $new_attachment_post->post_excerpt = $new_attachment_post->post_excerpt ?? $original_attachment_post->post_excerpt ?? ''; 772 773 // Set new attachment post description (post_content) with fallbacks. 774 $new_attachment_post->post_content = $new_attachment_post->post_content ?? $original_attachment_post->post_content ?? ''; 775 776 // Set post parent if set in request, else the default of `0` (no parent). 777 $new_attachment_post->post_parent = $new_attachment_post->post_parent ?? 0; 778 779 // Insert the new attachment post. 780 $new_attachment_id = wp_insert_attachment( wp_slash( $new_attachment_post ), $saved['path'], 0, true ); 781 782 if ( is_wp_error( $new_attachment_id ) ) { 783 if ( 'db_update_error' === $new_attachment_id->get_error_code() ) { 784 $new_attachment_id->add_data( array( 'status' => 500 ) ); 785 } else { 786 $new_attachment_id->add_data( array( 'status' => 400 ) ); 787 } 788 789 return $new_attachment_id; 790 } 791 792 // First, try to use the alt text from the request. If not set, copy the image alt text from the original attachment. 793 $image_alt = isset( $request['alt_text'] ) ? sanitize_text_field( $request['alt_text'] ) : get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); 794 795 if ( ! empty( $image_alt ) ) { 796 // update_post_meta() expects slashed. 797 update_post_meta( $new_attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) ); 798 } 799 800 if ( wp_is_serving_rest_request() ) { 801 /* 802 * Set a custom header with the attachment_id. 803 * Used by the browser/client to resume creating image sub-sizes after a PHP fatal error. 804 */ 805 header( 'X-WP-Upload-Attachment-ID: ' . $new_attachment_id ); 806 } 807 808 // Generate image sub-sizes and meta. 809 $new_image_meta = wp_generate_attachment_metadata( $new_attachment_id, $saved['path'] ); 810 811 // Copy the EXIF metadata from the original attachment if not generated for the edited image. 812 if ( isset( $image_meta['image_meta'] ) && isset( $new_image_meta['image_meta'] ) && is_array( $new_image_meta['image_meta'] ) ) { 813 // Merge but skip empty values. 814 foreach ( (array) $image_meta['image_meta'] as $key => $value ) { 815 if ( empty( $new_image_meta['image_meta'][ $key ] ) && ! empty( $value ) ) { 816 $new_image_meta['image_meta'][ $key ] = $value; 817 } 818 } 819 } 820 821 // Reset orientation. At this point the image is edited and orientation is correct. 822 if ( ! empty( $new_image_meta['image_meta']['orientation'] ) ) { 823 $new_image_meta['image_meta']['orientation'] = 1; 824 } 825 826 // The attachment_id may change if the site is exported and imported. 827 $new_image_meta['parent_image'] = array( 828 'attachment_id' => $attachment_id, 829 // Path to the originally uploaded image file relative to the uploads directory. 830 'file' => _wp_relative_upload_path( $image_file ), 831 ); 832 833 /** 834 * Filters the meta data for the new image created by editing an existing image. 835 * 836 * @since 5.5.0 837 * 838 * @param array $new_image_meta Meta data for the new image. 839 * @param int $new_attachment_id Attachment post ID for the new image. 840 * @param int $attachment_id Attachment post ID for the edited (parent) image. 841 */ 842 $new_image_meta = apply_filters( 'wp_edited_image_metadata', $new_image_meta, $new_attachment_id, $attachment_id ); 843 844 wp_update_attachment_metadata( $new_attachment_id, $new_image_meta ); 845 846 $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request ); 847 $response->set_status( 201 ); 848 $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) ); 849 850 return $response; 851 } 852 853 /** 854 * Prepares a single attachment for create or update. 855 * 856 * @since 4.7.0 857 * 858 * @param WP_REST_Request $request Request object. 859 * @return stdClass|WP_Error Post object. 860 */ 861 protected function prepare_item_for_database( $request ) { 862 $prepared_attachment = parent::prepare_item_for_database( $request ); 863 864 // Attachment caption (post_excerpt internally). 865 if ( isset( $request['caption'] ) ) { 866 if ( is_string( $request['caption'] ) ) { 867 $prepared_attachment->post_excerpt = $request['caption']; 868 } elseif ( isset( $request['caption']['raw'] ) ) { 869 $prepared_attachment->post_excerpt = $request['caption']['raw']; 870 } 871 } 872 873 // Attachment description (post_content internally). 874 if ( isset( $request['description'] ) ) { 875 if ( is_string( $request['description'] ) ) { 876 $prepared_attachment->post_content = $request['description']; 877 } elseif ( isset( $request['description']['raw'] ) ) { 878 $prepared_attachment->post_content = $request['description']['raw']; 879 } 880 } 881 882 if ( isset( $request['post'] ) ) { 883 $prepared_attachment->post_parent = (int) $request['post']; 884 } 885 886 return $prepared_attachment; 887 } 888 889 /** 890 * Prepares a single attachment output for response. 891 * 892 * @since 4.7.0 893 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. 894 * 895 * @param WP_Post $item Attachment object. 896 * @param WP_REST_Request $request Request object. 897 * @return WP_REST_Response Response object. 898 */ 899 public function prepare_item_for_response( $item, $request ) { 900 // Restores the more descriptive, specific name for use within this method. 901 $post = $item; 902 903 $response = parent::prepare_item_for_response( $post, $request ); 904 $fields = $this->get_fields_for_response( $request ); 905 $data = $response->get_data(); 906 907 if ( in_array( 'description', $fields, true ) ) { 908 $data['description'] = array( 909 'raw' => $post->post_content, 910 /** This filter is documented in wp-includes/post-template.php */ 911 'rendered' => apply_filters( 'the_content', $post->post_content ), 912 ); 913 } 914 915 if ( in_array( 'caption', $fields, true ) ) { 916 /** This filter is documented in wp-includes/post-template.php */ 917 $caption = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ); 918 919 /** This filter is documented in wp-includes/post-template.php */ 920 $caption = apply_filters( 'the_excerpt', $caption ); 921 922 $data['caption'] = array( 923 'raw' => $post->post_excerpt, 924 'rendered' => $caption, 925 ); 926 } 927 928 if ( in_array( 'alt_text', $fields, true ) ) { 929 $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true ); 930 } 931 932 if ( in_array( 'media_type', $fields, true ) ) { 933 $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file'; 934 } 935 936 if ( in_array( 'mime_type', $fields, true ) ) { 937 $data['mime_type'] = $post->post_mime_type; 938 } 939 940 if ( in_array( 'media_details', $fields, true ) ) { 941 $data['media_details'] = wp_get_attachment_metadata( $post->ID ); 942 943 // Ensure empty details is an empty object. 944 if ( empty( $data['media_details'] ) ) { 945 $data['media_details'] = new stdClass(); 946 } elseif ( ! empty( $data['media_details']['sizes'] ) ) { 947 948 foreach ( $data['media_details']['sizes'] as $size => &$size_data ) { 949 950 if ( isset( $size_data['mime-type'] ) ) { 951 $size_data['mime_type'] = $size_data['mime-type']; 952 unset( $size_data['mime-type'] ); 953 } 954 955 // Use the same method image_downsize() does. 956 $image_src = wp_get_attachment_image_src( $post->ID, $size ); 957 if ( ! $image_src ) { 958 continue; 959 } 960 961 $size_data['source_url'] = $image_src[0]; 962 } 963 964 $full_src = wp_get_attachment_image_src( $post->ID, 'full' ); 965 966 if ( ! empty( $full_src ) ) { 967 $data['media_details']['sizes']['full'] = array( 968 'file' => wp_basename( $full_src[0] ), 969 'width' => $full_src[1], 970 'height' => $full_src[2], 971 'mime_type' => $post->post_mime_type, 972 'source_url' => $full_src[0], 973 ); 974 } 975 } else { 976 $data['media_details']['sizes'] = new stdClass(); 977 } 978 } 979 980 if ( in_array( 'post', $fields, true ) ) { 981 $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null; 982 } 983 984 if ( in_array( 'source_url', $fields, true ) ) { 985 $data['source_url'] = wp_get_attachment_url( $post->ID ); 986 } 987 988 if ( in_array( 'missing_image_sizes', $fields, true ) ) { 989 require_once ABSPATH . 'wp-admin/includes/image.php'; 990 $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) ); 991 } 992 993 $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; 994 995 $data = $this->filter_response_by_context( $data, $context ); 996 997 $links = $response->get_links(); 998 999 // Wrap the data in a response object. 1000 $response = rest_ensure_response( $data ); 1001 1002 foreach ( $links as $rel => $rel_links ) { 1003 foreach ( $rel_links as $link ) { 1004 $response->add_link( $rel, $link['href'], $link['attributes'] ); 1005 } 1006 } 1007 1008 /** 1009 * Filters an attachment returned from the REST API. 1010 * 1011 * Allows modification of the attachment right before it is returned. 1012 * 1013 * @since 4.7.0 1014 * 1015 * @param WP_REST_Response $response The response object. 1016 * @param WP_Post $post The original attachment post. 1017 * @param WP_REST_Request $request Request used to generate the response. 1018 */ 1019 return apply_filters( 'rest_prepare_attachment', $response, $post, $request ); 1020 } 1021 1022 /** 1023 * Prepares attachment links for the request. 1024 * 1025 * @since 6.9.0 1026 * 1027 * @param WP_Post $post Post object. 1028 * @return array Links for the given attachment. 1029 */ 1030 protected function prepare_links( $post ) { 1031 $links = parent::prepare_links( $post ); 1032 1033 if ( ! empty( $post->post_parent ) ) { 1034 $post = get_post( $post->post_parent ); 1035 1036 if ( ! empty( $post ) ) { 1037 $links['https://api.w.org/attached-to'] = array( 1038 'href' => rest_url( rest_get_route_for_post( $post ) ), 1039 'embeddable' => true, 1040 'post_type' => $post->post_type, 1041 'id' => $post->ID, 1042 ); 1043 } 1044 } 1045 1046 return $links; 1047 } 1048 1049 /** 1050 * Retrieves the attachment's schema, conforming to JSON Schema. 1051 * 1052 * @since 4.7.0 1053 * 1054 * @return array Item schema as an array. 1055 */ 1056 public function get_item_schema() { 1057 if ( $this->schema ) { 1058 return $this->add_additional_fields_schema( $this->schema ); 1059 } 1060 1061 $schema = parent::get_item_schema(); 1062 1063 $schema['properties']['alt_text'] = array( 1064 'description' => __( 'Alternative text to display when attachment is not displayed.' ), 1065 'type' => 'string', 1066 'context' => array( 'view', 'edit', 'embed' ), 1067 'arg_options' => array( 1068 'sanitize_callback' => 'sanitize_text_field', 1069 ), 1070 ); 1071 1072 $schema['properties']['caption'] = array( 1073 'description' => __( 'The attachment caption.' ), 1074 'type' => 'object', 1075 'context' => array( 'view', 'edit', 'embed' ), 1076 'arg_options' => array( 1077 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 1078 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). 1079 ), 1080 'properties' => array( 1081 'raw' => array( 1082 'description' => __( 'Caption for the attachment, as it exists in the database.' ), 1083 'type' => 'string', 1084 'context' => array( 'edit' ), 1085 ), 1086 'rendered' => array( 1087 'description' => __( 'HTML caption for the attachment, transformed for display.' ), 1088 'type' => 'string', 1089 'context' => array( 'view', 'edit', 'embed' ), 1090 'readonly' => true, 1091 ), 1092 ), 1093 ); 1094 1095 $schema['properties']['description'] = array( 1096 'description' => __( 'The attachment description.' ), 1097 'type' => 'object', 1098 'context' => array( 'view', 'edit' ), 1099 'arg_options' => array( 1100 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 1101 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). 1102 ), 1103 'properties' => array( 1104 'raw' => array( 1105 'description' => __( 'Description for the attachment, as it exists in the database.' ), 1106 'type' => 'string', 1107 'context' => array( 'edit' ), 1108 ), 1109 'rendered' => array( 1110 'description' => __( 'HTML description for the attachment, transformed for display.' ), 1111 'type' => 'string', 1112 'context' => array( 'view', 'edit' ), 1113 'readonly' => true, 1114 ), 1115 ), 1116 ); 1117 1118 $schema['properties']['media_type'] = array( 1119 'description' => __( 'Attachment type.' ), 1120 'type' => 'string', 1121 'enum' => array( 'image', 'file' ), 1122 'context' => array( 'view', 'edit', 'embed' ), 1123 'readonly' => true, 1124 ); 1125 1126 $schema['properties']['mime_type'] = array( 1127 'description' => __( 'The attachment MIME type.' ), 1128 'type' => 'string', 1129 'context' => array( 'view', 'edit', 'embed' ), 1130 'readonly' => true, 1131 ); 1132 1133 $schema['properties']['media_details'] = array( 1134 'description' => __( 'Details about the media file, specific to its type.' ), 1135 'type' => 'object', 1136 'context' => array( 'view', 'edit', 'embed' ), 1137 'readonly' => true, 1138 ); 1139 1140 $schema['properties']['post'] = array( 1141 'description' => __( 'The ID for the associated post of the attachment.' ), 1142 'type' => 'integer', 1143 'context' => array( 'view', 'edit' ), 1144 ); 1145 1146 $schema['properties']['source_url'] = array( 1147 'description' => __( 'URL to the original attachment file.' ), 1148 'type' => 'string', 1149 'format' => 'uri', 1150 'context' => array( 'view', 'edit', 'embed' ), 1151 'readonly' => true, 1152 ); 1153 1154 $schema['properties']['missing_image_sizes'] = array( 1155 'description' => __( 'List of the missing image sizes of the attachment.' ), 1156 'type' => 'array', 1157 'items' => array( 'type' => 'string' ), 1158 'context' => array( 'edit' ), 1159 'readonly' => true, 1160 ); 1161 1162 unset( $schema['properties']['password'] ); 1163 1164 $this->schema = $schema; 1165 1166 return $this->add_additional_fields_schema( $this->schema ); 1167 } 1168 1169 /** 1170 * Handles an upload via raw POST data. 1171 * 1172 * @since 4.7.0 1173 * @since 6.6.0 Added the `$time` parameter. 1174 * 1175 * @param string $data Supplied file data. 1176 * @param array $headers HTTP headers from the request. 1177 * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. 1178 * @return array|WP_Error Data from wp_handle_sideload(). 1179 */ 1180 protected function upload_from_data( $data, $headers, $time = null ) { 1181 if ( empty( $data ) ) { 1182 return new WP_Error( 1183 'rest_upload_no_data', 1184 __( 'No data supplied.' ), 1185 array( 'status' => 400 ) 1186 ); 1187 } 1188 1189 if ( empty( $headers['content_type'] ) ) { 1190 return new WP_Error( 1191 'rest_upload_no_content_type', 1192 __( 'No Content-Type supplied.' ), 1193 array( 'status' => 400 ) 1194 ); 1195 } 1196 1197 if ( empty( $headers['content_disposition'] ) ) { 1198 return new WP_Error( 1199 'rest_upload_no_content_disposition', 1200 __( 'No Content-Disposition supplied.' ), 1201 array( 'status' => 400 ) 1202 ); 1203 } 1204 1205 $filename = self::get_filename_from_disposition( $headers['content_disposition'] ); 1206 1207 if ( empty( $filename ) ) { 1208 return new WP_Error( 1209 'rest_upload_invalid_disposition', 1210 __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ), 1211 array( 'status' => 400 ) 1212 ); 1213 } 1214 1215 if ( ! empty( $headers['content_md5'] ) ) { 1216 $content_md5 = array_shift( $headers['content_md5'] ); 1217 $expected = trim( $content_md5 ); 1218 $actual = md5( $data ); 1219 1220 if ( $expected !== $actual ) { 1221 return new WP_Error( 1222 'rest_upload_hash_mismatch', 1223 __( 'Content hash did not match expected.' ), 1224 array( 'status' => 412 ) 1225 ); 1226 } 1227 } 1228 1229 // Get the content-type. 1230 $type = array_shift( $headers['content_type'] ); 1231 1232 // Include filesystem functions to get access to wp_tempnam() and wp_handle_sideload(). 1233 require_once ABSPATH . 'wp-admin/includes/file.php'; 1234 1235 // Save the file. 1236 $tmpfname = wp_tempnam( $filename ); 1237 1238 $fp = fopen( $tmpfname, 'w+' ); 1239 1240 if ( ! $fp ) { 1241 return new WP_Error( 1242 'rest_upload_file_error', 1243 __( 'Could not open file handle.' ), 1244 array( 'status' => 500 ) 1245 ); 1246 } 1247 1248 fwrite( $fp, $data ); 1249 fclose( $fp ); 1250 1251 // Now, sideload it in. 1252 $file_data = array( 1253 'error' => null, 1254 'tmp_name' => $tmpfname, 1255 'name' => $filename, 1256 'type' => $type, 1257 ); 1258 1259 $size_check = self::check_upload_size( $file_data ); 1260 if ( is_wp_error( $size_check ) ) { 1261 return $size_check; 1262 } 1263 1264 $overrides = array( 1265 'test_form' => false, 1266 ); 1267 1268 $sideloaded = wp_handle_sideload( $file_data, $overrides, $time ); 1269 1270 if ( isset( $sideloaded['error'] ) ) { 1271 @unlink( $tmpfname ); 1272 1273 return new WP_Error( 1274 'rest_upload_sideload_error', 1275 $sideloaded['error'], 1276 array( 'status' => 500 ) 1277 ); 1278 } 1279 1280 return $sideloaded; 1281 } 1282 1283 /** 1284 * Parses filename from a Content-Disposition header value. 1285 * 1286 * As per RFC6266: 1287 * 1288 * content-disposition = "Content-Disposition" ":" 1289 * disposition-type *( ";" disposition-parm ) 1290 * 1291 * disposition-type = "inline" | "attachment" | disp-ext-type 1292 * ; case-insensitive 1293 * disp-ext-type = token 1294 * 1295 * disposition-parm = filename-parm | disp-ext-parm 1296 * 1297 * filename-parm = "filename" "=" value 1298 * | "filename*" "=" ext-value 1299 * 1300 * disp-ext-parm = token "=" value 1301 * | ext-token "=" ext-value 1302 * ext-token = <the characters in token, followed by "*"> 1303 * 1304 * @since 4.7.0 1305 * 1306 * @link https://tools.ietf.org/html/rfc2388 1307 * @link https://tools.ietf.org/html/rfc6266 1308 * 1309 * @param string[] $disposition_header List of Content-Disposition header values. 1310 * @return string|null Filename if available, or null if not found. 1311 */ 1312 public static function get_filename_from_disposition( $disposition_header ) { 1313 // Get the filename. 1314 $filename = null; 1315 1316 foreach ( $disposition_header as $value ) { 1317 $value = trim( $value ); 1318 1319 if ( ! str_contains( $value, ';' ) ) { 1320 continue; 1321 } 1322 1323 list( , $attr_parts ) = explode( ';', $value, 2 ); 1324 1325 $attr_parts = explode( ';', $attr_parts ); 1326 $attributes = array(); 1327 1328 foreach ( $attr_parts as $part ) { 1329 if ( ! str_contains( $part, '=' ) ) { 1330 continue; 1331 } 1332 1333 list( $key, $value ) = explode( '=', $part, 2 ); 1334 1335 $attributes[ trim( $key ) ] = trim( $value ); 1336 } 1337 1338 if ( empty( $attributes['filename'] ) ) { 1339 continue; 1340 } 1341 1342 $filename = trim( $attributes['filename'] ); 1343 1344 // Unquote quoted filename, but after trimming. 1345 if ( str_starts_with( $filename, '"' ) && str_ends_with( $filename, '"' ) ) { 1346 $filename = substr( $filename, 1, -1 ); 1347 } 1348 } 1349 1350 return $filename; 1351 } 1352 1353 /** 1354 * Retrieves the query params for collections of attachments. 1355 * 1356 * @since 4.7.0 1357 * @since 6.9.0 Extends the `media_type` and `mime_type` request arguments to support array values. 1358 * 1359 * @return array Query parameters for the attachment collection as an array. 1360 */ 1361 public function get_collection_params() { 1362 $params = parent::get_collection_params(); 1363 $params['status']['default'] = 'inherit'; 1364 $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' ); 1365 $media_types = array_keys( $this->get_media_types() ); 1366 1367 $params['media_type'] = array( 1368 'default' => null, 1369 'description' => __( 'Limit result set to attachments of a particular media type or media types.' ), 1370 'type' => 'array', 1371 'items' => array( 1372 'type' => 'string', 1373 'enum' => $media_types, 1374 ), 1375 ); 1376 1377 $params['mime_type'] = array( 1378 'default' => null, 1379 'description' => __( 'Limit result set to attachments of a particular MIME type or MIME types.' ), 1380 'type' => 'array', 1381 'items' => array( 1382 'type' => 'string', 1383 ), 1384 ); 1385 1386 return $params; 1387 } 1388 1389 /** 1390 * Handles an upload via multipart/form-data ($_FILES). 1391 * 1392 * @since 4.7.0 1393 * @since 6.6.0 Added the `$time` parameter. 1394 * 1395 * @param array $files Data from the `$_FILES` superglobal. 1396 * @param array $headers HTTP headers from the request. 1397 * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. 1398 * @return array|WP_Error Data from wp_handle_upload(). 1399 */ 1400 protected function upload_from_file( $files, $headers, $time = null ) { 1401 if ( empty( $files ) ) { 1402 return new WP_Error( 1403 'rest_upload_no_data', 1404 __( 'No data supplied.' ), 1405 array( 'status' => 400 ) 1406 ); 1407 } 1408 1409 // Verify hash, if given. 1410 if ( ! empty( $headers['content_md5'] ) ) { 1411 $content_md5 = array_shift( $headers['content_md5'] ); 1412 $expected = trim( $content_md5 ); 1413 $actual = md5_file( $files['file']['tmp_name'] ); 1414 1415 if ( $expected !== $actual ) { 1416 return new WP_Error( 1417 'rest_upload_hash_mismatch', 1418 __( 'Content hash did not match expected.' ), 1419 array( 'status' => 412 ) 1420 ); 1421 } 1422 } 1423 1424 // Pass off to WP to handle the actual upload. 1425 $overrides = array( 1426 'test_form' => false, 1427 ); 1428 1429 // Bypasses is_uploaded_file() when running unit tests. 1430 if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) { 1431 $overrides['action'] = 'wp_handle_mock_upload'; 1432 } 1433 1434 $size_check = self::check_upload_size( $files['file'] ); 1435 if ( is_wp_error( $size_check ) ) { 1436 return $size_check; 1437 } 1438 1439 // Include filesystem functions to get access to wp_handle_upload(). 1440 require_once ABSPATH . 'wp-admin/includes/file.php'; 1441 1442 $file = wp_handle_upload( $files['file'], $overrides, $time ); 1443 1444 if ( isset( $file['error'] ) ) { 1445 return new WP_Error( 1446 'rest_upload_unknown_error', 1447 $file['error'], 1448 array( 'status' => 500 ) 1449 ); 1450 } 1451 1452 return $file; 1453 } 1454 1455 /** 1456 * Retrieves the supported media types. 1457 * 1458 * Media types are considered the MIME type category. 1459 * 1460 * @since 4.7.0 1461 * 1462 * @return array Array of supported media types. 1463 */ 1464 protected function get_media_types() { 1465 $media_types = array(); 1466 1467 foreach ( get_allowed_mime_types() as $mime_type ) { 1468 $parts = explode( '/', $mime_type ); 1469 1470 if ( ! isset( $media_types[ $parts[0] ] ) ) { 1471 $media_types[ $parts[0] ] = array(); 1472 } 1473 1474 $media_types[ $parts[0] ][] = $mime_type; 1475 } 1476 1477 return $media_types; 1478 } 1479 1480 /** 1481 * Determine if uploaded file exceeds space quota on multisite. 1482 * 1483 * Replicates check_upload_size(). 1484 * 1485 * @since 4.9.8 1486 * 1487 * @param array $file $_FILES array for a given file. 1488 * @return true|WP_Error True if can upload, error for errors. 1489 */ 1490 protected function check_upload_size( $file ) { 1491 if ( ! is_multisite() ) { 1492 return true; 1493 } 1494 1495 if ( get_site_option( 'upload_space_check_disabled' ) ) { 1496 return true; 1497 } 1498 1499 $space_left = get_upload_space_available(); 1500 1501 $file_size = filesize( $file['tmp_name'] ); 1502 1503 if ( $space_left < $file_size ) { 1504 return new WP_Error( 1505 'rest_upload_limited_space', 1506 /* translators: %s: Required disk space in kilobytes. */ 1507 sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ), 1508 array( 'status' => 400 ) 1509 ); 1510 } 1511 1512 if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) { 1513 return new WP_Error( 1514 'rest_upload_file_too_big', 1515 /* translators: %s: Maximum allowed file size in kilobytes. */ 1516 sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ), 1517 array( 'status' => 400 ) 1518 ); 1519 } 1520 1521 // Include multisite admin functions to get access to upload_is_user_over_quota(). 1522 require_once ABSPATH . 'wp-admin/includes/ms.php'; 1523 1524 if ( upload_is_user_over_quota( false ) ) { 1525 return new WP_Error( 1526 'rest_upload_user_quota_exceeded', 1527 __( 'You have used your space quota. Please delete files before uploading.' ), 1528 array( 'status' => 400 ) 1529 ); 1530 } 1531 1532 return true; 1533 } 1534 1535 /** 1536 * Gets the request args for the edit item route. 1537 * 1538 * @since 5.5.0 1539 * @since 6.9.0 Adds flips capability and editable fields for the newly-created attachment post. 1540 * 1541 * @return array 1542 */ 1543 protected function get_edit_media_item_args() { 1544 $args = array( 1545 'src' => array( 1546 'description' => __( 'URL to the edited image file.' ), 1547 'type' => 'string', 1548 'format' => 'uri', 1549 'required' => true, 1550 ), 1551 // The `modifiers` param takes precedence over the older format. 1552 'modifiers' => array( 1553 'description' => __( 'Array of image edits.' ), 1554 'type' => 'array', 1555 'minItems' => 1, 1556 'items' => array( 1557 'description' => __( 'Image edit.' ), 1558 'type' => 'object', 1559 'required' => array( 1560 'type', 1561 'args', 1562 ), 1563 'oneOf' => array( 1564 array( 1565 'title' => __( 'Flip' ), 1566 'properties' => array( 1567 'type' => array( 1568 'description' => __( 'Flip type.' ), 1569 'type' => 'string', 1570 'enum' => array( 'flip' ), 1571 ), 1572 'args' => array( 1573 'description' => __( 'Flip arguments.' ), 1574 'type' => 'object', 1575 'required' => array( 1576 'flip', 1577 ), 1578 'properties' => array( 1579 'flip' => array( 1580 'description' => __( 'Flip direction.' ), 1581 'type' => 'object', 1582 'required' => array( 1583 'horizontal', 1584 'vertical', 1585 ), 1586 'properties' => array( 1587 'horizontal' => array( 1588 'description' => __( 'Whether to flip in the horizontal direction.' ), 1589 'type' => 'boolean', 1590 ), 1591 'vertical' => array( 1592 'description' => __( 'Whether to flip in the vertical direction.' ), 1593 'type' => 'boolean', 1594 ), 1595 ), 1596 ), 1597 ), 1598 ), 1599 ), 1600 ), 1601 array( 1602 'title' => __( 'Rotation' ), 1603 'properties' => array( 1604 'type' => array( 1605 'description' => __( 'Rotation type.' ), 1606 'type' => 'string', 1607 'enum' => array( 'rotate' ), 1608 ), 1609 'args' => array( 1610 'description' => __( 'Rotation arguments.' ), 1611 'type' => 'object', 1612 'required' => array( 1613 'angle', 1614 ), 1615 'properties' => array( 1616 'angle' => array( 1617 'description' => __( 'Angle to rotate clockwise in degrees.' ), 1618 'type' => 'number', 1619 ), 1620 ), 1621 ), 1622 ), 1623 ), 1624 array( 1625 'title' => __( 'Crop' ), 1626 'properties' => array( 1627 'type' => array( 1628 'description' => __( 'Crop type.' ), 1629 'type' => 'string', 1630 'enum' => array( 'crop' ), 1631 ), 1632 'args' => array( 1633 'description' => __( 'Crop arguments.' ), 1634 'type' => 'object', 1635 'required' => array( 1636 'left', 1637 'top', 1638 'width', 1639 'height', 1640 ), 1641 'properties' => array( 1642 'left' => array( 1643 'description' => __( 'Horizontal position from the left to begin the crop as a percentage of the image width.' ), 1644 'type' => 'number', 1645 ), 1646 'top' => array( 1647 'description' => __( 'Vertical position from the top to begin the crop as a percentage of the image height.' ), 1648 'type' => 'number', 1649 ), 1650 'width' => array( 1651 'description' => __( 'Width of the crop as a percentage of the image width.' ), 1652 'type' => 'number', 1653 ), 1654 'height' => array( 1655 'description' => __( 'Height of the crop as a percentage of the image height.' ), 1656 'type' => 'number', 1657 ), 1658 ), 1659 ), 1660 ), 1661 ), 1662 ), 1663 ), 1664 ), 1665 'rotation' => array( 1666 'description' => __( 'The amount to rotate the image clockwise in degrees. DEPRECATED: Use `modifiers` instead.' ), 1667 'type' => 'integer', 1668 'minimum' => 0, 1669 'exclusiveMinimum' => true, 1670 'maximum' => 360, 1671 'exclusiveMaximum' => true, 1672 ), 1673 'x' => array( 1674 'description' => __( 'As a percentage of the image, the x position to start the crop from. DEPRECATED: Use `modifiers` instead.' ), 1675 'type' => 'number', 1676 'minimum' => 0, 1677 'maximum' => 100, 1678 ), 1679 'y' => array( 1680 'description' => __( 'As a percentage of the image, the y position to start the crop from. DEPRECATED: Use `modifiers` instead.' ), 1681 'type' => 'number', 1682 'minimum' => 0, 1683 'maximum' => 100, 1684 ), 1685 'width' => array( 1686 'description' => __( 'As a percentage of the image, the width to crop the image to. DEPRECATED: Use `modifiers` instead.' ), 1687 'type' => 'number', 1688 'minimum' => 0, 1689 'maximum' => 100, 1690 ), 1691 'height' => array( 1692 'description' => __( 'As a percentage of the image, the height to crop the image to. DEPRECATED: Use `modifiers` instead.' ), 1693 'type' => 'number', 1694 'minimum' => 0, 1695 'maximum' => 100, 1696 ), 1697 ); 1698 1699 /* 1700 * Get the args based on the post schema. This calls `rest_get_endpoint_args_for_schema()`, 1701 * which also takes care of sanitization and validation. 1702 */ 1703 $update_item_args = $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ); 1704 1705 if ( isset( $update_item_args['caption'] ) ) { 1706 $args['caption'] = $update_item_args['caption']; 1707 } 1708 1709 if ( isset( $update_item_args['description'] ) ) { 1710 $args['description'] = $update_item_args['description']; 1711 } 1712 1713 if ( isset( $update_item_args['title'] ) ) { 1714 $args['title'] = $update_item_args['title']; 1715 } 1716 1717 if ( isset( $update_item_args['post'] ) ) { 1718 $args['post'] = $update_item_args['post']; 1719 } 1720 1721 if ( isset( $update_item_args['alt_text'] ) ) { 1722 $args['alt_text'] = $update_item_args['alt_text']; 1723 } 1724 1725 return $args; 1726 } 1727 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Wed Oct 15 08:20:04 2025 | Cross-referenced by PHPXref |