[ Index ]

PHP Cross Reference of WordPress

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       * Registers the routes for attachments.
  21       *
  22       * @since 5.3.0
  23       *
  24       * @see register_rest_route()
  25       */
  26  	public function register_routes() {
  27          parent::register_routes();
  28          register_rest_route(
  29              $this->namespace,
  30              '/' . $this->rest_base . '/(?P<id>[\d]+)/post-process',
  31              array(
  32                  'methods'             => WP_REST_Server::CREATABLE,
  33                  'callback'            => array( $this, 'post_process_item' ),
  34                  'permission_callback' => array( $this, 'post_process_item_permissions_check' ),
  35                  'args'                => array(
  36                      'id'     => array(
  37                          'description' => __( 'Unique identifier for the object.' ),
  38                          'type'        => 'integer',
  39                      ),
  40                      'action' => array(
  41                          'type'     => 'string',
  42                          'enum'     => array( 'create-image-subsizes' ),
  43                          'required' => true,
  44                      ),
  45                  ),
  46              )
  47          );
  48          register_rest_route(
  49              $this->namespace,
  50              '/' . $this->rest_base . '/(?P<id>[\d]+)/edit',
  51              array(
  52                  'methods'             => WP_REST_Server::CREATABLE,
  53                  'callback'            => array( $this, 'edit_media_item' ),
  54                  'permission_callback' => array( $this, 'edit_media_item_permissions_check' ),
  55                  'args'                => $this->get_edit_media_item_args(),
  56              )
  57          );
  58      }
  59  
  60      /**
  61       * Determines the allowed query_vars for a get_items() response and
  62       * prepares for WP_Query.
  63       *
  64       * @since 4.7.0
  65       *
  66       * @param array           $prepared_args Optional. Array of prepared arguments. Default empty array.
  67       * @param WP_REST_Request $request       Optional. Request to prepare items for.
  68       * @return array Array of query arguments.
  69       */
  70  	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
  71          $query_args = parent::prepare_items_query( $prepared_args, $request );
  72  
  73          if ( empty( $query_args['post_status'] ) ) {
  74              $query_args['post_status'] = 'inherit';
  75          }
  76  
  77          $media_types = $this->get_media_types();
  78  
  79          if ( ! empty( $request['media_type'] ) && isset( $media_types[ $request['media_type'] ] ) ) {
  80              $query_args['post_mime_type'] = $media_types[ $request['media_type'] ];
  81          }
  82  
  83          if ( ! empty( $request['mime_type'] ) ) {
  84              $parts = explode( '/', $request['mime_type'] );
  85              if ( isset( $media_types[ $parts[0] ] ) && in_array( $request['mime_type'], $media_types[ $parts[0] ], true ) ) {
  86                  $query_args['post_mime_type'] = $request['mime_type'];
  87              }
  88          }
  89  
  90          // Filter query clauses to include filenames.
  91          if ( isset( $query_args['s'] ) ) {
  92              add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
  93          }
  94  
  95          return $query_args;
  96      }
  97  
  98      /**
  99       * Checks if a given request has access to create an attachment.
 100       *
 101       * @since 4.7.0
 102       *
 103       * @param WP_REST_Request $request Full details about the request.
 104       * @return true|WP_Error Boolean true if the attachment may be created, or a WP_Error if not.
 105       */
 106  	public function create_item_permissions_check( $request ) {
 107          $ret = parent::create_item_permissions_check( $request );
 108  
 109          if ( ! $ret || is_wp_error( $ret ) ) {
 110              return $ret;
 111          }
 112  
 113          if ( ! current_user_can( 'upload_files' ) ) {
 114              return new WP_Error(
 115                  'rest_cannot_create',
 116                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 117                  array( 'status' => 400 )
 118              );
 119          }
 120  
 121          // Attaching media to a post requires ability to edit said post.
 122          if ( ! empty( $request['post'] ) && ! current_user_can( 'edit_post', (int) $request['post'] ) ) {
 123              return new WP_Error(
 124                  'rest_cannot_edit',
 125                  __( 'Sorry, you are not allowed to upload media to this post.' ),
 126                  array( 'status' => rest_authorization_required_code() )
 127              );
 128          }
 129  
 130          return true;
 131      }
 132  
 133      /**
 134       * Creates a single attachment.
 135       *
 136       * @since 4.7.0
 137       *
 138       * @param WP_REST_Request $request Full details about the request.
 139       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 140       */
 141  	public function create_item( $request ) {
 142          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 143              return new WP_Error(
 144                  'rest_invalid_param',
 145                  __( 'Invalid parent type.' ),
 146                  array( 'status' => 400 )
 147              );
 148          }
 149  
 150          $insert = $this->insert_attachment( $request );
 151  
 152          if ( is_wp_error( $insert ) ) {
 153              return $insert;
 154          }
 155  
 156          $schema = $this->get_item_schema();
 157  
 158          // Extract by name.
 159          $attachment_id = $insert['attachment_id'];
 160          $file          = $insert['file'];
 161  
 162          if ( isset( $request['alt_text'] ) ) {
 163              update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
 164          }
 165  
 166          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 167              $meta_update = $this->meta->update_value( $request['meta'], $attachment_id );
 168  
 169              if ( is_wp_error( $meta_update ) ) {
 170                  return $meta_update;
 171              }
 172          }
 173  
 174          $attachment    = get_post( $attachment_id );
 175          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 176  
 177          if ( is_wp_error( $fields_update ) ) {
 178              return $fields_update;
 179          }
 180  
 181          $request->set_param( 'context', 'edit' );
 182  
 183          /**
 184           * Fires after a single attachment is completely created or updated via the REST API.
 185           *
 186           * @since 5.0.0
 187           *
 188           * @param WP_Post         $attachment Inserted or updated attachment object.
 189           * @param WP_REST_Request $request    Request object.
 190           * @param bool            $creating   True when creating an attachment, false when updating.
 191           */
 192          do_action( 'rest_after_insert_attachment', $attachment, $request, true );
 193  
 194          wp_after_insert_post( $attachment, false );
 195  
 196          if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
 197              // Set a custom header with the attachment_id.
 198              // Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
 199              header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id );
 200          }
 201  
 202          // Include media and image functions to get access to wp_generate_attachment_metadata().
 203          require_once ABSPATH . 'wp-admin/includes/media.php';
 204          require_once ABSPATH . 'wp-admin/includes/image.php';
 205  
 206          // Post-process the upload (create image sub-sizes, make PDF thumbnails, etc.) and insert attachment meta.
 207          // At this point the server may run out of resources and post-processing of uploaded images may fail.
 208          wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
 209  
 210          $response = $this->prepare_item_for_response( $attachment, $request );
 211          $response = rest_ensure_response( $response );
 212          $response->set_status( 201 );
 213          $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $attachment_id ) ) );
 214  
 215          return $response;
 216      }
 217  
 218      /**
 219       * Inserts the attachment post in the database. Does not update the attachment meta.
 220       *
 221       * @since 5.3.0
 222       *
 223       * @param WP_REST_Request $request
 224       * @return array|WP_Error
 225       */
 226  	protected function insert_attachment( $request ) {
 227          // Get the file via $_FILES or raw data.
 228          $files   = $request->get_file_params();
 229          $headers = $request->get_headers();
 230  
 231          if ( ! empty( $files ) ) {
 232              $file = $this->upload_from_file( $files, $headers );
 233          } else {
 234              $file = $this->upload_from_data( $request->get_body(), $headers );
 235          }
 236  
 237          if ( is_wp_error( $file ) ) {
 238              return $file;
 239          }
 240  
 241          $name       = wp_basename( $file['file'] );
 242          $name_parts = pathinfo( $name );
 243          $name       = trim( substr( $name, 0, -( 1 + strlen( $name_parts['extension'] ) ) ) );
 244  
 245          $url  = $file['url'];
 246          $type = $file['type'];
 247          $file = $file['file'];
 248  
 249          // Include image functions to get access to wp_read_image_metadata().
 250          require_once ABSPATH . 'wp-admin/includes/image.php';
 251  
 252          // Use image exif/iptc data for title and caption defaults if possible.
 253          $image_meta = wp_read_image_metadata( $file );
 254  
 255          if ( ! empty( $image_meta ) ) {
 256              if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
 257                  $request['title'] = $image_meta['title'];
 258              }
 259  
 260              if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
 261                  $request['caption'] = $image_meta['caption'];
 262              }
 263          }
 264  
 265          $attachment = $this->prepare_item_for_database( $request );
 266  
 267          $attachment->post_mime_type = $type;
 268          $attachment->guid           = $url;
 269  
 270          if ( empty( $attachment->post_title ) ) {
 271              $attachment->post_title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) );
 272          }
 273  
 274          // $post_parent is inherited from $attachment['post_parent'].
 275          $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true, false );
 276  
 277          if ( is_wp_error( $id ) ) {
 278              if ( 'db_update_error' === $id->get_error_code() ) {
 279                  $id->add_data( array( 'status' => 500 ) );
 280              } else {
 281                  $id->add_data( array( 'status' => 400 ) );
 282              }
 283  
 284              return $id;
 285          }
 286  
 287          $attachment = get_post( $id );
 288  
 289          /**
 290           * Fires after a single attachment is created or updated via the REST API.
 291           *
 292           * @since 4.7.0
 293           *
 294           * @param WP_Post         $attachment Inserted or updated attachment
 295           *                                    object.
 296           * @param WP_REST_Request $request    The request sent to the API.
 297           * @param bool            $creating   True when creating an attachment, false when updating.
 298           */
 299          do_action( 'rest_insert_attachment', $attachment, $request, true );
 300  
 301          return array(
 302              'attachment_id' => $id,
 303              'file'          => $file,
 304          );
 305      }
 306  
 307      /**
 308       * Updates a single attachment.
 309       *
 310       * @since 4.7.0
 311       *
 312       * @param WP_REST_Request $request Full details about the request.
 313       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 314       */
 315  	public function update_item( $request ) {
 316          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 317              return new WP_Error(
 318                  'rest_invalid_param',
 319                  __( 'Invalid parent type.' ),
 320                  array( 'status' => 400 )
 321              );
 322          }
 323  
 324          $response = parent::update_item( $request );
 325  
 326          if ( is_wp_error( $response ) ) {
 327              return $response;
 328          }
 329  
 330          $response = rest_ensure_response( $response );
 331          $data     = $response->get_data();
 332  
 333          if ( isset( $request['alt_text'] ) ) {
 334              update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
 335          }
 336  
 337          $attachment = get_post( $request['id'] );
 338  
 339          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 340  
 341          if ( is_wp_error( $fields_update ) ) {
 342              return $fields_update;
 343          }
 344  
 345          $request->set_param( 'context', 'edit' );
 346  
 347          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
 348          do_action( 'rest_after_insert_attachment', $attachment, $request, false );
 349  
 350          wp_after_insert_post( $attachment, true );
 351  
 352          $response = $this->prepare_item_for_response( $attachment, $request );
 353          $response = rest_ensure_response( $response );
 354  
 355          return $response;
 356      }
 357  
 358      /**
 359       * Performs post processing on an attachment.
 360       *
 361       * @since 5.3.0
 362       *
 363       * @param WP_REST_Request $request Full details about the request.
 364       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 365       */
 366  	public function post_process_item( $request ) {
 367          switch ( $request['action'] ) {
 368              case 'create-image-subsizes':
 369                  require_once ABSPATH . 'wp-admin/includes/image.php';
 370                  wp_update_image_subsizes( $request['id'] );
 371                  break;
 372          }
 373  
 374          $request['context'] = 'edit';
 375  
 376          return $this->prepare_item_for_response( get_post( $request['id'] ), $request );
 377      }
 378  
 379      /**
 380       * Checks if a given request can perform post processing on an attachment.
 381       *
 382       * @since 5.3.0
 383       *
 384       * @param WP_REST_Request $request Full details about the request.
 385       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
 386       */
 387  	public function post_process_item_permissions_check( $request ) {
 388          return $this->update_item_permissions_check( $request );
 389      }
 390  
 391      /**
 392       * Checks if a given request has access to editing media.
 393       *
 394       * @since 5.5.0
 395       *
 396       * @param WP_REST_Request $request Full details about the request.
 397       * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
 398       */
 399  	public function edit_media_item_permissions_check( $request ) {
 400          if ( ! current_user_can( 'upload_files' ) ) {
 401              return new WP_Error(
 402                  'rest_cannot_edit_image',
 403                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 404                  array( 'status' => rest_authorization_required_code() )
 405              );
 406          }
 407  
 408          return $this->update_item_permissions_check( $request );
 409      }
 410  
 411      /**
 412       * Applies edits to a media item and creates a new attachment record.
 413       *
 414       * @since 5.5.0
 415       *
 416       * @param WP_REST_Request $request Full details about the request.
 417       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 418       */
 419  	public function edit_media_item( $request ) {
 420          require_once ABSPATH . 'wp-admin/includes/image.php';
 421  
 422          $attachment_id = $request['id'];
 423  
 424          // This also confirms the attachment is an image.
 425          $image_file = wp_get_original_image_path( $attachment_id );
 426          $image_meta = wp_get_attachment_metadata( $attachment_id );
 427  
 428          if (
 429              ! $image_meta ||
 430              ! $image_file ||
 431              ! wp_image_file_matches_image_meta( $request['src'], $image_meta, $attachment_id )
 432          ) {
 433              return new WP_Error(
 434                  'rest_unknown_attachment',
 435                  __( 'Unable to get meta information for file.' ),
 436                  array( 'status' => 404 )
 437              );
 438          }
 439  
 440          $supported_types = array( 'image/jpeg', 'image/png', 'image/gif' );
 441          $mime_type       = get_post_mime_type( $attachment_id );
 442          if ( ! in_array( $mime_type, $supported_types, true ) ) {
 443              return new WP_Error(
 444                  'rest_cannot_edit_file_type',
 445                  __( 'This type of file cannot be edited.' ),
 446                  array( 'status' => 400 )
 447              );
 448          }
 449  
 450          // Check if we need to do anything.
 451          $rotate = 0;
 452          $crop   = false;
 453  
 454          if ( ! empty( $request['rotation'] ) ) {
 455              // Rotation direction: clockwise vs. counter clockwise.
 456              $rotate = 0 - (int) $request['rotation'];
 457          }
 458  
 459          if ( isset( $request['x'], $request['y'], $request['width'], $request['height'] ) ) {
 460              $crop = true;
 461          }
 462  
 463          if ( ! $rotate && ! $crop ) {
 464              return new WP_Error(
 465                  'rest_image_not_edited',
 466                  __( 'The image was not edited. Edit the image before applying the changes.' ),
 467                  array( 'status' => 400 )
 468              );
 469          }
 470  
 471          /*
 472           * If the file doesn't exist, attempt a URL fopen on the src link.
 473           * This can occur with certain file replication plugins.
 474           * Keep the original file path to get a modified name later.
 475           */
 476          $image_file_to_edit = $image_file;
 477          if ( ! file_exists( $image_file_to_edit ) ) {
 478              $image_file_to_edit = _load_image_to_edit_path( $attachment_id );
 479          }
 480  
 481          $image_editor = wp_get_image_editor( $image_file_to_edit );
 482  
 483          if ( is_wp_error( $image_editor ) ) {
 484              return new WP_Error(
 485                  'rest_unknown_image_file_type',
 486                  __( 'Unable to edit this image.' ),
 487                  array( 'status' => 500 )
 488              );
 489          }
 490  
 491          if ( 0 !== $rotate ) {
 492              $result = $image_editor->rotate( $rotate );
 493  
 494              if ( is_wp_error( $result ) ) {
 495                  return new WP_Error(
 496                      'rest_image_rotation_failed',
 497                      __( 'Unable to rotate this image.' ),
 498                      array( 'status' => 500 )
 499                  );
 500              }
 501          }
 502  
 503          if ( $crop ) {
 504              $size = $image_editor->get_size();
 505  
 506              $crop_x = round( ( $size['width'] * (float) $request['x'] ) / 100.0 );
 507              $crop_y = round( ( $size['height'] * (float) $request['y'] ) / 100.0 );
 508              $width  = round( ( $size['width'] * (float) $request['width'] ) / 100.0 );
 509              $height = round( ( $size['height'] * (float) $request['height'] ) / 100.0 );
 510  
 511              $result = $image_editor->crop( $crop_x, $crop_y, $width, $height );
 512  
 513              if ( is_wp_error( $result ) ) {
 514                  return new WP_Error(
 515                      'rest_image_crop_failed',
 516                      __( 'Unable to crop this image.' ),
 517                      array( 'status' => 500 )
 518                  );
 519              }
 520          }
 521  
 522          // Calculate the file name.
 523          $image_ext  = pathinfo( $image_file, PATHINFO_EXTENSION );
 524          $image_name = wp_basename( $image_file, ".{$image_ext}" );
 525  
 526          // Do not append multiple `-edited` to the file name.
 527          // The user may be editing a previously edited image.
 528          if ( preg_match( '/-edited(-\d+)?$/', $image_name ) ) {
 529              // Remove any `-1`, `-2`, etc. `wp_unique_filename()` will add the proper number.
 530              $image_name = preg_replace( '/-edited(-\d+)?$/', '-edited', $image_name );
 531          } else {
 532              // Append `-edited` before the extension.
 533              $image_name .= '-edited';
 534          }
 535  
 536          $filename = "{$image_name}.{$image_ext}";
 537  
 538          // Create the uploads sub-directory if needed.
 539          $uploads = wp_upload_dir();
 540  
 541          // Make the file name unique in the (new) upload directory.
 542          $filename = wp_unique_filename( $uploads['path'], $filename );
 543  
 544          // Save to disk.
 545          $saved = $image_editor->save( $uploads['path'] . "/$filename" );
 546  
 547          if ( is_wp_error( $saved ) ) {
 548              return $saved;
 549          }
 550  
 551          // Create new attachment post.
 552          $new_attachment_post = array(
 553              'post_mime_type' => $saved['mime-type'],
 554              'guid'           => $uploads['url'] . "/$filename",
 555              'post_title'     => $image_name,
 556              'post_content'   => '',
 557          );
 558  
 559          // Copy post_content, post_excerpt, and post_title from the edited image's attachment post.
 560          $attachment_post = get_post( $attachment_id );
 561  
 562          if ( $attachment_post ) {
 563              $new_attachment_post['post_content'] = $attachment_post->post_content;
 564              $new_attachment_post['post_excerpt'] = $attachment_post->post_excerpt;
 565              $new_attachment_post['post_title']   = $attachment_post->post_title;
 566          }
 567  
 568          $new_attachment_id = wp_insert_attachment( wp_slash( $new_attachment_post ), $saved['path'], 0, true );
 569  
 570          if ( is_wp_error( $new_attachment_id ) ) {
 571              if ( 'db_update_error' === $new_attachment_id->get_error_code() ) {
 572                  $new_attachment_id->add_data( array( 'status' => 500 ) );
 573              } else {
 574                  $new_attachment_id->add_data( array( 'status' => 400 ) );
 575              }
 576  
 577              return $new_attachment_id;
 578          }
 579  
 580          // Copy the image alt text from the edited image.
 581          $image_alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
 582  
 583          if ( ! empty( $image_alt ) ) {
 584              // update_post_meta() expects slashed.
 585              update_post_meta( $new_attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
 586          }
 587  
 588          if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
 589              // Set a custom header with the attachment_id.
 590              // Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
 591              header( 'X-WP-Upload-Attachment-ID: ' . $new_attachment_id );
 592          }
 593  
 594          // Generate image sub-sizes and meta.
 595          $new_image_meta = wp_generate_attachment_metadata( $new_attachment_id, $saved['path'] );
 596  
 597          // Copy the EXIF metadata from the original attachment if not generated for the edited image.
 598          if ( isset( $image_meta['image_meta'] ) && isset( $new_image_meta['image_meta'] ) && is_array( $new_image_meta['image_meta'] ) ) {
 599              // Merge but skip empty values.
 600              foreach ( (array) $image_meta['image_meta'] as $key => $value ) {
 601                  if ( empty( $new_image_meta['image_meta'][ $key ] ) && ! empty( $value ) ) {
 602                      $new_image_meta['image_meta'][ $key ] = $value;
 603                  }
 604              }
 605          }
 606  
 607          // Reset orientation. At this point the image is edited and orientation is correct.
 608          if ( ! empty( $new_image_meta['image_meta']['orientation'] ) ) {
 609              $new_image_meta['image_meta']['orientation'] = 1;
 610          }
 611  
 612          // The attachment_id may change if the site is exported and imported.
 613          $new_image_meta['parent_image'] = array(
 614              'attachment_id' => $attachment_id,
 615              // Path to the originally uploaded image file relative to the uploads directory.
 616              'file'          => _wp_relative_upload_path( $image_file ),
 617          );
 618  
 619          /**
 620           * Filters the meta data for the new image created by editing an existing image.
 621           *
 622           * @since 5.5.0
 623           *
 624           * @param array $new_image_meta    Meta data for the new image.
 625           * @param int   $new_attachment_id Attachment post ID for the new image.
 626           * @param int   $attachment_id     Attachment post ID for the edited (parent) image.
 627           */
 628          $new_image_meta = apply_filters( 'wp_edited_image_metadata', $new_image_meta, $new_attachment_id, $attachment_id );
 629  
 630          wp_update_attachment_metadata( $new_attachment_id, $new_image_meta );
 631  
 632          $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request );
 633          $response->set_status( 201 );
 634          $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) );
 635  
 636          return $response;
 637      }
 638  
 639      /**
 640       * Prepares a single attachment for create or update.
 641       *
 642       * @since 4.7.0
 643       *
 644       * @param WP_REST_Request $request Request object.
 645       * @return stdClass|WP_Error Post object.
 646       */
 647  	protected function prepare_item_for_database( $request ) {
 648          $prepared_attachment = parent::prepare_item_for_database( $request );
 649  
 650          // Attachment caption (post_excerpt internally).
 651          if ( isset( $request['caption'] ) ) {
 652              if ( is_string( $request['caption'] ) ) {
 653                  $prepared_attachment->post_excerpt = $request['caption'];
 654              } elseif ( isset( $request['caption']['raw'] ) ) {
 655                  $prepared_attachment->post_excerpt = $request['caption']['raw'];
 656              }
 657          }
 658  
 659          // Attachment description (post_content internally).
 660          if ( isset( $request['description'] ) ) {
 661              if ( is_string( $request['description'] ) ) {
 662                  $prepared_attachment->post_content = $request['description'];
 663              } elseif ( isset( $request['description']['raw'] ) ) {
 664                  $prepared_attachment->post_content = $request['description']['raw'];
 665              }
 666          }
 667  
 668          if ( isset( $request['post'] ) ) {
 669              $prepared_attachment->post_parent = (int) $request['post'];
 670          }
 671  
 672          return $prepared_attachment;
 673      }
 674  
 675      /**
 676       * Prepares a single attachment output for response.
 677       *
 678       * @since 4.7.0
 679       *
 680       * @param WP_Post         $post    Attachment object.
 681       * @param WP_REST_Request $request Request object.
 682       * @return WP_REST_Response Response object.
 683       */
 684  	public function prepare_item_for_response( $post, $request ) {
 685          $response = parent::prepare_item_for_response( $post, $request );
 686          $fields   = $this->get_fields_for_response( $request );
 687          $data     = $response->get_data();
 688  
 689          if ( in_array( 'description', $fields, true ) ) {
 690              $data['description'] = array(
 691                  'raw'      => $post->post_content,
 692                  /** This filter is documented in wp-includes/post-template.php */
 693                  'rendered' => apply_filters( 'the_content', $post->post_content ),
 694              );
 695          }
 696  
 697          if ( in_array( 'caption', $fields, true ) ) {
 698              /** This filter is documented in wp-includes/post-template.php */
 699              $caption = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
 700  
 701              /** This filter is documented in wp-includes/post-template.php */
 702              $caption = apply_filters( 'the_excerpt', $caption );
 703  
 704              $data['caption'] = array(
 705                  'raw'      => $post->post_excerpt,
 706                  'rendered' => $caption,
 707              );
 708          }
 709  
 710          if ( in_array( 'alt_text', $fields, true ) ) {
 711              $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
 712          }
 713  
 714          if ( in_array( 'media_type', $fields, true ) ) {
 715              $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
 716          }
 717  
 718          if ( in_array( 'mime_type', $fields, true ) ) {
 719              $data['mime_type'] = $post->post_mime_type;
 720          }
 721  
 722          if ( in_array( 'media_details', $fields, true ) ) {
 723              $data['media_details'] = wp_get_attachment_metadata( $post->ID );
 724  
 725              // Ensure empty details is an empty object.
 726              if ( empty( $data['media_details'] ) ) {
 727                  $data['media_details'] = new stdClass;
 728              } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
 729  
 730                  foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
 731  
 732                      if ( isset( $size_data['mime-type'] ) ) {
 733                          $size_data['mime_type'] = $size_data['mime-type'];
 734                          unset( $size_data['mime-type'] );
 735                      }
 736  
 737                      // Use the same method image_downsize() does.
 738                      $image_src = wp_get_attachment_image_src( $post->ID, $size );
 739                      if ( ! $image_src ) {
 740                          continue;
 741                      }
 742  
 743                      $size_data['source_url'] = $image_src[0];
 744                  }
 745  
 746                  $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
 747  
 748                  if ( ! empty( $full_src ) ) {
 749                      $data['media_details']['sizes']['full'] = array(
 750                          'file'       => wp_basename( $full_src[0] ),
 751                          'width'      => $full_src[1],
 752                          'height'     => $full_src[2],
 753                          'mime_type'  => $post->post_mime_type,
 754                          'source_url' => $full_src[0],
 755                      );
 756                  }
 757              } else {
 758                  $data['media_details']['sizes'] = new stdClass;
 759              }
 760          }
 761  
 762          if ( in_array( 'post', $fields, true ) ) {
 763              $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
 764          }
 765  
 766          if ( in_array( 'source_url', $fields, true ) ) {
 767              $data['source_url'] = wp_get_attachment_url( $post->ID );
 768          }
 769  
 770          if ( in_array( 'missing_image_sizes', $fields, true ) ) {
 771              require_once ABSPATH . 'wp-admin/includes/image.php';
 772              $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) );
 773          }
 774  
 775          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
 776  
 777          $data = $this->filter_response_by_context( $data, $context );
 778  
 779          $links = $response->get_links();
 780  
 781          // Wrap the data in a response object.
 782          $response = rest_ensure_response( $data );
 783  
 784          foreach ( $links as $rel => $rel_links ) {
 785              foreach ( $rel_links as $link ) {
 786                  $response->add_link( $rel, $link['href'], $link['attributes'] );
 787              }
 788          }
 789  
 790          /**
 791           * Filters an attachment returned from the REST API.
 792           *
 793           * Allows modification of the attachment right before it is returned.
 794           *
 795           * @since 4.7.0
 796           *
 797           * @param WP_REST_Response $response The response object.
 798           * @param WP_Post          $post     The original attachment post.
 799           * @param WP_REST_Request  $request  Request used to generate the response.
 800           */
 801          return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
 802      }
 803  
 804      /**
 805       * Retrieves the attachment's schema, conforming to JSON Schema.
 806       *
 807       * @since 4.7.0
 808       *
 809       * @return array Item schema as an array.
 810       */
 811  	public function get_item_schema() {
 812          if ( $this->schema ) {
 813              return $this->add_additional_fields_schema( $this->schema );
 814          }
 815  
 816          $schema = parent::get_item_schema();
 817  
 818          $schema['properties']['alt_text'] = array(
 819              'description' => __( 'Alternative text to display when attachment is not displayed.' ),
 820              'type'        => 'string',
 821              'context'     => array( 'view', 'edit', 'embed' ),
 822              'arg_options' => array(
 823                  'sanitize_callback' => 'sanitize_text_field',
 824              ),
 825          );
 826  
 827          $schema['properties']['caption'] = array(
 828              'description' => __( 'The attachment caption.' ),
 829              'type'        => 'object',
 830              'context'     => array( 'view', 'edit', 'embed' ),
 831              'arg_options' => array(
 832                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
 833                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
 834              ),
 835              'properties'  => array(
 836                  'raw'      => array(
 837                      'description' => __( 'Caption for the attachment, as it exists in the database.' ),
 838                      'type'        => 'string',
 839                      'context'     => array( 'edit' ),
 840                  ),
 841                  'rendered' => array(
 842                      'description' => __( 'HTML caption for the attachment, transformed for display.' ),
 843                      'type'        => 'string',
 844                      'context'     => array( 'view', 'edit', 'embed' ),
 845                      'readonly'    => true,
 846                  ),
 847              ),
 848          );
 849  
 850          $schema['properties']['description'] = array(
 851              'description' => __( 'The attachment description.' ),
 852              'type'        => 'object',
 853              'context'     => array( 'view', 'edit' ),
 854              'arg_options' => array(
 855                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
 856                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
 857              ),
 858              'properties'  => array(
 859                  'raw'      => array(
 860                      'description' => __( 'Description for the object, as it exists in the database.' ),
 861                      'type'        => 'string',
 862                      'context'     => array( 'edit' ),
 863                  ),
 864                  'rendered' => array(
 865                      'description' => __( 'HTML description for the object, transformed for display.' ),
 866                      'type'        => 'string',
 867                      'context'     => array( 'view', 'edit' ),
 868                      'readonly'    => true,
 869                  ),
 870              ),
 871          );
 872  
 873          $schema['properties']['media_type'] = array(
 874              'description' => __( 'Attachment type.' ),
 875              'type'        => 'string',
 876              'enum'        => array( 'image', 'file' ),
 877              'context'     => array( 'view', 'edit', 'embed' ),
 878              'readonly'    => true,
 879          );
 880  
 881          $schema['properties']['mime_type'] = array(
 882              'description' => __( 'The attachment MIME type.' ),
 883              'type'        => 'string',
 884              'context'     => array( 'view', 'edit', 'embed' ),
 885              'readonly'    => true,
 886          );
 887  
 888          $schema['properties']['media_details'] = array(
 889              'description' => __( 'Details about the media file, specific to its type.' ),
 890              'type'        => 'object',
 891              'context'     => array( 'view', 'edit', 'embed' ),
 892              'readonly'    => true,
 893          );
 894  
 895          $schema['properties']['post'] = array(
 896              'description' => __( 'The ID for the associated post of the attachment.' ),
 897              'type'        => 'integer',
 898              'context'     => array( 'view', 'edit' ),
 899          );
 900  
 901          $schema['properties']['source_url'] = array(
 902              'description' => __( 'URL to the original attachment file.' ),
 903              'type'        => 'string',
 904              'format'      => 'uri',
 905              'context'     => array( 'view', 'edit', 'embed' ),
 906              'readonly'    => true,
 907          );
 908  
 909          $schema['properties']['missing_image_sizes'] = array(
 910              'description' => __( 'List of the missing image sizes of the attachment.' ),
 911              'type'        => 'array',
 912              'items'       => array( 'type' => 'string' ),
 913              'context'     => array( 'edit' ),
 914              'readonly'    => true,
 915          );
 916  
 917          unset( $schema['properties']['password'] );
 918  
 919          $this->schema = $schema;
 920  
 921          return $this->add_additional_fields_schema( $this->schema );
 922      }
 923  
 924      /**
 925       * Handles an upload via raw POST data.
 926       *
 927       * @since 4.7.0
 928       *
 929       * @param array $data    Supplied file data.
 930       * @param array $headers HTTP headers from the request.
 931       * @return array|WP_Error Data from wp_handle_sideload().
 932       */
 933  	protected function upload_from_data( $data, $headers ) {
 934          if ( empty( $data ) ) {
 935              return new WP_Error(
 936                  'rest_upload_no_data',
 937                  __( 'No data supplied.' ),
 938                  array( 'status' => 400 )
 939              );
 940          }
 941  
 942          if ( empty( $headers['content_type'] ) ) {
 943              return new WP_Error(
 944                  'rest_upload_no_content_type',
 945                  __( 'No Content-Type supplied.' ),
 946                  array( 'status' => 400 )
 947              );
 948          }
 949  
 950          if ( empty( $headers['content_disposition'] ) ) {
 951              return new WP_Error(
 952                  'rest_upload_no_content_disposition',
 953                  __( 'No Content-Disposition supplied.' ),
 954                  array( 'status' => 400 )
 955              );
 956          }
 957  
 958          $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
 959  
 960          if ( empty( $filename ) ) {
 961              return new WP_Error(
 962                  'rest_upload_invalid_disposition',
 963                  __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ),
 964                  array( 'status' => 400 )
 965              );
 966          }
 967  
 968          if ( ! empty( $headers['content_md5'] ) ) {
 969              $content_md5 = array_shift( $headers['content_md5'] );
 970              $expected    = trim( $content_md5 );
 971              $actual      = md5( $data );
 972  
 973              if ( $expected !== $actual ) {
 974                  return new WP_Error(
 975                      'rest_upload_hash_mismatch',
 976                      __( 'Content hash did not match expected.' ),
 977                      array( 'status' => 412 )
 978                  );
 979              }
 980          }
 981  
 982          // Get the content-type.
 983          $type = array_shift( $headers['content_type'] );
 984  
 985          // Include filesystem functions to get access to wp_tempnam() and wp_handle_sideload().
 986          require_once ABSPATH . 'wp-admin/includes/file.php';
 987  
 988          // Save the file.
 989          $tmpfname = wp_tempnam( $filename );
 990  
 991          $fp = fopen( $tmpfname, 'w+' );
 992  
 993          if ( ! $fp ) {
 994              return new WP_Error(
 995                  'rest_upload_file_error',
 996                  __( 'Could not open file handle.' ),
 997                  array( 'status' => 500 )
 998              );
 999          }
