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