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'];
50 // Filter query clauses to include filenames.
51 if ( isset( $query_args['s'] ) ) {
52 add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
59 * Checks if a given request has access to create an attachment.
64 * @param WP_REST_Request $request Full details about the request.
65 * @return WP_Error|true Boolean true if the attachment may be created, or a WP_Error if not.
67 public function create_item_permissions_check( $request ) {
68 $ret = parent::create_item_permissions_check( $request );
70 if ( ! $ret || is_wp_error( $ret ) ) {
74 if ( ! current_user_can( 'upload_files' ) ) {
75 return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to upload media on this site.' ), array( 'status' => 400 ) );
78 // Attaching media to a post requires ability to edit said post.
79 if ( ! empty( $request['post'] ) ) {
80 $parent = get_post( (int) $request['post'] );
81 $post_parent_type = get_post_type_object( $parent->post_type );
83 if ( ! current_user_can( $post_parent_type->cap->edit_post, $request['post'] ) ) {
84 return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to upload media to this post.' ), array( 'status' => rest_authorization_required_code() ) );
92 * Creates a single attachment.
97 * @param WP_REST_Request $request Full details about the request.
98 * @return WP_Error|WP_REST_Response Response object on success, WP_Error object on failure.
100 public function create_item( $request ) {
102 if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
103 return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
106 // Get the file via $_FILES or raw data.
107 $files = $request->get_file_params();
108 $headers = $request->get_headers();
110 if ( ! empty( $files ) ) {
111 $file = $this->upload_from_file( $files, $headers );
113 $file = $this->upload_from_data( $request->get_body(), $headers );
116 if ( is_wp_error( $file ) ) {
120 $name = basename( $file['file'] );
121 $name_parts = pathinfo( $name );
122 $name = trim( substr( $name, 0, -(1 + strlen( $name_parts['extension'] ) ) ) );
125 $type = $file['type'];
126 $file = $file['file'];
128 // use image exif/iptc data for title and caption defaults if possible
129 $image_meta = @wp_read_image_metadata( $file );
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'];
136 if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
137 $request['caption'] = $image_meta['caption'];
141 $attachment = $this->prepare_item_for_database( $request );
142 $attachment->file = $file;
143 $attachment->post_mime_type = $type;
144 $attachment->guid = $url;
146 if ( empty( $attachment->post_title ) ) {
147 $attachment->post_title = preg_replace( '/\.[^.]+$/', '', basename( $file ) );
150 $id = wp_insert_post( wp_slash( (array) $attachment ), true );
152 if ( is_wp_error( $id ) ) {
153 if ( 'db_update_error' === $id->get_error_code() ) {
154 $id->add_data( array( 'status' => 500 ) );
156 $id->add_data( array( 'status' => 400 ) );
161 $attachment = get_post( $id );
164 * Fires after a single attachment is created or updated via the REST API.
168 * @param WP_Post $attachment Inserted or updated attachment
170 * @param WP_REST_Request $request The request sent to the API.
171 * @param bool $creating True when creating an attachment, false when updating.
173 do_action( 'rest_insert_attachment', $attachment, $request, true );
175 // Include admin functions to get access to wp_generate_attachment_metadata().
176 require_once ABSPATH . 'wp-admin/includes/admin.php';
178 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
180 if ( isset( $request['alt_text'] ) ) {
181 update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
184 $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
186 if ( is_wp_error( $fields_update ) ) {
187 return $fields_update;
190 $request->set_param( 'context', 'edit' );
191 $response = $this->prepare_item_for_response( $attachment, $request );
192 $response = rest_ensure_response( $response );
193 $response->set_status( 201 );
194 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $id ) ) );
200 * Updates a single attachment.
205 * @param WP_REST_Request $request Full details about the request.
206 * @return WP_Error|WP_REST_Response Response object on success, WP_Error object on failure.
208 public function update_item( $request ) {
209 if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
210 return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
213 $response = parent::update_item( $request );
215 if ( is_wp_error( $response ) ) {
219 $response = rest_ensure_response( $response );
220 $data = $response->get_data();
222 if ( isset( $request['alt_text'] ) ) {
223 update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
226 $attachment = get_post( $request['id'] );
228 /* This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
229 do_action( 'rest_insert_attachment', $data, $request, false );
231 $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
233 if ( is_wp_error( $fields_update ) ) {
234 return $fields_update;
237 $request->set_param( 'context', 'edit' );
238 $response = $this->prepare_item_for_response( $attachment, $request );
239 $response = rest_ensure_response( $response );
245 * Prepares a single attachment for create or update.
250 * @param WP_REST_Request $request Request object.
251 * @return WP_Error|stdClass $prepared_attachment Post object.
253 protected function prepare_item_for_database( $request ) {
254 $prepared_attachment = parent::prepare_item_for_database( $request );
256 // Attachment caption (post_excerpt internally)
257 if ( isset( $request['caption'] ) ) {
258 if ( is_string( $request['caption'] ) ) {
259 $prepared_attachment->post_excerpt = $request['caption'];
260 } elseif ( isset( $request['caption']['raw'] ) ) {
261 $prepared_attachment->post_excerpt = $request['caption']['raw'];
265 // Attachment description (post_content internally)
266 if ( isset( $request['description'] ) ) {
267 if ( is_string( $request['description'] ) ) {
268 $prepared_attachment->post_content = $request['description'];
269 } elseif ( isset( $request['description']['raw'] ) ) {
270 $prepared_attachment->post_content = $request['description']['raw'];
274 if ( isset( $request['post'] ) ) {
275 $prepared_attachment->post_parent = (int) $request['post'];
278 return $prepared_attachment;
282 * Prepares a single attachment output for response.
287 * @param WP_Post $post Attachment object.
288 * @param WP_REST_Request $request Request object.
289 * @return WP_REST_Response Response object.
291 public function prepare_item_for_response( $post, $request ) {
292 $response = parent::prepare_item_for_response( $post, $request );
293 $data = $response->get_data();
295 $data['description'] = array(
296 'raw' => $post->post_content,
297 /** This filter is documented in wp-includes/post-template.php */
298 'rendered' => apply_filters( 'the_content', $post->post_content ),
301 /** This filter is documented in wp-includes/post-template.php */
302 $caption = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ) );
303 $data['caption'] = array(
304 'raw' => $post->post_excerpt,
305 'rendered' => $caption,
308 $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
309 $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
310 $data['mime_type'] = $post->post_mime_type;
311 $data['media_details'] = wp_get_attachment_metadata( $post->ID );
312 $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
313 $data['source_url'] = wp_get_attachment_url( $post->ID );
315 // Ensure empty details is an empty object.
316 if ( empty( $data['media_details'] ) ) {
317 $data['media_details'] = new stdClass;
318 } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
320 foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
322 if ( isset( $size_data['mime-type'] ) ) {
323 $size_data['mime_type'] = $size_data['mime-type'];
324 unset( $size_data['mime-type'] );
327 // Use the same method image_downsize() does.
328 $image_src = wp_get_attachment_image_src( $post->ID, $size );
329 if ( ! $image_src ) {
333 $size_data['source_url'] = $image_src[0];
336 $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
338 if ( ! empty( $full_src ) ) {
339 $data['media_details']['sizes']['full'] = array(
340 'file' => wp_basename( $full_src[0] ),
341 'width' => $full_src[1],
342 'height' => $full_src[2],
343 'mime_type' => $post->post_mime_type,
344 'source_url' => $full_src[0],
348 $data['media_details']['sizes'] = new stdClass;
351 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
353 $data = $this->filter_response_by_context( $data, $context );
355 // Wrap the data in a response object.
356 $response = rest_ensure_response( $data );
358 $response->add_links( $this->prepare_links( $post ) );
361 * Filters an attachment returned from the REST API.
363 * Allows modification of the attachment right before it is returned.
367 * @param WP_REST_Response $response The response object.
368 * @param WP_Post $post The original attachment post.
369 * @param WP_REST_Request $request Request used to generate the response.
371 return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
375 * Retrieves the attachment's schema, conforming to JSON Schema.
380 * @return array Item schema as an array.
382 public function get_item_schema() {
384 $schema = parent::get_item_schema();
386 $schema['properties']['alt_text'] = array(
387 'description' => __( 'Alternative text to display when attachment is not displayed.' ),
389 'context' => array( 'view', 'edit', 'embed' ),
390 'arg_options' => array(
391 'sanitize_callback' => 'sanitize_text_field',
395 $schema['properties']['caption'] = array(
396 'description' => __( 'The attachment caption.' ),
398 'context' => array( 'view', 'edit', 'embed' ),
399 'arg_options' => array(
400 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
402 'properties' => array(
404 'description' => __( 'Caption for the attachment, as it exists in the database.' ),
406 'context' => array( 'edit' ),
409 'description' => __( 'HTML caption for the attachment, transformed for display.' ),
411 'context' => array( 'view', 'edit', 'embed' ),
417 $schema['properties']['description'] = array(
418 'description' => __( 'The attachment description.' ),
420 'context' => array( 'view', 'edit' ),
421 'arg_options' => array(
422 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
424 'properties' => array(
426 'description' => __( 'Description for the object, as it exists in the database.' ),
428 'context' => array( 'edit' ),
431 'description' => __( 'HTML description for the object, transformed for display.' ),
433 'context' => array( 'view', 'edit' ),
439 $schema['properties']['media_type'] = array(
440 'description' => __( 'Attachment type.' ),
442 'enum' => array( 'image', 'file' ),
443 'context' => array( 'view', 'edit', 'embed' ),
447 $schema['properties']['mime_type'] = array(
448 'description' => __( 'The attachment MIME type.' ),
450 'context' => array( 'view', 'edit', 'embed' ),
454 $schema['properties']['media_details'] = array(
455 'description' => __( 'Details about the media file, specific to its type.' ),
457 'context' => array( 'view', 'edit', 'embed' ),
461 $schema['properties']['post'] = array(
462 'description' => __( 'The ID for the associated post of the attachment.' ),
464 'context' => array( 'view', 'edit' ),
467 $schema['properties']['source_url'] = array(
468 'description' => __( 'URL to the original attachment file.' ),
471 'context' => array( 'view', 'edit', 'embed' ),
475 unset( $schema['properties']['password'] );
481 * Handles an upload via raw POST data.
486 * @param array $data Supplied file data.
487 * @param array $headers HTTP headers from the request.
488 * @return array|WP_Error Data from wp_handle_sideload().
490 protected function upload_from_data( $data, $headers ) {
491 if ( empty( $data ) ) {
492 return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
495 if ( empty( $headers['content_type'] ) ) {
496 return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied.' ), array( 'status' => 400 ) );
499 if ( empty( $headers['content_disposition'] ) ) {
500 return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied.' ), array( 'status' => 400 ) );
503 $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
505 if ( empty( $filename ) ) {
506 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 ) );
509 if ( ! empty( $headers['content_md5'] ) ) {
510 $content_md5 = array_shift( $headers['content_md5'] );
511 $expected = trim( $content_md5 );
512 $actual = md5( $data );
514 if ( $expected !== $actual ) {
515 return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
519 // Get the content-type.
520 $type = array_shift( $headers['content_type'] );
522 /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload() */
523 require_once ABSPATH . 'wp-admin/includes/admin.php';
526 $tmpfname = wp_tempnam( $filename );
528 $fp = fopen( $tmpfname, 'w+' );
531 return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle.' ), array( 'status' => 500 ) );
534 fwrite( $fp, $data );
537 // Now, sideload it in.
540 'tmp_name' => $tmpfname,
546 'test_form' => false,
549 $sideloaded = wp_handle_sideload( $file_data, $overrides );
551 if ( isset( $sideloaded['error'] ) ) {
552 @unlink( $tmpfname );
554 return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
561 * Parses filename from a Content-Disposition header value.
565 * content-disposition = "Content-Disposition" ":"
566 * disposition-type *( ";" disposition-parm )
568 * disposition-type = "inline" | "attachment" | disp-ext-type
570 * disp-ext-type = token
572 * disposition-parm = filename-parm | disp-ext-parm
574 * filename-parm = "filename" "=" value
575 * | "filename*" "=" ext-value
577 * disp-ext-parm = token "=" value
578 * | ext-token "=" ext-value
579 * ext-token = <the characters in token, followed by "*">
584 * @link http://tools.ietf.org/html/rfc2388
585 * @link http://tools.ietf.org/html/rfc6266
587 * @param string[] $disposition_header List of Content-Disposition header values.
588 * @return string|null Filename if available, or null if not found.
590 public static function get_filename_from_disposition( $disposition_header ) {
594 foreach ( $disposition_header as $value ) {
595 $value = trim( $value );
597 if ( strpos( $value, ';' ) === false ) {
601 list( $type, $attr_parts ) = explode( ';', $value, 2 );
603 $attr_parts = explode( ';', $attr_parts );
604 $attributes = array();
606 foreach ( $attr_parts as $part ) {
607 if ( strpos( $part, '=' ) === false ) {
611 list( $key, $value ) = explode( '=', $part, 2 );
613 $attributes[ trim( $key ) ] = trim( $value );
616 if ( empty( $attributes['filename'] ) ) {
620 $filename = trim( $attributes['filename'] );
622 // Unquote quoted filename, but after trimming.
623 if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
624 $filename = substr( $filename, 1, -1 );
632 * Retrieves the query params for collections of attachments.
637 * @return array Query parameters for the attachment collection as an array.
639 public function get_collection_params() {
640 $params = parent::get_collection_params();
641 $params['status']['default'] = 'inherit';
642 $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
643 $media_types = $this->get_media_types();
645 $params['media_type'] = array(
647 'description' => __( 'Limit result set to attachments of a particular media type.' ),
649 'enum' => array_keys( $media_types ),
652 $params['mime_type'] = array(
654 'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
662 * Validates whether the user can query private statuses.
667 * @param mixed $value Status value.
668 * @param WP_REST_Request $request Request object.
669 * @param string $parameter Additional parameter to pass for validation.
670 * @return WP_Error|bool True if the user may query, WP_Error if not.
672 public function validate_user_can_query_private_statuses( $value, $request, $parameter ) {
673 if ( 'inherit' === $value ) {
677 return parent::validate_user_can_query_private_statuses( $value, $request, $parameter );
681 * Handles an upload via multipart/form-data ($_FILES).
686 * @param array $files Data from the `$_FILES` superglobal.
687 * @param array $headers HTTP headers from the request.
688 * @return array|WP_Error Data from wp_handle_upload().
690 protected function upload_from_file( $files, $headers ) {
691 if ( empty( $files ) ) {
692 return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
695 // Verify hash, if given.
696 if ( ! empty( $headers['content_md5'] ) ) {
697 $content_md5 = array_shift( $headers['content_md5'] );
698 $expected = trim( $content_md5 );
699 $actual = md5_file( $files['file']['tmp_name'] );
701 if ( $expected !== $actual ) {
702 return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
706 // Pass off to WP to handle the actual upload.
708 'test_form' => false,
711 // Bypasses is_uploaded_file() when running unit tests.
712 if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
713 $overrides['action'] = 'wp_handle_mock_upload';
716 /** Include admin functions to get access to wp_handle_upload() */
717 require_once ABSPATH . 'wp-admin/includes/admin.php';
719 $file = wp_handle_upload( $files['file'], $overrides );
721 if ( isset( $file['error'] ) ) {
722 return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
729 * Retrieves the supported media types.
731 * Media types are considered the MIME type category.
736 * @return array Array of supported media types.
738 protected function get_media_types() {
739 $media_types = array();
741 foreach ( get_allowed_mime_types() as $mime_type ) {
742 $parts = explode( '/', $mime_type );
744 if ( ! isset( $media_types[ $parts[0] ] ) ) {
745 $media_types[ $parts[0] ] = array();
748 $media_types[ $parts[0] ][] = $mime_type;