Completed
Branch develop (0e5e8d)
by
unknown
06:58
created

endpoints/class-wp-rest-attachments-controller.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
4
5
	/**
6
	 * Determine the allowed query_vars for a get_items() response and
7
	 * prepare for WP_Query.
8
	 *
9
	 * @param array           $prepared_args
10
	 * @param WP_REST_Request $request
11
	 * @return array          $query_args
12
	 */
13
	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
14
		$query_args = parent::prepare_items_query( $prepared_args, $request );
15
		if ( empty( $query_args['post_status'] ) || ! in_array( $query_args['post_status'], array( 'inherit', 'private', 'trash' ) ) ) {
16
			$query_args['post_status'] = 'inherit';
17
		}
18
		$media_types = $this->get_media_types();
19
		if ( ! empty( $request['media_type'] ) && in_array( $request['media_type'], array_keys( $media_types ) ) ) {
20
			$query_args['post_mime_type'] = $media_types[ $request['media_type'] ];
21
		}
22
		if ( ! empty( $request['mime_type'] ) ) {
23
			$parts = explode( '/', $request['mime_type'] );
24
			if ( isset( $media_types[ $parts[0] ] ) && in_array( $request['mime_type'], $media_types[ $parts[0] ] ) ) {
25
				$query_args['post_mime_type'] = $request['mime_type'];
26
			}
27
		}
28
		return $query_args;
29
	}
30
31
	/**
32
	 * Check if a given request has access to create an attachment.
33
	 *
34
	 * @param  WP_REST_Request $request Full details about the request.
35
	 * @return WP_Error|boolean
36
	 */
37
	public function create_item_permissions_check( $request ) {
38
		$ret = parent::create_item_permissions_check( $request );
39
		if ( ! $ret || is_wp_error( $ret ) ) {
40
			return $ret;
41
		}
42
43
		// "upload_files" cap is returned for an attachment by $post_type_obj->cap->create_posts
44
		$post_type_obj = get_post_type_object( $this->post_type );
45
		if ( ! current_user_can( $post_type_obj->cap->create_posts ) || ! current_user_can( $post_type_obj->cap->edit_posts ) ) {
46
			return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to upload media on this site.' ), array( 'status' => 400 ) );
47
		}
48
49
		// Attaching media to a post requires ability to edit said post
50
		if ( ! empty( $request['post'] ) ) {
51
			$parent = $this->get_post( (int) $request['post'] );
52
			$post_parent_type = get_post_type_object( $parent->post_type );
53
			if ( ! current_user_can( $post_parent_type->cap->edit_post, $request['post'] ) ) {
54
				return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to upload media to this resource.' ), array( 'status' => rest_authorization_required_code() ) );
55
			}
56
		}
57
58
		return true;
59
	}
60
61
	/**
62
	 * Create a single attachment
63
	 *
64
	 * @param WP_REST_Request $request Full details about the request
65
	 * @return WP_Error|WP_REST_Response
66
	 */
67
	public function create_item( $request ) {
68
69
		if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ) ) ) {
70
			return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
71
		}
72
73
		// Get the file via $_FILES or raw data
74
		$files = $request->get_file_params();
75
		$headers = $request->get_headers();
76
		if ( ! empty( $files ) ) {
77
			$file = $this->upload_from_file( $files, $headers );
78
		} else {
79
			$file = $this->upload_from_data( $request->get_body(), $headers );
80
		}
81
82
		if ( is_wp_error( $file ) ) {
83
			return $file;
84
		}
85
86
		$name       = basename( $file['file'] );
87
		$name_parts = pathinfo( $name );
88
		$name       = trim( substr( $name, 0, -(1 + strlen( $name_parts['extension'] ) ) ) );
89
90
		$url     = $file['url'];
91
		$type    = $file['type'];
92
		$file    = $file['file'];
93
94
		// use image exif/iptc data for title and caption defaults if possible
95
		// @codingStandardsIgnoreStart
96
		$image_meta = @wp_read_image_metadata( $file );
97
		// @codingStandardsIgnoreEnd
98
		if ( ! empty( $image_meta ) ) {
99
			if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
100
				$request['title'] = $image_meta['title'];
101
			}
102
103
			if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
104
				$request['caption'] = $image_meta['caption'];
105
			}
106
		}
107
108
		$attachment = $this->prepare_item_for_database( $request );
109
		$attachment->file = $file;
110
		$attachment->post_mime_type = $type;
