[ 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      }
  49  
  50      /**
  51       * Determines the allowed query_vars for a get_items() response and
  52       * prepares for WP_Query.
  53       *
  54       * @since 4.7.0
  55       *
  56       * @param array           $prepared_args Optional. Array of prepared arguments. Default empty array.
  57       * @param WP_REST_Request $request       Optional. Request to prepare items for.
  58       * @return array Array of query arguments.
  59       */
  60  	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
  61          $query_args = parent::prepare_items_query( $prepared_args, $request );
  62  
  63          if ( empty( $query_args['post_status'] ) ) {
  64              $query_args['post_status'] = 'inherit';
  65          }
  66  
  67          $media_types = $this->get_media_types();
  68  
  69          if ( ! empty( $request['media_type'] ) && isset( $media_types[ $request['media_type'] ] ) ) {
  70              $query_args['post_mime_type'] = $media_types[ $request['media_type'] ];
  71          }
  72  
  73          if ( ! empty( $request['mime_type'] ) ) {
  74              $parts = explode( '/', $request['mime_type'] );
  75              if ( isset( $media_types[ $parts[0] ] ) && in_array( $request['mime_type'], $media_types[ $parts[0] ], true ) ) {
  76                  $query_args['post_mime_type'] = $request['mime_type'];
  77              }
  78          }
  79  
  80          // Filter query clauses to include filenames.
  81          if ( isset( $query_args['s'] ) ) {
  82              add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
  83          }
  84  
  85          return $query_args;
  86      }
  87  
  88      /**
  89       * Checks if a given request has access to create an attachment.
  90       *
  91       * @since 4.7.0
  92       *
  93       * @param WP_REST_Request $request Full details about the request.
  94       * @return true|WP_Error Boolean true if the attachment may be created, or a WP_Error if not.
  95       */
  96  	public function create_item_permissions_check( $request ) {
  97          $ret = parent::create_item_permissions_check( $request );
  98  
  99          if ( ! $ret || is_wp_error( $ret ) ) {
 100              return $ret;
 101          }
 102  
 103          if ( ! current_user_can( 'upload_files' ) ) {
 104              return new WP_Error(
 105                  'rest_cannot_create',
 106                  __( 'Sorry, you are not allowed to upload media on this site.' ),
 107                  array( 'status' => 400 )
 108              );
 109          }
 110  
 111          // Attaching media to a post requires ability to edit said post.
 112          if ( ! empty( $request['post'] ) ) {
 113              $parent           = get_post( (int) $request['post'] );
 114              $post_parent_type = get_post_type_object( $parent->post_type );
 115  
 116              if ( ! current_user_can( $post_parent_type->cap->edit_post, $request['post'] ) ) {
 117                  return new WP_Error(
 118                      'rest_cannot_edit',
 119                      __( 'Sorry, you are not allowed to upload media to this post.' ),
 120                      array( 'status' => rest_authorization_required_code() )
 121                  );
 122              }
 123          }
 124  
 125          return true;
 126      }
 127  
 128      /**
 129       * Creates a single attachment.
 130       *
 131       * @since 4.7.0
 132       *
 133       * @param WP_REST_Request $request Full details about the request.
 134       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 135       */
 136  	public function create_item( $request ) {
 137          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 138              return new WP_Error(
 139                  'rest_invalid_param',
 140                  __( 'Invalid parent type.' ),
 141                  array( 'status' => 400 )
 142              );
 143          }
 144  
 145          $insert = $this->insert_attachment( $request );
 146  
 147          if ( is_wp_error( $insert ) ) {
 148              return $insert;
 149          }
 150  
 151          $schema = $this->get_item_schema();
 152  
 153          // Extract by name.
 154          $attachment_id = $insert['attachment_id'];
 155          $file          = $insert['file'];
 156  
 157          if ( isset( $request['alt_text'] ) ) {
 158              update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
 159          }
 160  
 161          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
 162              $meta_update = $this->meta->update_value( $request['meta'], $attachment_id );
 163  
 164              if ( is_wp_error( $meta_update ) ) {
 165                  return $meta_update;
 166              }
 167          }
 168  
 169          $attachment    = get_post( $attachment_id );
 170          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 171  
 172          if ( is_wp_error( $fields_update ) ) {
 173              return $fields_update;
 174          }
 175  
 176          $request->set_param( 'context', 'edit' );
 177  
 178          /**
 179           * Fires after a single attachment is completely created or updated via the REST API.
 180           *
 181           * @since 5.0.0
 182           *
 183           * @param WP_Post         $attachment Inserted or updated attachment object.
 184           * @param WP_REST_Request $request    Request object.
 185           * @param bool            $creating   True when creating an attachment, false when updating.
 186           */
 187          do_action( 'rest_after_insert_attachment', $attachment, $request, true );
 188  
 189          if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
 190              // Set a custom header with the attachment_id.
 191              // Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
 192              header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id );
 193          }
 194  
 195          // Include media and image functions to get access to wp_generate_attachment_metadata().
 196          require_once ABSPATH . 'wp-admin/includes/media.php';
 197          require_once ABSPATH . 'wp-admin/includes/image.php';
 198  
 199          // Post-process the upload (create image sub-sizes, make PDF thumbnails, etc.) and insert attachment meta.
 200          // At this point the server may run out of resources and post-processing of uploaded images may fail.
 201          wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
 202  
 203          $response = $this->prepare_item_for_response( $attachment, $request );
 204          $response = rest_ensure_response( $response );
 205          $response->set_status( 201 );
 206          $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $attachment_id ) ) );
 207  
 208          return $response;
 209      }
 210  
 211      /**
 212       * Inserts the attachment post in the database. Does not update the attachment meta.
 213       *
 214       * @since 5.3.0
 215       *
 216       * @param WP_REST_Request $request
 217       * @return array|WP_Error
 218       */
 219  	protected function insert_attachment( $request ) {
 220          // Get the file via $_FILES or raw data.
 221          $files   = $request->get_file_params();
 222          $headers = $request->get_headers();
 223  
 224          if ( ! empty( $files ) ) {
 225              $file = $this->upload_from_file( $files, $headers );
 226          } else {
 227              $file = $this->upload_from_data( $request->get_body(), $headers );
 228          }
 229  
 230          if ( is_wp_error( $file ) ) {
 231              return $file;
 232          }
 233  
 234          $name       = wp_basename( $file['file'] );
 235          $name_parts = pathinfo( $name );
 236          $name       = trim( substr( $name, 0, -( 1 + strlen( $name_parts['extension'] ) ) ) );
 237  
 238          $url  = $file['url'];
 239          $type = $file['type'];
 240          $file = $file['file'];
 241  
 242          // Include image functions to get access to wp_read_image_metadata().
 243          require_once ABSPATH . 'wp-admin/includes/image.php';
 244  
 245          // Use image exif/iptc data for title and caption defaults if possible.
 246          $image_meta = wp_read_image_metadata( $file );
 247  
 248          if ( ! empty( $image_meta ) ) {
 249              if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
 250                  $request['title'] = $image_meta['title'];
 251              }
 252  
 253              if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
 254                  $request['caption'] = $image_meta['caption'];
 255              }
 256          }
 257  
 258          $attachment = $this->prepare_item_for_database( $request );
 259  
 260          $attachment->post_mime_type = $type;
 261          $attachment->guid           = $url;
 262  
 263          if ( empty( $attachment->post_title ) ) {
 264              $attachment->post_title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) );
 265          }
 266  
 267          // $post_parent is inherited from $attachment['post_parent'].
 268          $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true );
 269  
 270          if ( is_wp_error( $id ) ) {
 271              if ( 'db_update_error' === $id->get_error_code() ) {
 272                  $id->add_data( array( 'status' => 500 ) );
 273              } else {
 274                  $id->add_data( array( 'status' => 400 ) );
 275              }
 276  
 277              return $id;
 278          }
 279  
 280          $attachment = get_post( $id );
 281  
 282          /**
 283           * Fires after a single attachment is created or updated via the REST API.
 284           *
 285           * @since 4.7.0
 286           *
 287           * @param WP_Post         $attachment Inserted or updated attachment
 288           *                                    object.
 289           * @param WP_REST_Request $request    The request sent to the API.
 290           * @param bool            $creating   True when creating an attachment, false when updating.
 291           */
 292          do_action( 'rest_insert_attachment', $attachment, $request, true );
 293  
 294          return array(
 295              'attachment_id' => $id,
 296              'file'          => $file,
 297          );
 298      }
 299  
 300      /**
 301       * Updates a single attachment.
 302       *
 303       * @since 4.7.0
 304       *
 305       * @param WP_REST_Request $request Full details about the request.
 306       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 307       */
 308  	public function update_item( $request ) {
 309          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 310              return new WP_Error(
 311                  'rest_invalid_param',
 312                  __( 'Invalid parent type.' ),
 313                  array( 'status' => 400 )
 314              );
 315          }
 316  
 317          $response = parent::update_item( $request );
 318  
 319          if ( is_wp_error( $response ) ) {
 320              return $response;
 321          }
 322  
 323          $response = rest_ensure_response( $response );
 324          $data     = $response->get_data();
 325  
 326          if ( isset( $request['alt_text'] ) ) {
 327              update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
 328          }
 329  
 330          $attachment = get_post( $request['id'] );
 331  
 332          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 333  
 334          if ( is_wp_error( $fields_update ) ) {
 335              return $fields_update;
 336          }
 337  
 338          $request->set_param( 'context', 'edit' );
 339  
 340          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
 341          do_action( 'rest_after_insert_attachment', $attachment, $request, false );
 342  
 343          $response = $this->prepare_item_for_response( $attachment, $request );
 344          $response = rest_ensure_response( $response );
 345  
 346          return $response;
 347      }
 348  
 349      /**
 350       * Performs post processing on an attachment.
 351       *
 352       * @since 5.3.0
 353       *
 354       * @param WP_REST_Request $request Full details about the request.
 355       * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure.
 356       */
 357  	public function post_process_item( $request ) {
 358          switch ( $request['action'] ) {
 359              case 'create-image-subsizes':
 360                  require_once ABSPATH . 'wp-admin/includes/image.php';
 361                  wp_update_image_subsizes( $request['id'] );
 362                  break;
 363          }
 364  
 365          $request['context'] = 'edit';
 366  
 367          return $this->prepare_item_for_response( get_post( $request['id'] ), $request );
 368      }
 369  
 370      /**
 371       * Checks if a given request can perform post processing on an attachment.
 372       *
 373       * @sicne 5.3.0
 374       *
 375       * @param WP_REST_Request $request Full details about the request.
 376       * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
 377       */
 378  	public function post_process_item_permissions_check( $request ) {
 379          return $this->update_item_permissions_check( $request );
 380      }
 381  
 382      /**
 383       * Prepares a single attachment for create or update.
 384       *
 385       * @since 4.7.0
 386       *
 387       * @param WP_REST_Request $request Request object.
 388       * @return stdClass|WP_Error Post object.
 389       */
 390  	protected function prepare_item_for_database( $request ) {
 391          $prepared_attachment = parent::prepare_item_for_database( $request );
 392  
 393          // Attachment caption (post_excerpt internally).
 394          if ( isset( $request['caption'] ) ) {
 395              if ( is_string( $request['caption'] ) ) {
 396                  $prepared_attachment->post_excerpt = $request['caption'];
 397              } elseif ( isset( $request['caption']['raw'] ) ) {
 398                  $prepared_attachment->post_excerpt = $request['caption']['raw'];
 399              }
 400          }
 401  
 402          // Attachment description (post_content internally).
 403          if ( isset( $request['description'] ) ) {
 404              if ( is_string( $request['description'] ) ) {
 405                  $prepared_attachment->post_content = $request['description'];
 406              } elseif ( isset( $request['description']['raw'] ) ) {
 407                  $prepared_attachment->post_content = $request['description']['raw'];
 408              }
 409          }
 410  
 411          if ( isset( $request['post'] ) ) {
 412              $prepared_attachment->post_parent = (int) $request['post'];
 413          }
 414  
 415          return $prepared_attachment;
 416      }
 417  
 418      /**
 419       * Prepares a single attachment output for response.
 420       *
 421       * @since 4.7.0
 422       *
 423       * @param WP_Post         $post    Attachment object.
 424       * @param WP_REST_Request $request Request object.
 425       * @return WP_REST_Response Response object.
 426       */
 427  	public function prepare_item_for_response( $post, $request ) {
 428          $response = parent::prepare_item_for_response( $post, $request );
 429          $fields   = $this->get_fields_for_response( $request );
 430          $data     = $response->get_data();
 431  
 432          if ( in_array( 'description', $fields, true ) ) {
 433              $data['description'] = array(
 434                  'raw'      => $post->post_content,
 435                  /** This filter is documented in wp-includes/post-template.php */
 436                  'rendered' => apply_filters( 'the_content', $post->post_content ),
 437              );
 438          }
 439  
 440          if ( in_array( 'caption', $fields, true ) ) {
 441              /** This filter is documented in wp-includes/post-template.php */
 442              $caption = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post );
 443  
 444              /** This filter is documented in wp-includes/post-template.php */
 445              $caption = apply_filters( 'the_excerpt', $caption );
 446  
 447              $data['caption'] = array(
 448                  'raw'      => $post->post_excerpt,
 449                  'rendered' => $caption,
 450              );
 451          }
 452  
 453          if ( in_array( 'alt_text', $fields, true ) ) {
 454              $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
 455          }
 456  
 457          if ( in_array( 'media_type', $fields, true ) ) {
 458              $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
 459          }
 460  
 461          if ( in_array( 'mime_type', $fields, true ) ) {
 462              $data['mime_type'] = $post->post_mime_type;
 463          }
 464  
 465          if ( in_array( 'media_details', $fields, true ) ) {
 466              $data['media_details'] = wp_get_attachment_metadata( $post->ID );
 467  
 468              // Ensure empty details is an empty object.
 469              if ( empty( $data['media_details'] ) ) {
 470                  $data['media_details'] = new stdClass;
 471              } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
 472  
 473                  foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
 474  
 475                      if ( isset( $size_data['mime-type'] ) ) {
 476                          $size_data['mime_type'] = $size_data['mime-type'];
 477                          unset( $size_data['mime-type'] );
 478                      }
 479  
 480                      // Use the same method image_downsize() does.
 481                      $image_src = wp_get_attachment_image_src( $post->ID, $size );
 482                      if ( ! $image_src ) {
 483                          continue;
 484                      }
 485  
 486                      $size_data['source_url'] = $image_src[0];
 487                  }
 488  
 489                  $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
 490  
 491                  if ( ! empty( $full_src ) ) {
 492                      $data['media_details']['sizes']['full'] = array(
 493                          'file'       => wp_basename( $full_src[0] ),
 494                          'width'      => $full_src[1],
 495                          'height'     => $full_src[2],
 496                          'mime_type'  => $post->post_mime_type,
 497                          'source_url' => $full_src[0],
 498                      );
 499                  }
 500              } else {
 501                  $data['media_details']['sizes'] = new stdClass;
 502              }
 503          }
 504  
 505          if ( in_array( 'post', $fields, true ) ) {
 506              $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
 507          }
 508  
 509          if ( in_array( 'source_url', $fields, true ) ) {
 510              $data['source_url'] = wp_get_attachment_url( $post->ID );
 511          }
 512  
 513          if ( in_array( 'missing_image_sizes', $fields, true ) ) {
 514              require_once ABSPATH . 'wp-admin/includes/image.php';
 515              $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) );
 516          }
 517  
 518          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
 519  
 520          $data = $this->filter_response_by_context( $data, $context );
 521  
 522          $links = $response->get_links();
 523  
 524          // Wrap the data in a response object.
 525          $response = rest_ensure_response( $data );
 526  
 527          foreach ( $links as $rel => $rel_links ) {
 528              foreach ( $rel_links as $link ) {
 529                  $response->add_link( $rel, $link['href'], $link['attributes'] );
 530              }
 531          }
 532  
 533          /**
 534           * Filters an attachment returned from the REST API.
 535           *
 536           * Allows modification of the attachment right before it is returned.
 537           *
 538           * @since 4.7.0
 539           *
 540           * @param WP_REST_Response $response The response object.
 541           * @param WP_Post          $post     The original attachment post.
 542           * @param WP_REST_Request  $request  Request used to generate the response.
 543           */
 544          return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
 545      }
 546  
 547      /**
 548       * Retrieves the attachment's schema, conforming to JSON Schema.
 549       *
 550       * @since 4.7.0
 551       *
 552       * @return array Item schema as an array.
 553       */
 554  	public function get_item_schema() {
 555          if ( $this->schema ) {
 556              return $this->add_additional_fields_schema( $this->schema );
 557          }
 558  
 559          $schema = parent::get_item_schema();
 560  
 561          $schema['properties']['alt_text'] = array(
 562              'description' => __( 'Alternative text to display when attachment is not displayed.' ),
 563              'type'        => 'string',
 564              'context'     => array( 'view', 'edit', 'embed' ),
 565              'arg_options' => array(
 566                  'sanitize_callback' => 'sanitize_text_field',
 567              ),
 568          );
 569  
 570          $schema['properties']['caption'] = array(
 571              'description' => __( 'The attachment caption.' ),
 572              'type'        => 'object',
 573              'context'     => array( 'view', 'edit', 'embed' ),
 574              'arg_options' => array(
 575                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
 576                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
 577              ),
 578              'properties'  => array(
 579                  'raw'      => array(
 580                      'description' => __( 'Caption for the attachment, as it exists in the database.' ),
 581                      'type'        => 'string',
 582                      'context'     => array( 'edit' ),
 583                  ),
 584                  'rendered' => array(
 585                      'description' => __( 'HTML caption for the attachment, transformed for display.' ),
 586                      'type'        => 'string',
 587                      'context'     => array( 'view', 'edit', 'embed' ),
 588                      'readonly'    => true,
 589                  ),
 590              ),
 591          );
 592  
 593          $schema['properties']['description'] = array(
 594              'description' => __( 'The attachment description.' ),
 595              'type'        => 'object',
 596              'context'     => array( 'view', 'edit' ),
 597              'arg_options' => array(
 598                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
 599                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
 600              ),
 601              'properties'  => array(
 602                  'raw'      => array(
 603                      'description' => __( 'Description for the object, as it exists in the database.' ),
 604                      'type'        => 'string',
 605                      'context'     => array( 'edit' ),
 606                  ),
 607                  'rendered' => array(
 608                      'description' => __( 'HTML description for the object, transformed for display.' ),
 609                      'type'        => 'string',
 610                      'context'     => array( 'view', 'edit' ),
 611                      'readonly'    => true,
 612                  ),
 613              ),
 614          );
 615  
 616          $schema['properties']['media_type'] = array(
 617              'description' => __( 'Attachment type.' ),
 618              'type'        => 'string',
 619              'enum'        => array( 'image', 'file' ),
 620              'context'     => array( 'view', 'edit', 'embed' ),
 621              'readonly'    => true,
 622          );
 623  
 624          $schema['properties']['mime_type'] = array(
 625              'description' => __( 'The attachment MIME type.' ),
 626              'type'        => 'string',
 627              'context'     => array( 'view', 'edit', 'embed' ),
 628              'readonly'    => true,
 629          );
 630  
 631          $schema['properties']['media_details'] = array(
 632              'description' => __( 'Details about the media file, specific to its type.' ),
 633              'type'        => 'object',
 634              'context'     => array( 'view', 'edit', 'embed' ),
 635              'readonly'    => true,
 636          );
 637  
 638          $schema['properties']['post'] = array(
 639              'description' => __( 'The ID for the associated post of the attachment.' ),
 640              'type'        => 'integer',
 641              'context'     => array( 'view', 'edit' ),
 642          );
 643  
 644          $schema['properties']['source_url'] = array(
 645              'description' => __( 'URL to the original attachment file.' ),
 646              'type'        => 'string',
 647              'format'      => 'uri',
 648              'context'     => array( 'view', 'edit', 'embed' ),
 649              'readonly'    => true,
 650          );
 651  
 652          $schema['properties']['missing_image_sizes'] = array(
 653              'description' => __( 'List of the missing image sizes of the attachment.' ),
 654              'type'        => 'array',
 655              'items'       => array( 'type' => 'string' ),
 656              'context'     => array( 'edit' ),
 657              'readonly'    => true,
 658          );
 659  
 660          unset( $schema['properties']['password'] );
 661  
 662          $this->schema = $schema;
 663  
 664          return $this->add_additional_fields_schema( $this->schema );
 665      }
 666  
 667      /**
 668       * Handles an upload via raw POST data.
 669       *
 670       * @since 4.7.0
 671       *
 672       * @param array $data    Supplied file data.
 673       * @param array $headers HTTP headers from the request.
 674       * @return array|WP_Error Data from wp_handle_sideload().
 675       */
 676  	protected function upload_from_data( $data, $headers ) {
 677          if ( empty( $data ) ) {
 678              return new WP_Error(
 679                  'rest_upload_no_data',
 680                  __( 'No data supplied.' ),
 681                  array( 'status' => 400 )
 682              );
 683          }
 684  
 685          if ( empty( $headers['content_type'] ) ) {
 686              return new WP_Error(
 687                  'rest_upload_no_content_type',
 688                  __( 'No Content-Type supplied.' ),
 689                  array( 'status' => 400 )
 690              );
 691          }
 692  
 693          if ( empty( $headers['content_disposition'] ) ) {
 694              return new WP_Error(
 695                  'rest_upload_no_content_disposition',
 696                  __( 'No Content-Disposition supplied.' ),
 697                  array( 'status' => 400 )
 698              );
 699          }
 700  
 701          $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
 702  
 703          if ( empty( $filename ) ) {
 704              return new WP_Error(
 705                  'rest_upload_invalid_disposition',
 706                  __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ),
 707                  array( 'status' => 400 )
 708              );
 709          }
 710  
 711          if ( ! empty( $headers['content_md5'] ) ) {
 712              $content_md5 = array_shift( $headers['content_md5'] );
 713              $expected    = trim( $content_md5 );
 714              $actual      = md5( $data );
 715  
 716              if ( $expected !== $actual ) {
 717                  return new WP_Error(
 718                      'rest_upload_hash_mismatch',
 719                      __( 'Content hash did not match expected.' ),
 720                      array( 'status' => 412 )
 721                  );
 722              }
 723          }
 724  
 725          // Get the content-type.
 726          $type = array_shift( $headers['content_type'] );
 727  
 728          // Include filesystem functions to get access to wp_tempnam() and wp_handle_sideload().
 729          require_once ABSPATH . 'wp-admin/includes/file.php';
 730  
 731          // Save the file.
 732          $tmpfname = wp_tempnam( $filename );
 733  
 734          $fp = fopen( $tmpfname, 'w+' );
 735  
 736          if ( ! $fp ) {
 737              return new WP_Error(
 738                  'rest_upload_file_error',
 739                  __( 'Could not open file handle.' ),
 740                  array( 'status' => 500 )
 741              );
 742          }
 743  
 744          fwrite( $fp, $data );
 745          fclose( $fp );
 746  
 747          // Now, sideload it in.
 748          $file_data = array(
 749              'error'    => null,
 750              'tmp_name' => $tmpfname,
 751              'name'     => $filename,
 752              'type'     => $type,
 753          );
 754  
 755          $size_check = self::check_upload_size( $file_data );
 756          if ( is_wp_error( $size_check ) ) {
 757              return $size_check;
 758          }
 759  
 760          $overrides = array(
 761              'test_form' => false,
 762          );
 763  
 764          $sideloaded = wp_handle_sideload( $file_data, $overrides );
 765  
 766          if ( isset( $sideloaded['error'] ) ) {
 767              @unlink( $tmpfname );
 768  
 769              return new WP_Error(
 770                  'rest_upload_sideload_error',
 771                  $sideloaded['error'],
 772                  array( 'status' => 500 )
 773              );
 774          }
 775  
 776          return $sideloaded;
 777      }
 778  
 779      /**
 780       * Parses filename from a Content-Disposition header value.
 781       *
 782       * As per RFC6266:
 783       *
 784       *     content-disposition = "Content-Disposition" ":"
 785       *                            disposition-type *( ";" disposition-parm )
 786       *
 787       *     disposition-type    = "inline" | "attachment" | disp-ext-type
 788       *                         ; case-insensitive
 789       *     disp-ext-type       = token
 790       *
 791       *     disposition-parm    = filename-parm | disp-ext-parm
 792       *
 793       *     filename-parm       = "filename" "=" value
 794       *                         | "filename*" "=" ext-value
 795       *
 796       *     disp-ext-parm       = token "=" value
 797       *                         | ext-token "=" ext-value
 798       *     ext-token           = <the characters in token, followed by "*">
 799       *
 800       * @since 4.7.0
 801       *
 802       * @link https://tools.ietf.org/html/rfc2388
 803       * @link https://tools.ietf.org/html/rfc6266
 804       *
 805       * @param string[] $disposition_header List of Content-Disposition header values.
 806       * @return string|null Filename if available, or null if not found.
 807       */
 808  	public static function get_filename_from_disposition( $disposition_header ) {
 809          // Get the filename.
 810          $filename = null;
 811  
 812          foreach ( $disposition_header as $value ) {
 813              $value = trim( $value );
 814  
 815              if ( strpos( $value, ';' ) === false ) {
 816                  continue;
 817              }
 818  
 819              list( $type, $attr_parts ) = explode( ';', $value, 2 );
 820  
 821              $attr_parts = explode( ';', $attr_parts );
 822              $attributes = array();
 823  
 824              foreach ( $attr_parts as $part ) {
 825                  if ( strpos( $part, '=' ) === false ) {
 826                      continue;
 827                  }
 828  
 829                  list( $key, $value ) = explode( '=', $part, 2 );
 830  
 831                  $attributes[ trim( $key ) ] = trim( $value );
 832              }
 833  
 834              if ( empty( $attributes['filename'] ) ) {
 835                  continue;
 836              }
 837  
 838              $filename = trim( $attributes['filename'] );
 839  
 840              // Unquote quoted filename, but after trimming.
 841              if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
 842                  $filename = substr( $filename, 1, -1 );
 843              }
 844          }
 845  
 846          return $filename;
 847      }
 848  
 849      /**
 850       * Retrieves the query params for collections of attachments.
 851       *
 852       * @since 4.7.0
 853       *
 854       * @return array Query parameters for the attachment collection as an array.
 855       */
 856  	public function get_collection_params() {
 857          $params                            = parent::get_collection_params();
 858          $params['status']['default']       = 'inherit';
 859          $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
 860          $media_types                       = $this->get_media_types();
 861  
 862          $params['media_type'] = array(
 863              'default'     => null,
 864              'description' => __( 'Limit result set to attachments of a particular media type.' ),
 865              'type'        => 'string',
 866              'enum'        => array_keys( $media_types ),
 867          );
 868  
 869          $params['mime_type'] = array(
 870              'default'     => null,
 871              'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
 872              'type'        => 'string',
 873          );
 874  
 875          return $params;
 876      }
 877  
 878      /**
 879       * Handles an upload via multipart/form-data ($_FILES).
 880       *
 881       * @since 4.7.0
 882       *
 883       * @param array $files   Data from the `$_FILES` superglobal.
 884       * @param array $headers HTTP headers from the request.
 885       * @return array|WP_Error Data from wp_handle_upload().
 886       */
 887  	protected function upload_from_file( $files, $headers ) {
 888          if ( empty( $files ) ) {
 889              return new WP_Error(
 890                  'rest_upload_no_data',
 891                  __( 'No data supplied.' ),
 892                  array( 'status' => 400 )
 893              );
 894          }
 895  
 896          // Verify hash, if given.
 897          if ( ! empty( $headers['content_md5'] ) ) {
 898              $content_md5 = array_shift( $headers['content_md5'] );
 899              $expected    = trim( $content_md5 );
 900              $actual      = md5_file( $files['file']['tmp_name'] );
 901  
 902              if ( $expected !== $actual ) {
 903                  return new WP_Error(
 904                      'rest_upload_hash_mismatch',
 905                      __( 'Content hash did not match expected.' ),
 906                      array( 'status' => 412 )
 907                  );
 908              }
 909          }
 910  
 911          // Pass off to WP to handle the actual upload.
 912          $overrides = array(
 913              'test_form' => false,
 914          );
 915  
 916          // Bypasses is_uploaded_file() when running unit tests.
 917          if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
 918              $overrides['action'] = 'wp_handle_mock_upload';
 919          }
 920  
 921          $size_check = self::check_upload_size( $files['file'] );
 922          if ( is_wp_error( $size_check ) ) {
 923              return $size_check;
 924          }
 925  
 926          // Include filesystem functions to get access to wp_handle_upload().
 927          require_once ABSPATH . 'wp-admin/includes/file.php';
 928  
 929          $file = wp_handle_upload( $files['file'], $overrides );
 930  
 931          if ( isset( $file['error'] ) ) {
 932              return new WP_Error(
 933                  'rest_upload_unknown_error',
 934                  $file['error'],
 935                  array( 'status' => 500 )
 936              );
 937          }
 938  
 939          return $file;
 940      }
 941  
 942      /**
 943       * Retrieves the supported media types.
 944       *
 945       * Media types are considered the MIME type category.
 946       *
 947       * @since 4.7.0
 948       *
 949       * @return array Array of supported media types.
 950       */
 951  	protected function get_media_types() {
 952          $media_types = array();
 953  
 954          foreach ( get_allowed_mime_types() as $mime_type ) {
 955              $parts = explode( '/', $mime_type );
 956  
 957              if ( ! isset( $media_types[ $parts[0] ] ) ) {
 958                  $media_types[ $parts[0] ] = array();
 959              }
 960  
 961              $media_types[ $parts[0] ][] = $mime_type;
 962          }
 963  
 964          return $media_types;
 965      }
 966  
 967      /**
 968       * Determine if uploaded file exceeds space quota on multisite.
 969       *
 970       * Replicates check_upload_size().
 971       *
 972       * @since 4.9.8
 973       *
 974       * @param array $file $_FILES array for a given file.
 975       * @return true|WP_Error True if can upload, error for errors.
 976       */
 977  	protected function check_upload_size( $file ) {
 978          if ( ! is_multisite() ) {
 979              return true;
 980          }
 981  
 982          if ( get_site_option( 'upload_space_check_disabled' ) ) {
 983              return true;
 984          }
 985  
 986          $space_left = get_upload_space_available();
 987  
 988          $file_size = filesize( $file['tmp_name'] );
 989  
 990          if ( $space_left < $file_size ) {
 991              return new WP_Error(
 992                  'rest_upload_limited_space',
 993                  /* translators: %s: Required disk space in kilobytes. */
 994                  sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ),
 995                  array( 'status' => 400 )
 996              );
 997          }
 998  
 999          if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
1000              return new WP_Error(
1001                  'rest_upload_file_too_big',
1002                  /* translators: %s: Maximum allowed file size in kilobytes. */
1003                  sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ),
1004                  array( 'status' => 400 )
1005              );
1006          }
1007  
1008          // Include multisite admin functions to get access to upload_is_user_over_quota().
1009          require_once ABSPATH . 'wp-admin/includes/ms.php';
1010  
1011          if ( upload_is_user_over_quota( false ) ) {
1012              return new WP_Error(
1013                  'rest_upload_user_quota_exceeded',
1014                  __( 'You have used your space quota. Please delete files before uploading.' ),
1015                  array( 'status' => 400 )
1016              );
1017          }
1018  
1019          return true;
1020      }
1021  
1022  }


Generated: Sat Feb 29 01:00:03 2020 Cross-referenced by PHPXref 0.7.1