3 * REST API: WP_REST_Attachments_Controller class
11 * Core controller used to access attachments via the REST API.
15 * @see WP_REST_Posts_Controller
17 class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
20 * Determines the allowed query_vars for a get_items() response and
21 * prepares for WP_Query.
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.
30 protected function prepare_items_query( $prepared_args = array(), $request = null ) {
31 $query_args = parent::prepare_items_query( $prepared_args, $request );
33 if ( empty( $query_args['post_status'] ) ) {
34 $query_args['post_status'] = 'inherit';
37 $media_types = $this->get_media_types();
39 if ( ! empty( $request['media_type'] ) && isset( $media_types[ $request['media_type'] ] ) ) {
40 $query_args['post_mime_type'] = $media_types[ $request['media_type'] ];
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'];
54 * Checks if a given request has access to create an attachment.
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.
62 public function create_item_permissions_check( $request ) {
63 $ret = parent::create_item_permissions_check( $request );
65 if ( ! $ret || is_wp_error( $ret ) ) {
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 ) );
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 );
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() ) );
87 * Creates a single attachment.
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.
95 public function create_item( $request ) {
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 ) );
101 // Get the file via $_FILES or raw data.
102 $files = $request->get_file_params();
103 $headers = $request->get_headers();
105 if ( ! empty( $files ) ) {
106 $file = $this->upload_from_file( $files, $headers );
108 $file = $this->upload_from_data( $request->get_body(), $headers );
111 if ( is_wp_error( $file ) ) {
115 $name = basename( $file['file'] );
116 $name_parts = pathinfo( $name );
117 $name = trim( substr( $name, 0, -(1 + strlen( $name_parts['extension'] ) ) ) );
120 $type = $file['type'];
121 $file = $file['file'];
123 // use image exif/iptc data for title and caption defaults if possible
124 $image_meta = @wp_read_image_metadata( $file );
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'];
131 if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
132 $request['caption'] = $image_meta['caption'];
136 $attachment = $this->prepare_item_for_database( $request );
137 $attachment->file = $file;
138 $attachment->post_mime_type = $type;
139 $attachment->guid = $url;
141 if ( empty( $attachment->post_title ) ) {
142 $attachment->post_title = preg_replace( '/\.[^.]+$/', '', basename( $file ) );
145 $id = wp_insert_post( wp_slash( (array) $attachment ), true );
147 if ( is_wp_error( $id ) ) {
148 if ( 'db_update_error' === $id->get_error_code() ) {
149 $id->add_data( array( 'status' => 500 ) );
151 $id->add_data( array( 'status' => 400 ) );
156 $attachment = get_post( $id );
159 * Fires after a single attachment is created or updated via the REST API.
163 * @param WP_Post $attachment Inserted or updated attachment
165 * @param WP_REST_Request $request The request sent to the API.
166 * @param bool $creating True when creating an attachment, false when updating.
168 do_action( 'rest_insert_attachment', $attachment, $request, true );
170 // Include admin functions to get access to wp_generate_attachment_metadata().
171 require_once ABSPATH . 'wp-admin/includes/admin.php';
173 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
175 if ( isset( $request['alt_text'] ) ) {
176 update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
179 $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
181 if ( is_wp_error( $fields_update ) ) {
182 return $fields_update;
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 ) ) );
195 * Updates a single attachment.
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.
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 ) );
208 $response = parent::update_item( $request );
210 if ( is_wp_error( $response ) ) {
214 $response = rest_ensure_response( $response );
215 $data = $response->get_data();
217 if ( isset( $request['alt_text'] ) ) {
218 update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
221 $attachment = get_post( $request['id'] );
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 );
226 $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
228 if ( is_wp_error( $fields_update ) ) {
229 return $fields_update;
232 $request->set_param( 'context', 'edit' );
233 $response = $this->prepare_item_for_response( $attachment, $request );
234 $response = rest_ensure_response( $response );
240 * Prepares a single attachment for create or update.
245 * @param WP_REST_Request $request Request object.
246 * @return WP_Error|stdClass $prepared_attachment Post object.
248 protected function prepare_item_for_database( $request ) {
249 $prepared_attachment = parent::prepare_item_for_database( $request );
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'];
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'];
269 if ( isset( $request['post'] ) ) {
270 $prepared_attachment->post_parent = (int) $request['post'];
273 return $prepared_attachment;
277 * Prepares a single attachment output for response.
282 * @param WP_Post $post Attachment object.
283 * @param WP_REST_Request $request Request object.
284 * @return WP_REST_Response Response object.
286 public function prepare_item_for_response( $post, $request ) {
287 $response = parent::prepare_item_for_response( $post, $request );
288 $data = $response->get_data();
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 ),
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,
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 );
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'] ) ) {
315 foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
317 if ( isset( $size_data['mime-type'] ) ) {
318 $size_data['mime_type'] = $size_data['mime-type'];
319 unset( $size_data['mime-type'] );
322 // Use the same method image_downsize() does.
323 $image_src = wp_get_attachment_image_src( $post->ID, $size );
324 if ( ! $image_src ) {
328 $size_data['source_url'] = $image_src[0];
331 $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
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],
343 $data['media_details']['sizes'] = new stdClass;
346 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
348 $data = $this->filter_response_by_context( $data, $context );
350 // Wrap the data in a response object.
351 $response = rest_ensure_response( $data );
353 $response->add_links( $this->prepare_links( $post ) );
356 * Filters an attachment returned from the REST API.
358 * Allows modification of the attachment right before it is returned.
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.
366 return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
370 * Retrieves the attachment's schema, conforming to JSON Schema.
375 * @return array Item schema as an array.
377 public function get_item_schema() {
379 $schema = parent::get_item_schema();
381 $schema['properties']['alt_text'] = array(
382 'description' => __( 'Alternative text to display when attachment is not displayed.' ),
384 'context' => array( 'view', 'edit', 'embed' ),
385 'arg_options' => array(
386 'sanitize_callback' => 'sanitize_text_field',
390 $schema['properties']['caption'] = array(
391 'description' => __( 'The attachment caption.' ),
393 'context' => array( 'view', 'edit', 'embed' ),
394 'arg_options' => array(
395 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
397 'properties' => array(
399 'description' => __( 'Caption for the attachment, as it exists in the database.' ),
401 'context' => array( 'edit' ),
404 'description' => __( 'HTML caption for the attachment, transformed for display.' ),
406 'context' => array( 'view', 'edit', 'embed' ),
412 $schema['properties']['description'] = array(
413 'description' => __( 'The attachment description.' ),
415 'context' => array( 'view', 'edit' ),
416 'arg_options' => array(
417 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
419 'properties' => array(
421 'description' => __( 'Description for the object, as it exists in the database.' ),
423 'context' => array( 'edit' ),
426 'description' => __( 'HTML description for the object, transformed for display.' ),
428 'context' => array( 'view', 'edit' ),
434 $schema['properties']['media_type'] = array(
435 'description' => __( 'Attachment type.' ),
437 'enum' => array( 'image', 'file' ),
438 'context' => array( 'view', 'edit', 'embed' ),
442 $schema['properties']['mime_type'] = array(
443 'description' => __( 'The attachment MIME type.' ),
445 'context' => array( 'view', 'edit', 'embed' ),
449 $schema['properties']['media_details'] = array(
450 'description' => __( 'Details about the media file, specific to its type.' ),
452 'context' => array( 'view', 'edit', 'embed' ),
456 $schema['properties']['post'] = array(
457 'description' => __( 'The ID for the associated post of the attachment.' ),
459 'context' => array( 'view', 'edit' ),
462 $schema['properties']['source_url'] = array(
463 'description' => __( 'URL to the original attachment file.' ),
466 'context' => array( 'view', 'edit', 'embed' ),
470 unset( $schema['properties']['password'] );
476 * Handles an upload via raw POST data.
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().
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 ) );
490 if ( empty( $headers['content_type'] ) ) {
491 return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied.' ), array( 'status' => 400 ) );
494 if ( empty( $headers['content_disposition'] ) ) {
495 return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied.' ), array( 'status' => 400 ) );
498 $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
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 ) );
504 if ( ! empty( $headers['content_md5'] ) ) {
505 $content_md5 = array_shift( $headers['content_md5'] );
506 $expected = trim( $content_md5 );
507 $actual = md5( $data );
509 if ( $expected !== $actual ) {
510 return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
514 // Get the content-type.
515 $type = array_shift( $headers['content_type'] );
517 /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload() */
518 require_once ABSPATH . 'wp-admin/includes/admin.php';
521 $tmpfname = wp_tempnam( $filename );
523 $fp = fopen( $tmpfname, 'w+' );
526 return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle.' ), array( 'status' => 500 ) );
529 fwrite( $fp, $data );
532 // Now, sideload it in.
535 'tmp_name' => $tmpfname,
541 'test_form' => false,
544 $sideloaded = wp_handle_sideload( $file_data, $overrides );
546 if ( isset( $sideloaded['error'] ) ) {
547 @unlink( $tmpfname );
549 return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
556 * Parses filename from a Content-Disposition header value.
560 * content-disposition = "Content-Disposition" ":"
561 * disposition-type *( ";" disposition-parm )
563 * disposition-type = "inline" | "attachment" | disp-ext-type
565 * disp-ext-type = token
567 * disposition-parm = filename-parm | disp-ext-parm
569 * filename-parm = "filename" "=" value
570 * | "filename*" "=" ext-value
572 * disp-ext-parm = token "=" value
573 * | ext-token "=" ext-value
574 * ext-token = <the characters in token, followed by "*">
579 * @link http://tools.ietf.org/html/rfc2388
580 * @link http://tools.ietf.org/html/rfc6266
582 * @param string[] $disposition_header List of Content-Disposition header values.
583 * @return string|null Filename if available, or null if not found.
585 public static function get_filename_from_disposition( $disposition_header ) {
589 foreach ( $disposition_header as $value ) {
590 $value = trim( $value );
592 if ( strpos( $value, ';' ) === false ) {
596 list( $type, $attr_parts ) = explode( ';', $value, 2 );
598 $attr_parts = explode( ';', $attr_parts );
599 $attributes = array();
601 foreach ( $attr_parts as $part ) {
602 if ( strpos( $part, '=' ) === false ) {
606 list( $key, $value ) = explode( '=', $part, 2 );
608 $attributes[ trim( $key ) ] = trim( $value );
611 if ( empty( $attributes['filename'] ) ) {
615 $filename = trim( $attributes['filename'] );
617 // Unquote quoted filename, but after trimming.
618 if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
619 $filename = substr( $filename, 1, -1 );
627 * Retrieves the query params for collections of attachments.
632 * @return array Query parameters for the attachment collection as an array.
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();
640 $params['media_type'] = array(
642 'description' => __( 'Limit result set to attachments of a particular media type.' ),
644 'enum' => array_keys( $media_types ),
647 $params['mime_type'] = array(
649 'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
657 * Validates whether the user can query private statuses.
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.
667 public function validate_user_can_query_private_statuses( $value, $request, $parameter ) {
668 if ( 'inherit' === $value ) {
672 return parent::validate_user_can_query_private_statuses( $value, $request, $parameter );
676 * Handles an upload via multipart/form-data ($_FILES).
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().
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 ) );
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'] );
696 if ( $expected !== $actual ) {
697 return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
701 // Pass off to WP to handle the actual upload.
703 'test_form' => false,
706 // Bypasses is_uploaded_file() when running unit tests.
707 if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
708 $overrides['action'] = 'wp_handle_mock_upload';
711 /** Include admin functions to get access to wp_handle_upload() */
712 require_once ABSPATH . 'wp-admin/includes/admin.php';
714 $file = wp_handle_upload( $files['file'], $overrides );
716 if ( isset( $file['error'] ) ) {
717 return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
724 * Retrieves the supported media types.
726 * Media types are considered the MIME type category.
731 * @return array Array of supported media types.
733 protected function get_media_types() {
734 $media_types = array();
736 foreach ( get_allowed_mime_types() as $mime_type ) {
737 $parts = explode( '/', $mime_type );
739 if ( ! isset( $media_types[ $parts[0] ] ) ) {
740 $media_types[ $parts[0] ] = array();
743 $media_types[ $parts[0] ][] = $mime_type;