[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7