111
		$attachment->guid = $url;
112
113
		if ( empty( $attachment->post_title ) ) {
114
			$attachment->post_title = preg_replace( '/\.[^.]+$/', '', basename( $file ) );
115
		}
116
117
		$id = wp_insert_post( $attachment, true );
118 View Code Duplication
		if ( is_wp_error( $id ) ) {
119
			if ( in_array( $id->get_error_code(), array( 'db_update_error' ) ) ) {
120
				$id->add_data( array( 'status' => 500 ) );
121
			} else {
122
				$id->add_data( array( 'status' => 400 ) );
123
			}
124
			return $id;
125
		}
126
		$attachment = $this->get_post( $id );
127
128
		/** Include admin functions to get access to wp_generate_attachment_metadata() */
129
		require_once ABSPATH . 'wp-admin/includes/admin.php';
130
131
		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
132
133
		if ( isset( $request['alt_text'] ) ) {
134
			update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
135
		}
136
137
		$fields_update = $this->update_additional_fields_for_object( $attachment, $request );
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->update_additional...$attachment, $request); of type boolean|WP_Error adds the type boolean to the return on line 139 which is incompatible with the return type documented by WP_REST_Attachments_Controller::create_item of type WP_Error|WP_REST_Response.
Loading history...
138
		if ( is_wp_error( $fields_update ) ) {
139
			return $fields_update;
140
		}
141
142
		$request->set_param( 'context', 'edit' );
143
		$response = $this->prepare_item_for_response( $attachment, $request );
144
		$response = rest_ensure_response( $response );
145
		$response->set_status( 201 );
146
		$response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $id ) ) );
147
148
		/**
149
		 * Fires after a single attachment is created or updated via the REST API.
150
		 *
151
		 * @param object          $attachment Inserted attachment.
152
		 * @param WP_REST_Request $request    The request sent to the API.
153
		 * @param boolean         $creating   True when creating an attachment, false when updating.
154
		 */
155
		do_action( 'rest_insert_attachment', $attachment, $request, true );
156
157
		return $response;
158
159
	}
160
161
	/**
162
	 * Update a single post
163
	 *
164
	 * @param WP_REST_Request $request Full details about the request
165
	 * @return WP_Error|WP_REST_Response
166
	 */
167
	public function update_item( $request ) {
168
		if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ) ) ) {
169
			return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
170
		}
171
		$response = parent::update_item( $request );
172
		if ( is_wp_error( $response ) ) {
173
			return $response;
174
		}
175
176
		$response = rest_ensure_response( $response );
177
		$data = $response->get_data();
178
179
		if ( isset( $request['alt_text'] ) ) {
180
			update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
181
		}
182
183
		$attachment = $this->get_post( $request['id'] );
184
		$request->set_param( 'context', 'edit' );
185
		$response = $this->prepare_item_for_response( $attachment, $request );
186
		$response = rest_ensure_response( $response );
187
188
		/* This action is documented in lib/endpoints/class-wp-rest-attachments-controller.php */
189
		do_action( 'rest_insert_attachment', $data, $request, false );
190
191
		return $response;
192
	}
193
194
	/**
195
	 * Prepare a single attachment for create or update
196
	 *
197
	 * @param WP_REST_Request $request Request object
198
	 * @return WP_Error|stdClass $prepared_attachment Post object
199
	 */
200
	protected function prepare_item_for_database( $request ) {
201
		$prepared_attachment = parent::prepare_item_for_database( $request );
202
203
		if ( isset( $request['caption'] ) ) {
204
			$prepared_attachment->post_excerpt = $request['caption'];
205
		}
206
207
		if ( isset( $request['description'] ) ) {
208
			$prepared_attachment->post_content = $request['description'];
209
		}
210
211
		if ( isset( $request['post'] ) ) {
212
			$prepared_attachment->post_parent = (int) $request['post'];
213
		}
214
215
		return $prepared_attachment;
216
	}
217
218
	/**
219
	 * Prepare a single attachment output for response
220
	 *
221
	 * @param WP_Post $post Post object
222
	 * @param WP_REST_Request $request Request object
223
	 * @return WP_REST_Response $response
224
	 */
