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


Generated: Tue Sep 17 01:00:03 2019 Cross-referenced by PHPXref 0.7.1