[ 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  	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 true|WP_Error 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_REST_Response|WP_Error 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_REST_Response|WP_Error 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 stdClass|WP_Error 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( 'get_the_excerpt', $post->post_excerpt, $post );
 410  
 411              /** This filter is documented in wp-includes/post-template.php */
 412              $caption = apply_filters( 'the_excerpt', $caption );
 413  
 414              $data['caption'] = array(
 415                  'raw'      => $post->post_excerpt,
 416                  'rendered' => $caption,
 417              );
 418          }
 419  
 420          if ( in_array( 'alt_text', $fields, true ) ) {
 421              $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
 422          }
 423  
 424          if ( in_array( 'media_type', $fields, true ) ) {
 425              $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
 426          }
 427  
 428          if ( in_array( 'mime_type', $fields, true ) ) {
 429              $data['mime_type'] = $post->post_mime_type;
 430          }
 431  
 432          if ( in_array( 'media_details', $fields, true ) ) {
 433              $data['media_details'] = wp_get_attachment_metadata( $post->ID );
 434  
 435              // Ensure empty details is an empty object.
 436              if ( empty( $data['media_details'] ) ) {
 437                  $data['media_details'] = new stdClass;
 438              } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
 439  
 440                  foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
 441  
 442                      if ( isset( $size_data['mime-type'] ) ) {
 443                          $size_data['mime_type'] = $size_data['mime-type'];
 444                          unset( $size_data['mime-type'] );
 445                      }
 446  
 447                      // Use the same method image_downsize() does.
 448                      $image_src = wp_get_attachment_image_src( $post->ID, $size );
 449                      if ( ! $image_src ) {
 450                          continue;
 451                      }
 452  
 453                      $size_data['source_url'] = $image_src[0];
 454                  }
 455  
 456                  $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
 457  
 458                  if ( ! empty( $full_src ) ) {
 459                      $data['media_details']['sizes']['full'] = array(
 460                          'file'       => wp_basename( $full_src[0] ),
 461                          'width'      => $full_src[1],
 462                          'height'     => $full_src[2],
 463                          'mime_type'  => $post->post_mime_type,
 464                          'source_url' => $full_src[0],
 465                      );
 466                  }
 467              } else {
 468                  $data['media_details']['sizes'] = new stdClass;
 469              }
 470          }
 471  
 472          if ( in_array( 'post', $fields, true ) ) {
 473              $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
 474          }
 475  
 476          if ( in_array( 'source_url', $fields, true ) ) {
 477              $data['source_url'] = wp_get_attachment_url( $post->ID );
 478          }
 479  
 480          if ( in_array( 'missing_image_sizes', $fields, true ) ) {
 481              require_once ABSPATH . 'wp-admin/includes/image.php';
 482              $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) );
 483          }
 484  
 485          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
 486  
 487          $data = $this->filter_response_by_context( $data, $context );
 488  
 489          $links = $response->get_links();
 490  
 491          // Wrap the data in a response object.
 492          $response = rest_ensure_response( $data );
 493  
 494          foreach ( $links as $rel => $rel_links ) {
 495              foreach ( $rel_links as $link ) {
 496                  $response->add_link( $rel, $link['href'], $link['attributes'] );
 497              }
 498          }
 499  
 500          /**
 501           * Filters an attachment returned from the REST API.
 502           *
 503           * Allows modification of the attachment right before it is returned.
 504           *
 505           * @since 4.7.0
 506           *
 507           * @param WP_REST_Response $response The response object.
 508           * @param WP_Post          $post     The original attachment post.
 509           * @param WP_REST_Request  $request  Request used to generate the response.
 510           */
 511          return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
 512      }
 513  
 514      /**
 515       * Retrieves the attachment's schema, conforming to JSON Schema.
 516       *
 517       * @since 4.7.0
 518       *
 519       * @return array Item schema as an array.
 520       */
 521  	public function get_item_schema() {
 522          if ( $this->schema ) {
 523              return $this->add_additional_fields_schema( $this->schema );
 524          }
 525  
 526          $schema = parent::get_item_schema();
 527  
 528          $schema['properties']['alt_text'] = array(
 529              'description' => __( 'Alternative text to display when attachment is not displayed.' ),
 530              'type'        => 'string',
 531              'context'     => array( 'view', 'edit', 'embed' ),
 532              'arg_options' => array(
 533                  'sanitize_callback' => 'sanitize_text_field',
 534              ),
 535          );
 536  
 537          $schema['properties']['caption'] = array(
 538              'description' => __( 'The attachment caption.' ),
 539              'type'        => 'object',
 540              'context'     => array( 'view', 'edit', 'embed' ),
 541              'arg_options' => array(
 542                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
 543                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
 544              ),
 545              'properties'  => array(
 546                  'raw'      => array(
 547                      'description' => __( 'Caption for the attachment, as it exists in the database.' ),
 548                      'type'        => 'string',
 549                      'context'     => array( 'edit' ),
 550                  ),
 551                  'rendered' => array(
 552                      'description' => __( 'HTML caption for the attachment, transformed for display.' ),
 553                      'type'        => 'string',
 554                      'context'     => array( 'view', 'edit', 'embed' ),
 555                      'readonly'    => true,
 556                  ),
 557              ),
 558          );
 559  
 560          $schema['properties']['description'] = array(
 561              'description' => __( 'The attachment description.' ),
 562              'type'        => 'object',
 563              'context'     => array( 'view', 'edit' ),
 564              'arg_options' => array(
 565                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
 566                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
 567              ),
 568              'properties'  => array(
 569                  'raw'      => array(
 570                      'description' => __( 'Description for the object, as it exists in the database.' ),
 571                      'type'        => 'string',
 572                      'context'     => array( 'edit' ),
 573                  ),
 574                  'rendered' => array(
 575                      'description' => __( 'HTML description for the object, transformed for display.' ),
 576                      'type'        => 'string',
 577                      'context'     => array( 'view', 'edit' ),
 578                      'readonly'    => true,
 579                  ),
 580              ),
 581          );
 582  
 583          $schema['properties']['media_type'] = array(
 584              'description' => __( 'Attachment type.' ),
 585              'type'        => 'string',
 586              'enum'        => array( 'image', 'file' ),
 587              'context'     => array( 'view', 'edit', 'embed' ),
 588              'readonly'    => true,
 589          );
 590  
 591          $schema['properties']['mime_type'] = array(
 592              'description' => __( 'The attachment MIME type.' ),
 593              'type'        => 'string',
 594              'context'     => array( 'view', 'edit', 'embed' ),
 595              'readonly'    => true,
 596          );
 597  
 598          $schema['properties']['media_details'] = array(
 599              'description' => __( 'Details about the media file, specific to its type.' ),
 600              'type'        => 'object',
 601              'context'     => array( 'view', 'edit', 'embed' ),
 602              'readonly'    => true,
 603          );
 604  
 605          $schema['properties']['post'] = array(
 606              'description' => __( 'The ID for the associated post of the attachment.' ),
 607              'type'        => 'integer',
 608              'context'     => array( 'view', 'edit' ),
 609          );
 610  
 611          $schema['properties']['source_url'] = array(
 612              'description' => __( 'URL to the original attachment file.' ),
 613              'type'        => 'string',
 614              'format'      => 'uri',
 615              'context'     => array( 'view', 'edit', 'embed' ),
 616              'readonly'    => true,
 617          );
 618  
 619          $schema['properties']['missing_image_sizes'] = array(
 620              'description' => __( 'List of the missing image sizes of the attachment.' ),
 621              'type'        => 'array',
 622              'items'       => array( 'type' => 'string' ),
 623              'context'     => array( 'edit' ),
 624              'readonly'    => true,
 625          );
 626  
 627          unset( $schema['properties']['password'] );
 628  
 629          $this->schema = $schema;
 630          return $this->add_additional_fields_schema( $this->schema );
 631      }
 632  
 633      /**
 634       * Handles an upload via raw POST data.
 635       *
 636       * @since 4.7.0
 637       *
 638       * @param array $data    Supplied file data.
 639       * @param array $headers HTTP headers from the request.
 640       * @return array|WP_Error Data from wp_handle_sideload().
 641       */
 642  	protected function upload_from_data( $data, $headers ) {
 643          if ( empty( $data ) ) {
 644              return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
 645          }
 646  
 647          if ( empty( $headers['content_type'] ) ) {
 648              return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied.' ), array( 'status' => 400 ) );
 649          }
 650  
 651          if ( empty( $headers['content_disposition'] ) ) {
 652              return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied.' ), array( 'status' => 400 ) );
 653          }
 654  
 655          $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
 656  
 657          if ( empty( $filename ) ) {
 658              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 ) );
 659          }
 660  
 661          if ( ! empty( $headers['content_md5'] ) ) {
 662              $content_md5 = array_shift( $headers['content_md5'] );
 663              $expected    = trim( $content_md5 );
 664              $actual      = md5( $data );
 665  
 666              if ( $expected !== $actual ) {
 667                  return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
 668              }
 669          }
 670  
 671          // Get the content-type.
 672          $type = array_shift( $headers['content_type'] );
 673  
 674          /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload(). */
 675          require_once ABSPATH . 'wp-admin/includes/file.php';
 676  
 677          // Save the file.
 678          $tmpfname = wp_tempnam( $filename );
 679  
 680          $fp = fopen( $tmpfname, 'w+' );
 681  
 682          if ( ! $fp ) {
 683              return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle.' ), array( 'status' => 500 ) );
 684          }
 685  
 686          fwrite( $fp, $data );
 687          fclose( $fp );
 688  
 689          // Now, sideload it in.
 690          $file_data = array(
 691              'error'    => null,
 692              'tmp_name' => $tmpfname,
 693              'name'     => $filename,
 694              'type'     => $type,
 695          );
 696  
 697          $size_check = self::check_upload_size( $file_data );
 698          if ( is_wp_error( $size_check ) ) {
 699              return $size_check;
 700          }
 701  
 702          $overrides = array(
 703              'test_form' => false,
 704          );
 705  
 706          $sideloaded = wp_handle_sideload( $file_data, $overrides );
 707  
 708          if ( isset( $sideloaded['error'] ) ) {
 709              @unlink( $tmpfname );
 710  
 711              return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
 712          }
 713  
 714          return $sideloaded;
 715      }
 716  
 717      /**
 718       * Parses filename from a Content-Disposition header value.
 719       *
 720       * As per RFC6266:
 721       *
 722       *     content-disposition = "Content-Disposition" ":"
 723       *                            disposition-type *( ";" disposition-parm )
 724       *
 725       *     disposition-type    = "inline" | "attachment" | disp-ext-type
 726       *                         ; case-insensitive
 727       *     disp-ext-type       = token
 728       *
 729       *     disposition-parm    = filename-parm | disp-ext-parm
 730       *
 731       *     filename-parm       = "filename" "=" value
 732       *                         | "filename*" "=" ext-value
 733       *
 734       *     disp-ext-parm       = token "=" value
 735       *                         | ext-token "=" ext-value
 736       *     ext-token           = <the characters in token, followed by "*">
 737       *
 738       * @since 4.7.0
 739       *
 740       * @link https://tools.ietf.org/html/rfc2388
 741       * @link https://tools.ietf.org/html/rfc6266
 742       *
 743       * @param string[] $disposition_header List of Content-Disposition header values.
 744       * @return string|null Filename if available, or null if not found.
 745       */
 746  	public static function get_filename_from_disposition( $disposition_header ) {
 747          // Get the filename.
 748          $filename = null;
 749  
 750          foreach ( $disposition_header as $value ) {
 751              $value = trim( $value );
 752  
 753              if ( strpos( $value, ';' ) === false ) {
 754                  continue;
 755              }
 756  
 757              list( $type, $attr_parts ) = explode( ';', $value, 2 );
 758  
 759              $attr_parts = explode( ';', $attr_parts );
 760              $attributes = array();
 761  
 762              foreach ( $attr_parts as $part ) {
 763                  if ( strpos( $part, '=' ) === false ) {
 764                      continue;
 765                  }
 766  
 767                  list( $key, $value ) = explode( '=', $part, 2 );
 768  
 769                  $attributes[ trim( $key ) ] = trim( $value );
 770              }
 771  
 772              if ( empty( $attributes['filename'] ) ) {
 773                  continue;
 774              }
 775  
 776              $filename = trim( $attributes['filename'] );
 777  
 778              // Unquote quoted filename, but after trimming.
 779              if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
 780                  $filename = substr( $filename, 1, -1 );
 781              }
 782          }
 783  
 784          return $filename;
 785      }
 786  
 787      /**
 788       * Retrieves the query params for collections of attachments.
 789       *
 790       * @since 4.7.0
 791       *
 792       * @return array Query parameters for the attachment collection as an array.
 793       */
 794  	public function get_collection_params() {
 795          $params                            = parent::get_collection_params();
 796          $params['status']['default']       = 'inherit';
 797          $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
 798          $media_types                       = $this->get_media_types();
 799  
 800          $params['media_type'] = array(
 801              'default'     => null,
 802              'description' => __( 'Limit result set to attachments of a particular media type.' ),
 803              'type'        => 'string',
 804              'enum'        => array_keys( $media_types ),
 805          );
 806  
 807          $params['mime_type'] = array(
 808              'default'     => null,
 809              'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
 810              'type'        => 'string',
 811          );
 812  
 813          return $params;
 814      }
 815  
 816      /**
 817       * Handles an upload via multipart/form-data ($_FILES).
 818       *
 819       * @since 4.7.0
 820       *
 821       * @param array $files   Data from the `$_FILES` superglobal.
 822       * @param array $headers HTTP headers from the request.
 823       * @return array|WP_Error Data from wp_handle_upload().
 824       */
 825  	protected function upload_from_file( $files, $headers ) {
 826          if ( empty( $files ) ) {
 827              return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
 828          }
 829  
 830          // Verify hash, if given.
 831          if ( ! empty( $headers['content_md5'] ) ) {
 832              $content_md5 = array_shift( $headers['content_md5'] );
 833              $expected    = trim( $content_md5 );
 834              $actual      = md5_file( $files['file']['tmp_name'] );
 835  
 836              if ( $expected !== $actual ) {
 837                  return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
 838              }
 839          }
 840  
 841          // Pass off to WP to handle the actual upload.
 842          $overrides = array(
 843              'test_form' => false,
 844          );
 845  
 846          // Bypasses is_uploaded_file() when running unit tests.
 847          if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
 848              $overrides['action'] = 'wp_handle_mock_upload';
 849          }
 850  
 851          $size_check = self::check_upload_size( $files['file'] );
 852          if ( is_wp_error( $size_check ) ) {
 853              return $size_check;
 854          }
 855  
 856          /** Include admin function to get access to wp_handle_upload(). */
 857          require_once ABSPATH . 'wp-admin/includes/file.php';
 858  
 859          $file = wp_handle_upload( $files['file'], $overrides );
 860  
 861          if ( isset( $file['error'] ) ) {
 862              return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
 863          }
 864  
 865          return $file;
 866      }
 867  
 868      /**
 869       * Retrieves the supported media types.
 870       *
 871       * Media types are considered the MIME type category.
 872       *
 873       * @since 4.7.0
 874       *
 875       * @return array Array of supported media types.
 876       */
 877  	protected function get_media_types() {
 878          $media_types = array();
 879  
 880          foreach ( get_allowed_mime_types() as $mime_type ) {
 881              $parts = explode( '/', $mime_type );
 882  
 883              if ( ! isset( $media_types[ $parts[0] ] ) ) {
 884                  $media_types[ $parts[0] ] = array();
 885              }
 886  
 887              $media_types[ $parts[0] ][] = $mime_type;
 888          }
 889  
 890          return $media_types;
 891      }
 892  
 893      /**
 894       * Determine if uploaded file exceeds space quota on multisite.
 895       *
 896       * Replicates check_upload_size().
 897       *
 898       * @since 4.9.8
 899       *
 900       * @param array $file $_FILES array for a given file.
 901       * @return true|WP_Error True if can upload, error for errors.
 902       */
 903  	protected function check_upload_size( $file ) {
 904          if ( ! is_multisite() ) {
 905              return true;
 906          }
 907  
 908          if ( get_site_option( 'upload_space_check_disabled' ) ) {
 909              return true;
 910          }
 911  
 912          $space_left = get_upload_space_available();
 913  
 914          $file_size = filesize( $file['tmp_name'] );
 915          if ( $space_left < $file_size ) {
 916              /* translators: %s: Required disk space in kilobytes. */
 917              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 ) );
 918          }
 919  
 920          if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
 921              /* translators: %s: Maximum allowed file size in kilobytes. */
 922              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 ) );
 923          }
 924  
 925          // Include admin function to get access to upload_is_user_over_quota().
 926          require_once ABSPATH . 'wp-admin/includes/ms.php';
 927  
 928          if ( upload_is_user_over_quota( false ) ) {
 929              return new WP_Error( 'rest_upload_user_quota_exceeded', __( 'You have used your space quota. Please delete files before uploading.' ), array( 'status' => 400 ) );
 930          }
 931          return true;
 932      }
 933  
 934  }


Generated: Mon Nov 18 01:00:04 2019 Cross-referenced by PHPXref 0.7.1