225
	public function prepare_item_for_response( $post, $request ) {
226
		$response = parent::prepare_item_for_response( $post, $request );
227
		$data = $response->get_data();
228
229
		$data['alt_text']      = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
230
		$data['caption']       = $post->post_excerpt;
231
		$data['description']   = $post->post_content;
232
		$data['media_type']    = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
233
		$data['mime_type']     = $post->post_mime_type;
234
		$data['media_details'] = wp_get_attachment_metadata( $post->ID );
235
		$data['post']          = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
236
		$data['source_url']    = wp_get_attachment_url( $post->ID );
237
238
		// Ensure empty details is an empty object
239
		if ( empty( $data['media_details'] ) ) {
240
			$data['media_details'] = new stdClass;
241
		} elseif ( ! empty( $data['media_details']['sizes'] ) ) {
242
243
			foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
244
245
				if ( isset( $size_data['mime-type'] ) ) {
246
					$size_data['mime_type'] = $size_data['mime-type'];
247
					unset( $size_data['mime-type'] );
248
				}
249
250
				// Use the same method image_downsize() does
251
				$image_src = wp_get_attachment_image_src( $post->ID, $size );
252
				if ( ! $image_src ) {
253
					continue;
254
				}
255
256
				$size_data['source_url'] = $image_src[0];
257
			}
258
259
			$full_src = wp_get_attachment_image_src( $post->ID, 'full' );
260
			if ( ! empty( $full_src ) ) {
261
				$data['media_details']['sizes']['full'] = array(
262
					'file'          => wp_basename( $full_src[0] ),
263
					'width'         => $full_src[1],
264
					'height'        => $full_src[2],
265
					'mime_type'     => $post->post_mime_type,
266
					'source_url'    => $full_src[0],
267
					);
268
			}
269
		} else {
270
			$data['media_details']['sizes'] = new stdClass;
271
		}
272
273
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
274
275
		$data = $this->filter_response_by_context( $data, $context );
276
277
		// Wrap the data in a response object
278
		$response = rest_ensure_response( $data );
279
280
		$response->add_links( $this->prepare_links( $post ) );
281
282
		/**
283
		 * Filter an attachment returned from the API.
284
		 *
285
		 * Allows modification of the attachment right before it is returned.
286
		 *
287
		 * @param WP_REST_Response  $response   The response object.
288
		 * @param WP_Post           $post       The original attachment post.
289
		 * @param WP_REST_Request   $request    Request used to generate the response.
290
		 */
291
		return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
292
	}
293
294
	/**
295
	 * Get the Attachment's schema, conforming to JSON Schema
296
	 *
297
	 * @return array
298
	 */
299
	public function get_item_schema() {
300
301
		$schema = parent::get_item_schema();
302
303
		$schema['properties']['alt_text'] = array(
304
			'description'     => __( 'Alternative text to display when resource is not displayed.' ),
305
			'type'            => 'string',
306
			'context'         => array( 'view', 'edit', 'embed' ),
307
			'arg_options'     => array(
308
				'sanitize_callback' => 'sanitize_text_field',
309
			),
310
		);
311
		$schema['properties']['caption'] = array(
312
			'description'     => __( 'The caption for the resource.' ),
313
			'type'            => 'string',
314
			'context'         => array( 'view', 'edit' ),
315
			'arg_options'     => array(
316
				'sanitize_callback' => 'wp_filter_post_kses',
317
			),
318
		);
319
		$schema['properties']['description'] = array(
320
			'description'     => __( 'The description for the resource.' ),
321
			'type'            => 'string',
322
			'context'         => array( 'view', 'edit' ),
323
			'arg_options'     => array(
324
				'sanitize_callback' => 'wp_filter_post_kses',
325
			),
326
		);
327
		$schema['properties']['media_type'] = array(
328
			'description'     => __( 'Type of resource.' ),
329
			'type'            => 'string',
330
			'enum'            => array( 'image', 'file' ),
331
			'context'         => array( 'view', 'edit', 'embed' ),
332
			'readonly'        => true,
333
		);
334
		$schema['properties']['mime_type'] = array(
335
			'description'     => __( 'Mime type of resource.' ),
336
			'type'            => 'string',
337
			'context'         => array( 'view', 'edit', 'embed' ),
338
			'readonly'        => true,
339
		);
340
		$schema['properties']['media_details'] = array(
341
			'description'     => __( 'Details about the resource file, specific to its type.' ),
342
			'type'            => 'object',
343
			'context'         => array( 'view', 'edit', 'embed' ),
344
			'readonly'        => true,
345
		);
346
		$schema['properties']['post'] = array(
347
			'description'     => __( 'The id for the associated post of the resource.' ),
348
			'type'            => 'integer',
349
			'context'         => array( 'view', 'edit' ),
350
		);
351
		$schema['properties']['source_url'] = array(
352
			'description'     => __( 'URL to the original resource file.' ),
353
			'type'            => 'string',
354
			'format'          => 'uri',
355
			'context'         => array( 'view', 'edit', 'embed' ),
356
			'readonly'        => true,
357
		);
358
		return $schema;
359
	}