1000  
1001          fwrite( $fp, $data );
1002          fclose( $fp );
1003  
1004          // Now, sideload it in.
1005          $file_data = array(
1006              'error'    => null,
1007              'tmp_name' => $tmpfname,
1008              'name'     => $filename,
1009              'type'     => $type,
1010          );
1011  
1012          $size_check = self::check_upload_size( $file_data );
1013          if ( is_wp_error( $size_check ) ) {
1014              return $size_check;
1015          }
1016  
1017          $overrides = array(
1018              'test_form' => false,
1019          );
1020  
1021          $sideloaded = wp_handle_sideload( $file_data, $overrides );
1022  
1023          if ( isset( $sideloaded['error'] ) ) {
1024              @unlink( $tmpfname );
1025  
1026              return new WP_Error(
1027                  'rest_upload_sideload_error',
1028                  $sideloaded['error'],
1029                  array( 'status' => 500 )
1030              );
1031          }
1032  
1033          return $sideloaded;
1034      }
1035  
1036      /**
1037       * Parses filename from a Content-Disposition header value.
1038       *
1039       * As per RFC6266:
1040       *
1041       *     content-disposition = "Content-Disposition" ":"
1042       *                            disposition-type *( ";" disposition-parm )
1043       *
1044       *     disposition-type    = "inline" | "attachment" | disp-ext-type
1045       *                         ; case-insensitive
1046       *     disp-ext-type       = token
1047       *
1048       *     disposition-parm    = filename-parm | disp-ext-parm
1049       *
1050       *     filename-parm       = "filename" "=" value
1051       *                         | "filename*" "=" ext-value
1052       *
1053       *     disp-ext-parm       = token "=" value
1054       *                         | ext-token "=" ext-value
1055       *     ext-token           = <the characters in token, followed by "*">
1056       *
1057       * @since 4.7.0
1058       *
1059       * @link https://tools.ietf.org/html/rfc2388
1060       * @link https://tools.ietf.org/html/rfc6266
1061       *
1062       * @param string[] $disposition_header List of Content-Disposition header values.
1063       * @return string|null Filename if available, or null if not found.
1064       */
1065  	public static function get_filename_from_disposition( $disposition_header ) {
1066          // Get the filename.
1067          $filename = null;
1068  
1069          foreach ( $disposition_header as $value ) {
1070              $value = trim( $value );
1071  
1072              if ( strpos( $value, ';' ) === false ) {
1073                  continue;
1074              }
1075  
1076              list( $type, $attr_parts ) = explode( ';', $value, 2 );
1077  
1078              $attr_parts = explode( ';', $attr_parts );
1079              $attributes = array();
1080  
1081              foreach ( $attr_parts as $part ) {
1082                  if ( strpos( $part, '=' ) === false ) {
1083                      continue;
1084                  }
1085  
1086                  list( $key, $value ) = explode( '=', $part, 2 );
1087  
1088                  $attributes[ trim( $key ) ] = trim( $value );
1089              }
1090  
1091              if ( empty( $attributes['filename'] ) ) {
1092                  continue;
1093              }
1094  
1095              $filename = trim( $attributes['filename'] );
1096  
1097              // Unquote quoted filename, but after trimming.
1098              if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
1099                  $filename = substr( $filename, 1, -1 );
1100              }
1101          }
1102  
1103          return $filename;
1104      }
1105  
1106      /**
1107       * Retrieves the query params for collections of attachments.
1108       *
1109       * @since 4.7.0
1110       *
1111       * @return array Query parameters for the attachment collection as an array.
1112       */
1113  	public function get_collection_params() {
1114          $params                            = parent::get_collection_params();
1115          $params['status']['default']       = 'inherit';
1116          $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
1117          $media_types                       = $this->get_media_types();
1118  
1119          $params['media_type'] = array(
1120              'default'     => null,
1121              'description' => __( 'Limit result set to attachments of a particular media type.' ),
1122              'type'        => 'string',
1123              'enum'        => array_keys( $media_types ),
1124          );
1125  
1126          $params['mime_type'] = array(
1127              'default'     => null,
1128              'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
1129              'type'        => 'string',
1130          );
1131  
1132          return $params;
1133      }
1134  
1135      /**
1136       * Handles an upload via multipart/form-data ($_FILES).
1137       *
1138       * @since 4.7.0
1139       *
1140       * @param array $files   Data from the `$_FILES` superglobal.
1141       * @param array $headers HTTP headers from the request.
1142       * @return array|WP_Error Data from wp_handle_upload().
1143       */
1144  	protected function upload_from_file( $files, $headers ) {
1145          if ( empty( $files ) ) {
1146              return new WP_Error(
1147                  'rest_upload_no_data',
1148                  __( 'No data supplied.' ),
1149                  array( 'status' => 400 )
1150              );
1151          }
1152  
1153          // Verify hash, if given.
1154          if ( ! empty( $headers['content_md5'] ) ) {
1155              $content_md5 = array_shift( $headers['content_md5'] );
1156              $expected    = trim( $content_md5 );
1157              $actual      = md5_file( $files['file']['tmp_name'] );
1158  
1159              if ( $expected !== $actual ) {
1160                  return new WP_Error(
1161                      'rest_upload_hash_mismatch',
1162                      __( 'Content hash did not match expected.' ),
1163                      array( 'status' => 412 )
1164                  );
1165              }
1166          }
1167  
1168          // Pass off to WP to handle the actual upload.
1169          $overrides = array(
1170              'test_form' => false,
1171          );
1172  
1173          // Bypasses is_uploaded_file() when running unit tests.
1174          if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
1175              $overrides['action'] = 'wp_handle_mock_upload';
1176          }
1177  
1178          $size_check = self::check_upload_size( $files['file'] );
1179          if ( is_wp_error( $size_check ) ) {
1180              return $size_check;
1181          }
1182  
1183          // Include filesystem functions to get access to wp_handle_upload().
1184          require_once ABSPATH . 'wp-admin/includes/file.php';
1185  
1186          $file = wp_handle_upload( $files['file'], $overrides );
1187  
1188          if ( isset( $file['error'] ) ) {
1189              return new WP_Error(
1190                  'rest_upload_unknown_error',
1191                  $file['error'],
1192                  array( 'status' => 500 )
1193              );
1194          }
1195  
1196          return $file;
1197      }
1198  
1199      /**
1200       * Retrieves the supported media types.
1201       *
1202       * Media types are considered the MIME type category.
1203       *
1204       * @since 4.7.0
1205       *
1206       * @return array Array of supported media types.
1207       */
1208  	protected function get_media_types() {
1209          $media_types = array();
1210  
1211          foreach ( get_allowed_mime_types() as $mime_type ) {
1212              $parts = explode( '/', $mime_type );
1213  
1214              if ( ! isset( $media_types[ $parts[0] ] ) ) {
1215                  $media_types[ $parts[0] ] = array();
1216              }
1217  
1218              $media_types[ $parts[0] ][] = $mime_type;
1219          }
1220  
1221          return $media_types;
1222      }
1223  
1224      /**
1225       * Determine if uploaded file exceeds space quota on multisite.
1226       *
1227       * Replicates check_upload_size().
1228       *
1229       * @since 4.9.8
1230       *
1231       * @param array $file $_FILES array for a given file.
1232       * @return true|WP_Error True if can upload, error for errors.
1233       */
1234  	protected function check_upload_size( $file ) {
1235          if ( ! is_multisite() ) {
1236              return true;
1237          }
1238  
1239          if ( get_site_option( 'upload_space_check_disabled' ) ) {
1240              return true;
1241          }
1242  
1243          $space_left = get_upload_space_available();
1244  
1245          $file_size = filesize( $file['tmp_name'] );
1246  
1247          if ( $space_left < $file_size ) {
1248              return new WP_Error(
1249                  'rest_upload_limited_space',
1250                  /* translators: %s: Required disk space in kilobytes. */
1251                  sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ),
1252                  array( 'status' => 400 )
1253              );
1254          }
1255  
1256          if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
1257              return new WP_Error(
1258                  'rest_upload_file_too_big',
1259                  /* translators: %s: Maximum allowed file size in kilobytes. */
1260                  sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ),
1261                  array( 'status' => 400 )
1262              );
1263          }
1264  
1265          // Include multisite admin functions to get access to upload_is_user_over_quota().
1266          require_once ABSPATH . 'wp-admin/includes/ms.php';
1267  
1268          if ( upload_is_user_over_quota( false ) ) {
1269              return new WP_Error(
1270                  'rest_upload_user_quota_exceeded',
1271                  __( 'You have used your space quota. Please delete files before uploading.' ),
1272                  array( 'status' => 400 )
1273              );
1274          }
1275  
1276          return true;
1277      }
1278  
1279      /**
1280       * Gets the request args for the edit item route.
1281       *
1282       * @since 5.5.0
1283       *
1284       * @return array
1285       */
1286  	protected function get_edit_media_item_args() {
1287          return array(
1288              'rotation' => array(
1289                  'description'      => __( 'The amount to rotate the image clockwise in degrees.' ),
1290                  'type'             => 'integer',
1291                  'minimum'          => 0,
1292                  'exclusiveMinimum' => true,
1293                  'maximum'          => 360,
1294                  'exclusiveMaximum' => true,
1295              ),
1296              'x'        => array(
1297                  'description' => __( 'As a percentage of the image, the x position to start the crop from.' ),
1298                  'type'        => 'number',
1299                  'minimum'     => 0,
1300                  'maximum'     => 100,
1301              ),
1302              'y'        => array(
1303                  'description' => __( 'As a percentage of the image, the y position to start the crop from.' ),
1304                  'type'        => 'number',
1305                  'minimum'     => 0,
1306                  'maximum'     => 100,
1307              ),
1308              'width'    => array(
1309                  'description' => __( 'As a percentage of the image, the width to crop the image to.' ),
1310                  'type'        => 'number',
1311                  'minimum'     => 0,
1312                  'maximum'     => 100,
1313              ),
1314              'height'   => array(
1315                  'description' => __( 'As a percentage of the image, the height to crop the image to.' ),
1316                  'type'        => 'number',
1317                  'minimum'     => 0,
1318                  'maximum'     => 100,
1319              ),
1320              'src'      => array(
1321                  'description' => __( 'URL to the edited image file.' ),
1322                  'type'        => 'string',
1323                  'format'      => 'uri',
1324                  'required'    => true,
1325              ),
1326          );
1327      }
1328  
1329  }


Generated: Mon Oct 26 01:00:02 2020 Cross-referenced by PHPXref 0.7.1