360
361
	/**
362
	 * Handle an upload via raw POST data
363
	 *
364
	 * @param array $data Supplied file data
365
	 * @param array $headers HTTP headers from the request
366
	 * @return array|WP_Error Data from {@see wp_handle_sideload()}
367
	 */
368
	protected function upload_from_data( $data, $headers ) {
369
		if ( empty( $data ) ) {
370
			return new WP_Error( 'rest_upload_no_data', __( 'No data supplied' ), array( 'status' => 400 ) );
371
		}
372
373
		if ( empty( $headers['content_type'] ) ) {
374
			return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied' ), array( 'status' => 400 ) );
375
		}
376
377
		if ( empty( $headers['content_disposition'] ) ) {
378
			return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied' ), array( 'status' => 400 ) );
379
		}
380
381
		$filename = $this->get_filename_from_disposition( $headers['content_disposition'] );
382
383
		if ( empty( $filename ) ) {
384
			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 ) );
385
		}
386
387 View Code Duplication
		if ( ! empty( $headers['content_md5'] ) ) {
388
			$content_md5 = array_shift( $headers['content_md5'] );
389
			$expected = trim( $content_md5 );
390
			$actual   = md5( $data );
391
392
			if ( $expected !== $actual ) {
393
				return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected' ), array( 'status' => 412 ) );
394
			}
395
		}
396
397
		// Get the content-type
398
		$type = array_shift( $headers['content_type'] );
399
400
		/** Include admin functions to get access to wp_tempnam() and wp_handle_sideload() */
401
		require_once ABSPATH . 'wp-admin/includes/admin.php';
402
403
		// Save the file
404
		$tmpfname = wp_tempnam( $filename );
405
406
		$fp = fopen( $tmpfname, 'w+' );
407
408
		if ( ! $fp ) {
409
			return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle' ), array( 'status' => 500 ) );
410
		}
411
412
		fwrite( $fp, $data );
413
		fclose( $fp );
414
415
		// Now, sideload it in
416
		$file_data = array(
417
			'error'    => null,
418
			'tmp_name' => $tmpfname,
419
			'name'     => $filename,
420
			'type'     => $type,
421
		);
422
		$overrides = array(
423
			'test_form' => false,
424
		);
425
		$sideloaded = wp_handle_sideload( $file_data, $overrides );
426
427
		if ( isset( $sideloaded['error'] ) ) {
428
			// @codingStandardsIgnoreStart
429
			@unlink( $tmpfname );
430
			// @codingStandardsIgnoreEnd
431
			return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
432
		}
433
434
		return $sideloaded;
435
	}
436
437
	/**
438
	 * Parse filename from a Content-Disposition header value.
439
	 *
440
	 * As per RFC6266:
441
	 *
442
	 *     content-disposition = "Content-Disposition" ":"
443
	 *                            disposition-type *( ";" disposition-parm )
444
	 *
445
	 *     disposition-type    = "inline" | "attachment" | disp-ext-type
446
	 *                         ; case-insensitive
447
	 *     disp-ext-type       = token
448
	 *
449
	 *     disposition-parm    = filename-parm | disp-ext-parm
450
	 *
451
	 *     filename-parm       = "filename" "=" value
452
	 *                         | "filename*" "=" ext-value
453
	 *
454
	 *     disp-ext-parm       = token "=" value
455
	 *                         | ext-token "=" ext-value
456
	 *     ext-token           = <the characters in token, followed by "*">
457
	 *
458
	 * @see http://tools.ietf.org/html/rfc2388
459
	 * @see http://tools.ietf.org/html/rfc6266
460
	 *
461
	 * @param string[] $disposition_header List of Content-Disposition header values.
462
	 * @return string|null Filename if available, or null if not found.
463
	 */
464
	public static function get_filename_from_disposition( $disposition_header ) {
465
		// Get the filename
466
		$filename = null;
467
468
		foreach ( $disposition_header as $value ) {
469
			$value = trim( $value );
470
471
			if ( strpos( $value, ';' ) === false ) {
472
				continue;
473
			}
474
475
			list( $type, $attr_parts ) = explode( ';', $value, 2 );
476
			$attr_parts = explode( ';', $attr_parts );
477
			$attributes = array();
478
			foreach ( $attr_parts as $part ) {
479
				if ( strpos( $part, '=' ) === false ) {
480
					continue;
481
				}
482
483
				list( $key, $value ) = explode( '=', $part, 2 );
484
				$attributes[ trim( $key ) ] = trim( $value );
485
			}
486
487
			if ( empty( $attributes['filename'] ) ) {
488
				continue;
489
			}
490
491
			$filename = trim( $attributes['filename'] );
492
493
			// Unquote quoted filename, but after trimming.
494
			if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
495
				$filename = substr( $filename, 1, -1 );
496
			}
497
		}
498
499
		return $filename;
500
	}
501
502
	/**
503
	 * Get the query params for collections of attachments.
504
	 *
505
	 * @return array
506
	 */
507
	public function get_collection_params() {
508
		$params = parent::get_collection_params();
509
		$params['status']['default'] = 'inherit';
510
		$params['status']['enum'] = array( 'inherit', 'private', 'trash' );
511
		$media_types = $this->get_media_types();
512
		$params['media_type'] = array(
513
			'default'            => null,
514
			'description'        => __( 'Limit result set to attachments of a particular media type.' ),
515
			'type'               => 'string',
516
			'enum'               => array_keys( $media_types ),
517
			'validate_callback'  => 'rest_validate_request_arg',
518
		);
519
		$params['mime_type'] = array(
520
			'default'            => null,
521
			'description'        => __( 'Limit result set to attachments of a particular mime type.' ),
522
			'type'               => 'string',
523
		);
524
		return $params;
525
	}
526
527
	/**
528
	 * Validate whether the user can query private statuses
529
	 *
530
	 * @param  mixed $value
531
	 * @param  WP_REST_Request $request
532
	 * @param  string $parameter
533
	 * @return WP_Error|boolean
534
	 */
535
	public function validate_user_can_query_private_statuses( $value, $request, $parameter ) {
536
		if ( 'inherit' === $value ) {
537
			return true;
538
		}
539
		return parent::validate_user_can_query_private_statuses( $value, $request, $parameter );
540
	}
541
542
	/**
543
	 * Handle an upload via multipart/form-data ($_FILES)
544
	 *
545
	 * @param array $files Data from $_FILES
546
	 * @param array $headers HTTP headers from the request
547
	 * @return array|WP_Error Data from {@see wp_handle_upload()}
548
	 */
549
	protected function upload_from_file( $files, $headers ) {
550
		if ( empty( $files ) ) {
551
			return new WP_Error( 'rest_upload_no_data', __( 'No data supplied' ), array( 'status' => 400 ) );
552
		}
553
554
		// Verify hash, if given
555 View Code Duplication
		if ( ! empty( $headers['content_md5'] ) ) {
556
			$content_md5 = array_shift( $headers['content_md5'] );
557
			$expected = trim( $content_md5 );
558
			$actual = md5_file( $files['file']['tmp_name'] );
559
			if ( $expected !== $actual ) {
560
				return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected' ), array( 'status' => 412 ) );
561
			}
562
		}
563
564
		// Pass off to WP to handle the actual upload
565
		$overrides = array(
566
			'test_form'   => false,
567
		);
568
		// Bypasses is_uploaded_file() when running unit tests
569
		if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
570
			$overrides['action'] = 'wp_handle_mock_upload';
571
		}
572
573
		/** Include admin functions to get access to wp_handle_upload() */
574
		require_once ABSPATH . 'wp-admin/includes/admin.php';
575
		$file = wp_handle_upload( $files['file'], $overrides );
576
577
		if ( isset( $file['error'] ) ) {
578
			return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
579
		}
580
581
		return $file;
582
	}
583
584
	/**
585
	 * Get the supported media types.
586
	 * Media types are considered the mime type category
587
	 *
588
	 * @return array
589
	 */
590
	protected function get_media_types() {
591
		$media_types = array();
592
		foreach ( get_allowed_mime_types() as $mime_type ) {
593
			$parts = explode( '/', $mime_type );
594
			if ( ! isset( $media_types[ $parts[0] ] ) ) {
595
				$media_types[ $parts[0] ] = array();
596
			}
597
			$media_types[ $parts[0] ][] = $mime_type;
598
		}
599
		return $media_types;
600
	}
601
602
}
603