c037ae2107d9de3cf05919f3d01e2ea56e389673
[autoinstalls/wordpress.git] / wp-includes / rest-api / endpoints / class-wp-rest-posts-controller.php
1 <?php
2 /**
3  * REST API: WP_REST_Posts_Controller class
4  *
5  * @package WordPress
6  * @subpackage REST_API
7  * @since 4.7.0
8  */
9
10 /**
11  * Core class to access posts via the REST API.
12  *
13  * @since 4.7.0
14  *
15  * @see WP_REST_Controller
16  */
17 class WP_REST_Posts_Controller extends WP_REST_Controller {
18
19         /**
20          * Post type.
21          *
22          * @since 4.7.0
23          * @access protected
24          * @var string
25          */
26         protected $post_type;
27
28         /**
29          * Instance of a post meta fields object.
30          *
31          * @since 4.7.0
32          * @access protected
33          * @var WP_REST_Post_Meta_Fields
34          */
35         protected $meta;
36
37         /**
38          * Constructor.
39          *
40          * @since 4.7.0
41          * @access public
42          *
43          * @param string $post_type Post type.
44          */
45         public function __construct( $post_type ) {
46                 $this->post_type = $post_type;
47                 $this->namespace = 'wp/v2';
48                 $obj = get_post_type_object( $post_type );
49                 $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
50
51                 $this->meta = new WP_REST_Post_Meta_Fields( $this->post_type );
52         }
53
54         /**
55          * Registers the routes for the objects of the controller.
56          *
57          * @since 4.7.0
58          * @access public
59          *
60          * @see register_rest_route()
61          */
62         public function register_routes() {
63
64                 register_rest_route( $this->namespace, '/' . $this->rest_base, array(
65                         array(
66                                 'methods'             => WP_REST_Server::READABLE,
67                                 'callback'            => array( $this, 'get_items' ),
68                                 'permission_callback' => array( $this, 'get_items_permissions_check' ),
69                                 'args'                => $this->get_collection_params(),
70                         ),
71                         array(
72                                 'methods'             => WP_REST_Server::CREATABLE,
73                                 'callback'            => array( $this, 'create_item' ),
74                                 'permission_callback' => array( $this, 'create_item_permissions_check' ),
75                                 'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
76                         ),
77                         'schema' => array( $this, 'get_public_item_schema' ),
78                 ) );
79
80                 $schema = $this->get_item_schema();
81                 $get_item_args = array(
82                         'context'  => $this->get_context_param( array( 'default' => 'view' ) ),
83                 );
84                 if ( isset( $schema['properties']['password'] ) ) {
85                         $get_item_args['password'] = array(
86                                 'description' => __( 'The password for the post if it is password protected.' ),
87                                 'type'        => 'string',
88                         );
89                 }
90                 register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
91                         array(
92                                 'methods'             => WP_REST_Server::READABLE,
93                                 'callback'            => array( $this, 'get_item' ),
94                                 'permission_callback' => array( $this, 'get_item_permissions_check' ),
95                                 'args'                => $get_item_args,
96                         ),
97                         array(
98                                 'methods'             => WP_REST_Server::EDITABLE,
99                                 'callback'            => array( $this, 'update_item' ),
100                                 'permission_callback' => array( $this, 'update_item_permissions_check' ),
101                                 'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
102                         ),
103                         array(
104                                 'methods'             => WP_REST_Server::DELETABLE,
105                                 'callback'            => array( $this, 'delete_item' ),
106                                 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
107                                 'args'                => array(
108                                         'force' => array(
109                                                 'type'        => 'boolean',
110                                                 'default'     => false,
111                                                 'description' => __( 'Whether to bypass trash and force deletion.' ),
112                                         ),
113                                 ),
114                         ),
115                         'schema' => array( $this, 'get_public_item_schema' ),
116                 ) );
117         }
118
119         /**
120          * Checks if a given request has access to read posts.
121          *
122          * @since 4.7.0
123          * @access public
124          *
125          * @param  WP_REST_Request $request Full details about the request.
126          * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
127          */
128         public function get_items_permissions_check( $request ) {
129
130                 $post_type = get_post_type_object( $this->post_type );
131
132                 if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) {
133                         return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) );
134                 }
135
136                 return true;
137         }
138
139         /**
140          * Retrieves a collection of posts.
141          *
142          * @since 4.7.0
143          * @access public
144          *
145          * @param WP_REST_Request $request Full details about the request.
146          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
147          */
148         public function get_items( $request ) {
149
150                 // Ensure a search string is set in case the orderby is set to 'relevance'.
151                 if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
152                         return new WP_Error( 'rest_no_search_term_defined', __( 'You need to define a search term to order by relevance.' ), array( 'status' => 400 ) );
153                 }
154
155                 // Ensure an include parameter is set in case the orderby is set to 'include'.
156                 if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
157                         return new WP_Error( 'rest_orderby_include_missing_include', sprintf( __( 'Missing parameter(s): %s' ), 'include' ), array( 'status' => 400 ) );
158                 }
159
160                 // Retrieve the list of registered collection query parameters.
161                 $registered = $this->get_collection_params();
162                 $args = array();
163
164                 /*
165                  * This array defines mappings between public API query parameters whose
166                  * values are accepted as-passed, and their internal WP_Query parameter
167                  * name equivalents (some are the same). Only values which are also
168                  * present in $registered will be set.
169                  */
170                 $parameter_mappings = array(
171                         'author'         => 'author__in',
172                         'author_exclude' => 'author__not_in',
173                         'exclude'        => 'post__not_in',
174                         'include'        => 'post__in',
175                         'menu_order'     => 'menu_order',
176                         'offset'         => 'offset',
177                         'order'          => 'order',
178                         'orderby'        => 'orderby',
179                         'page'           => 'paged',
180                         'parent'         => 'post_parent__in',
181                         'parent_exclude' => 'post_parent__not_in',
182                         'search'         => 's',
183                         'slug'           => 'post_name__in',
184                         'status'         => 'post_status',
185                 );
186
187                 /*
188                  * For each known parameter which is both registered and present in the request,
189                  * set the parameter's value on the query $args.
190                  */
191                 foreach ( $parameter_mappings as $api_param => $wp_param ) {
192                         if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
193                                 $args[ $wp_param ] = $request[ $api_param ];
194                         }
195                 }
196
197                 // Check for & assign any parameters which require special handling or setting.
198                 $args['date_query'] = array();
199
200                 // Set before into date query. Date query must be specified as an array of an array.
201                 if ( isset( $registered['before'], $request['before'] ) ) {
202                         $args['date_query'][0]['before'] = $request['before'];
203                 }
204
205                 // Set after into date query. Date query must be specified as an array of an array.
206                 if ( isset( $registered['after'], $request['after'] ) ) {
207                         $args['date_query'][0]['after'] = $request['after'];
208                 }
209
210                 // Ensure our per_page parameter overrides any provided posts_per_page filter.
211                 if ( isset( $registered['per_page'] ) ) {
212                         $args['posts_per_page'] = $request['per_page'];
213                 }
214
215                 if ( isset( $registered['sticky'], $request['sticky'] ) ) {
216                         $sticky_posts = get_option( 'sticky_posts', array() );
217                         if ( $sticky_posts && $request['sticky'] ) {
218                                 /*
219                                  * As post__in will be used to only get sticky posts,
220                                  * we have to support the case where post__in was already
221                                  * specified.
222                                  */
223                                 $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts;
224
225                                 /*
226                                  * If we intersected, but there are no post ids in common,
227                                  * WP_Query won't return "no posts" for post__in = array()
228                                  * so we have to fake it a bit.
229                                  */
230                                 if ( ! $args['post__in'] ) {
231                                         $args['post__in'] = array( -1 );
232                                 }
233                         } elseif ( $sticky_posts ) {
234                                 /*
235                                  * As post___not_in will be used to only get posts that
236                                  * are not sticky, we have to support the case where post__not_in
237                                  * was already specified.
238                                  */
239                                 $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts );
240                         }
241                 }
242
243                 // Force the post_type argument, since it's not a user input variable.
244                 $args['post_type'] = $this->post_type;
245
246                 /**
247                  * Filters the query arguments for a request.
248                  *
249                  * Enables adding extra arguments or setting defaults for a post collection request.
250                  *
251                  * @since 4.7.0
252                  *
253                  * @link https://developer.wordpress.org/reference/classes/wp_query/
254                  *
255                  * @param array           $args    Key value array of query var to query value.
256                  * @param WP_REST_Request $request The request used.
257                  */
258                 $args = apply_filters( "rest_{$this->post_type}_query", $args, $request );
259                 $query_args = $this->prepare_items_query( $args, $request );
260
261                 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
262
263                 foreach ( $taxonomies as $taxonomy ) {
264                         $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
265                         $tax_exclude = $base . '_exclude';
266
267                         if ( ! empty( $request[ $base ] ) ) {
268                                 $query_args['tax_query'][] = array(
269                                         'taxonomy'         => $taxonomy->name,
270                                         'field'            => 'term_id',
271                                         'terms'            => $request[ $base ],
272                                         'include_children' => false,
273                                 );
274                         }
275
276                         if ( ! empty( $request[ $tax_exclude ] ) ) {
277                                 $query_args['tax_query'][] = array(
278                                         'taxonomy'         => $taxonomy->name,
279                                         'field'            => 'term_id',
280                                         'terms'            => $request[ $tax_exclude ],
281                                         'include_children' => false,
282                                         'operator'         => 'NOT IN',
283                                 );
284                         }
285                 }
286
287                 $posts_query  = new WP_Query();
288                 $query_result = $posts_query->query( $query_args );
289
290                 // Allow access to all password protected posts if the context is edit.
291                 if ( 'edit' === $request['context'] ) {
292                         add_filter( 'post_password_required', '__return_false' );
293                 }
294
295                 $posts = array();
296
297                 foreach ( $query_result as $post ) {
298                         if ( ! $this->check_read_permission( $post ) ) {
299                                 continue;
300                         }
301
302                         $data    = $this->prepare_item_for_response( $post, $request );
303                         $posts[] = $this->prepare_response_for_collection( $data );
304                 }
305
306                 // Reset filter.
307                 if ( 'edit' === $request['context'] ) {
308                         remove_filter( 'post_password_required', '__return_false' );
309                 }
310
311                 $page = (int) $query_args['paged'];
312                 $total_posts = $posts_query->found_posts;
313
314                 if ( $total_posts < 1 ) {
315                         // Out-of-bounds, run the query again without LIMIT for total count.
316                         unset( $query_args['paged'] );
317
318                         $count_query = new WP_Query();
319                         $count_query->query( $query_args );
320                         $total_posts = $count_query->found_posts;
321                 }
322
323                 $max_pages = ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );
324                 $response  = rest_ensure_response( $posts );
325
326                 $response->header( 'X-WP-Total', (int) $total_posts );
327                 $response->header( 'X-WP-TotalPages', (int) $max_pages );
328
329                 $request_params = $request->get_query_params();
330                 $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
331
332                 if ( $page > 1 ) {
333                         $prev_page = $page - 1;
334
335                         if ( $prev_page > $max_pages ) {
336                                 $prev_page = $max_pages;
337                         }
338
339                         $prev_link = add_query_arg( 'page', $prev_page, $base );
340                         $response->link_header( 'prev', $prev_link );
341                 }
342                 if ( $max_pages > $page ) {
343                         $next_page = $page + 1;
344                         $next_link = add_query_arg( 'page', $next_page, $base );
345
346                         $response->link_header( 'next', $next_link );
347                 }
348
349                 return $response;
350         }
351
352         /**
353          * Checks if a given request has access to read a post.
354          *
355          * @since 4.7.0
356          * @access public
357          *
358          * @param WP_REST_Request $request Full details about the request.
359          * @return bool|WP_Error True if the request has read access for the item, WP_Error object otherwise.
360          */
361         public function get_item_permissions_check( $request ) {
362
363                 $post = get_post( (int) $request['id'] );
364
365                 if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
366                         return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
367                 }
368
369                 if ( $post && ! empty( $request['password'] ) ) {
370                         // Check post password, and return error if invalid.
371                         if ( ! hash_equals( $post->post_password, $request['password'] ) ) {
372                                 return new WP_Error( 'rest_post_incorrect_password', __( 'Incorrect post password.' ), array( 'status' => 403 ) );
373                         }
374                 }
375
376                 // Allow access to all password protected posts if the context is edit.
377                 if ( 'edit' === $request['context'] ) {
378                         add_filter( 'post_password_required', '__return_false' );
379                 }
380
381                 if ( $post ) {
382                         return $this->check_read_permission( $post );
383                 }
384
385                 return true;
386         }
387
388         /**
389          * Checks if the user can access password-protected content.
390          *
391          * This method determines whether we need to override the regular password
392          * check in core with a filter.
393          *
394          * @since 4.7.0
395          * @access public
396          *
397          * @param WP_Post         $post    Post to check against.
398          * @param WP_REST_Request $request Request data to check.
399          * @return bool True if the user can access password-protected content, otherwise false.
400          */
401         public function can_access_password_content( $post, $request ) {
402                 if ( empty( $post->post_password ) ) {
403                         // No filter required.
404                         return false;
405                 }
406
407                 // Edit context always gets access to password-protected posts.
408                 if ( 'edit' === $request['context'] ) {
409                         return true;
410                 }
411
412                 // No password, no auth.
413                 if ( empty( $request['password'] ) ) {
414                         return false;
415                 }
416
417                 // Double-check the request password.
418                 return hash_equals( $post->post_password, $request['password'] );
419         }
420
421         /**
422          * Retrieves a single post.
423          *
424          * @since 4.7.0
425          * @access public
426          *
427          * @param WP_REST_Request $request Full details about the request.
428          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
429          */
430         public function get_item( $request ) {
431                 $id   = (int) $request['id'];
432                 $post = get_post( $id );
433
434                 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
435                         return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
436                 }
437
438                 $data     = $this->prepare_item_for_response( $post, $request );
439                 $response = rest_ensure_response( $data );
440
441                 if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) {
442                         $response->link_header( 'alternate',  get_permalink( $id ), array( 'type' => 'text/html' ) );
443                 }
444
445                 return $response;
446         }
447
448         /**
449          * Checks if a given request has access to create a post.
450          *
451          * @since 4.7.0
452          * @access public
453          *
454          * @param WP_REST_Request $request Full details about the request.
455          * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise.
456          */
457         public function create_item_permissions_check( $request ) {
458
459                 $post_type = get_post_type_object( $this->post_type );
460
461                 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
462                         return new WP_Error( 'rest_cannot_edit_others', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
463                 }
464
465                 if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
466                         return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
467                 }
468
469                 if ( ! current_user_can( $post_type->cap->create_posts ) ) {
470                         return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
471                 }
472
473                 if ( ! $this->check_assign_terms_permission( $request ) ) {
474                         return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
475                 }
476
477                 return true;
478         }
479
480         /**
481          * Creates a single post.
482          *
483          * @since 4.7.0
484          * @access public
485          *
486          * @param WP_REST_Request $request Full details about the request.
487          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
488          */
489         public function create_item( $request ) {
490                 if ( ! empty( $request['id'] ) ) {
491                         return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) );
492                 }
493
494                 $prepared_post = $this->prepare_item_for_database( $request );
495
496                 if ( is_wp_error( $prepared_post ) ) {
497                         return $prepared_post;
498                 }
499
500                 $prepared_post->post_type = $this->post_type;
501
502                 $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true );
503
504                 if ( is_wp_error( $post_id ) ) {
505
506                         if ( 'db_insert_error' === $post_id->get_error_code() ) {
507                                 $post_id->add_data( array( 'status' => 500 ) );
508                         } else {
509                                 $post_id->add_data( array( 'status' => 400 ) );
510                         }
511
512                         return $post_id;
513                 }
514
515                 $post = get_post( $post_id );
516
517                 /**
518                  * Fires after a single post is created or updated via the REST API.
519                  *
520                  * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
521                  *
522                  * @since 4.7.0
523                  *
524                  * @param WP_Post         $post     Inserted or updated post object.
525                  * @param WP_REST_Request $request  Request object.
526                  * @param bool            $creating True when creating a post, false when updating.
527                  */
528                 do_action( "rest_insert_{$this->post_type}", $post, $request, true );
529
530                 $schema = $this->get_item_schema();
531
532                 if ( ! empty( $schema['properties']['sticky'] ) ) {
533                         if ( ! empty( $request['sticky'] ) ) {
534                                 stick_post( $post_id );
535                         } else {
536                                 unstick_post( $post_id );
537                         }
538                 }
539
540                 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
541                         $this->handle_featured_media( $request['featured_media'], $post_id );
542                 }
543
544                 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
545                         set_post_format( $post, $request['format'] );
546                 }
547
548                 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
549                         $this->handle_template( $request['template'], $post_id );
550                 }
551
552                 $terms_update = $this->handle_terms( $post_id, $request );
553
554                 if ( is_wp_error( $terms_update ) ) {
555                         return $terms_update;
556                 }
557
558                 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
559                         $meta_update = $this->meta->update_value( $request['meta'], $post_id );
560
561                         if ( is_wp_error( $meta_update ) ) {
562                                 return $meta_update;
563                         }
564                 }
565
566                 $post = get_post( $post_id );
567                 $fields_update = $this->update_additional_fields_for_object( $post, $request );
568
569                 if ( is_wp_error( $fields_update ) ) {
570                         return $fields_update;
571                 }
572
573                 $request->set_param( 'context', 'edit' );
574
575                 $response = $this->prepare_item_for_response( $post, $request );
576                 $response = rest_ensure_response( $response );
577
578                 $response->set_status( 201 );
579                 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $post_id ) ) );
580
581                 return $response;
582         }
583
584         /**
585          * Checks if a given request has access to update a post.
586          *
587          * @since 4.7.0
588          * @access public
589          *
590          * @param WP_REST_Request $request Full details about the request.
591          * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
592          */
593         public function update_item_permissions_check( $request ) {
594
595                 $post = get_post( $request['id'] );
596                 $post_type = get_post_type_object( $this->post_type );
597
598                 if ( $post && ! $this->check_update_permission( $post ) ) {
599                         return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
600                 }
601
602                 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
603                         return new WP_Error( 'rest_cannot_edit_others', __( 'Sorry, you are not allowed to update posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
604                 }
605
606                 if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
607                         return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
608                 }
609
610                 if ( ! $this->check_assign_terms_permission( $request ) ) {
611                         return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
612                 }
613
614                 return true;
615         }
616
617         /**
618          * Updates a single post.
619          *
620          * @since 4.7.0
621          * @access public
622          *
623          * @param WP_REST_Request $request Full details about the request.
624          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
625          */
626         public function update_item( $request ) {
627                 $id   = (int) $request['id'];
628                 $post = get_post( $id );
629
630                 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
631                         return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
632                 }
633
634                 $post = $this->prepare_item_for_database( $request );
635
636                 if ( is_wp_error( $post ) ) {
637                         return $post;
638                 }
639
640                 // convert the post object to an array, otherwise wp_update_post will expect non-escaped input.
641                 $post_id = wp_update_post( wp_slash( (array) $post ), true );
642
643                 if ( is_wp_error( $post_id ) ) {
644                         if ( 'db_update_error' === $post_id->get_error_code() ) {
645                                 $post_id->add_data( array( 'status' => 500 ) );
646                         } else {
647                                 $post_id->add_data( array( 'status' => 400 ) );
648                         }
649                         return $post_id;
650                 }
651
652                 $post = get_post( $post_id );
653
654                 /* This action is documented in lib/endpoints/class-wp-rest-controller.php */
655                 do_action( "rest_insert_{$this->post_type}", $post, $request, false );
656
657                 $schema = $this->get_item_schema();
658
659                 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
660                         set_post_format( $post, $request['format'] );
661                 }
662
663                 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
664                         $this->handle_featured_media( $request['featured_media'], $post_id );
665                 }
666
667                 if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) {
668                         if ( ! empty( $request['sticky'] ) ) {
669                                 stick_post( $post_id );
670                         } else {
671                                 unstick_post( $post_id );
672                         }
673                 }
674
675                 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
676                         $this->handle_template( $request['template'], $post->ID );
677                 }
678
679                 $terms_update = $this->handle_terms( $post->ID, $request );
680
681                 if ( is_wp_error( $terms_update ) ) {
682                         return $terms_update;
683                 }
684
685                 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
686                         $meta_update = $this->meta->update_value( $request['meta'], $post->ID );
687
688                         if ( is_wp_error( $meta_update ) ) {
689                                 return $meta_update;
690                         }
691                 }
692
693                 $post = get_post( $post_id );
694                 $fields_update = $this->update_additional_fields_for_object( $post, $request );
695
696                 if ( is_wp_error( $fields_update ) ) {
697                         return $fields_update;
698                 }
699
700                 $request->set_param( 'context', 'edit' );
701
702                 $response = $this->prepare_item_for_response( $post, $request );
703
704                 return rest_ensure_response( $response );
705         }
706
707         /**
708          * Checks if a given request has access to delete a post.
709          *
710          * @since 4.7.0
711          * @access public
712          *
713          * @param WP_REST_Request $request Full details about the request.
714          * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
715          */
716         public function delete_item_permissions_check( $request ) {
717
718                 $post = get_post( $request['id'] );
719
720                 if ( $post && ! $this->check_delete_permission( $post ) ) {
721                         return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
722                 }
723
724                 return true;
725         }
726
727         /**
728          * Deletes a single post.
729          *
730          * @since 4.7.0
731          * @access public
732          *
733          * @param WP_REST_Request $request Full details about the request.
734          * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
735          */
736         public function delete_item( $request ) {
737                 $id    = (int) $request['id'];
738                 $force = (bool) $request['force'];
739
740                 $post = get_post( $id );
741
742                 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
743                         return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
744                 }
745
746                 $supports_trash = ( EMPTY_TRASH_DAYS > 0 );
747
748                 if ( 'attachment' === $post->post_type ) {
749                         $supports_trash = $supports_trash && MEDIA_TRASH;
750                 }
751
752                 /**
753                  * Filters whether a post is trashable.
754                  *
755                  * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
756                  *
757                  * Pass false to disable trash support for the post.
758                  *
759                  * @since 4.7.0
760                  *
761                  * @param bool    $supports_trash Whether the post type support trashing.
762                  * @param WP_Post $post           The Post object being considered for trashing support.
763                  */
764                 $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post );
765
766                 if ( ! $this->check_delete_permission( $post ) ) {
767                         return new WP_Error( 'rest_user_cannot_delete_post', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
768                 }
769
770                 $request->set_param( 'context', 'edit' );
771
772
773                 // If we're forcing, then delete permanently.
774                 if ( $force ) {
775                         $previous = $this->prepare_item_for_response( $post, $request );
776                         $result = wp_delete_post( $id, true );
777                         $response = new WP_REST_Response();
778                         $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
779                 } else {
780                         // If we don't support trashing for this type, error out.
781                         if ( ! $supports_trash ) {
782                                 return new WP_Error( 'rest_trash_not_supported', __( 'The post does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
783                         }
784
785                         // Otherwise, only trash if we haven't already.
786                         if ( 'trash' === $post->post_status ) {
787                                 return new WP_Error( 'rest_already_trashed', __( 'The post has already been deleted.' ), array( 'status' => 410 ) );
788                         }
789
790                         // (Note that internally this falls through to `wp_delete_post` if
791                         // the trash is disabled.)
792                         $result = wp_trash_post( $id );
793                         $post = get_post( $id );
794                         $response = $this->prepare_item_for_response( $post, $request );
795                 }
796
797                 if ( ! $result ) {
798                         return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) );
799                 }
800
801                 /**
802                  * Fires immediately after a single post is deleted or trashed via the REST API.
803                  *
804                  * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
805                  *
806                  * @since 4.7.0
807                  *
808                  * @param object           $post     The deleted or trashed post.
809                  * @param WP_REST_Response $response The response data.
810                  * @param WP_REST_Request  $request  The request sent to the API.
811                  */
812                 do_action( "rest_delete_{$this->post_type}", $post, $response, $request );
813
814                 return $response;
815         }
816
817         /**
818          * Determines the allowed query_vars for a get_items() response and prepares
819          * them for WP_Query.
820          *
821          * @since 4.7.0
822          * @access protected
823          *
824          * @param array           $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
825          * @param WP_REST_Request $request       Optional. Full details about the request.
826          * @return array Items query arguments.
827          */
828         protected function prepare_items_query( $prepared_args = array(), $request = null ) {
829                 $query_args = array();
830
831                 foreach ( $prepared_args as $key => $value ) {
832                         /**
833                          * Filters the query_vars used in get_items() for the constructed query.
834                          *
835                          * The dynamic portion of the hook name, `$key`, refers to the query_var key.
836                          *
837                          * @since 4.7.0
838                          *
839                          * @param string $value The query_var value.
840                          */
841                         $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value );
842                 }
843
844                 if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) {
845                         $query_args['ignore_sticky_posts'] = true;
846                 }
847
848                 // Map to proper WP_Query orderby param.
849                 if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
850                         $orderby_mappings = array(
851                                 'id'      => 'ID',
852                                 'include' => 'post__in',
853                                 'slug'    => 'post_name',
854                         );
855
856                         if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
857                                 $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
858                         }
859                 }
860
861                 return $query_args;
862         }
863
864         /**
865          * Checks the post_date_gmt or modified_gmt and prepare any post or
866          * modified date for single post output.
867          *
868          * @since 4.7.0
869          * @access protected
870          *
871          * @param string      $date_gmt GMT publication time.
872          * @param string|null $date     Optional. Local publication time. Default null.
873          * @return string|null ISO8601/RFC3339 formatted datetime.
874          */
875         protected function prepare_date_response( $date_gmt, $date = null ) {
876                 // Use the date if passed.
877                 if ( isset( $date ) ) {
878                         return mysql_to_rfc3339( $date );
879                 }
880
881                 // Return null if $date_gmt is empty/zeros.
882                 if ( '0000-00-00 00:00:00' === $date_gmt ) {
883                         return null;
884                 }
885
886                 // Return the formatted datetime.
887                 return mysql_to_rfc3339( $date_gmt );
888         }
889
890         /**
891          * Prepares a single post for create or update.
892          *
893          * @since 4.7.0
894          * @access protected
895          *
896          * @param WP_REST_Request $request Request object.
897          * @return stdClass|WP_Error Post object or WP_Error.
898          */
899         protected function prepare_item_for_database( $request ) {
900                 $prepared_post = new stdClass;
901
902                 // Post ID.
903                 if ( isset( $request['id'] ) ) {
904                         $prepared_post->ID = absint( $request['id'] );
905                 }
906
907                 $schema = $this->get_item_schema();
908
909                 // Post title.
910                 if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
911                         if ( is_string( $request['title'] ) ) {
912                                 $prepared_post->post_title = $request['title'];
913                         } elseif ( ! empty( $request['title']['raw'] ) ) {
914                                 $prepared_post->post_title = $request['title']['raw'];
915                         }
916                 }
917
918                 // Post content.
919                 if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) {
920                         if ( is_string( $request['content'] ) ) {
921                                 $prepared_post->post_content = $request['content'];
922                         } elseif ( isset( $request['content']['raw'] ) ) {
923                                 $prepared_post->post_content = $request['content']['raw'];
924                         }
925                 }
926
927                 // Post excerpt.
928                 if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) {
929                         if ( is_string( $request['excerpt'] ) ) {
930                                 $prepared_post->post_excerpt = $request['excerpt'];
931                         } elseif ( isset( $request['excerpt']['raw'] ) ) {
932                                 $prepared_post->post_excerpt = $request['excerpt']['raw'];
933                         }
934                 }
935
936                 // Post type.
937                 if ( empty( $request['id'] ) ) {
938                         // Creating new post, use default type for the controller.
939                         $prepared_post->post_type = $this->post_type;
940                 } else {
941                         // Updating a post, use previous type.
942                         $prepared_post->post_type = get_post_type( $request['id'] );
943                 }
944
945                 $post_type = get_post_type_object( $prepared_post->post_type );
946
947                 // Post status.
948                 if ( ! empty( $schema['properties']['status'] ) && isset( $request['status'] ) ) {
949                         $status = $this->handle_status_param( $request['status'], $post_type );
950
951                         if ( is_wp_error( $status ) ) {
952                                 return $status;
953                         }
954
955                         $prepared_post->post_status = $status;
956                 }
957
958                 // Post date.
959                 if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) {
960                         $date_data = rest_get_date_with_gmt( $request['date'] );
961
962                         if ( ! empty( $date_data ) ) {
963                                 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
964                         }
965                 } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) {
966                         $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
967
968                         if ( ! empty( $date_data ) ) {
969                                 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
970                         }
971                 }
972
973                 // Post slug.
974                 if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) {
975                         $prepared_post->post_name = $request['slug'];
976                 }
977
978                 // Author.
979                 if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) {
980                         $post_author = (int) $request['author'];
981
982                         if ( get_current_user_id() !== $post_author ) {
983                                 $user_obj = get_userdata( $post_author );
984
985                                 if ( ! $user_obj ) {
986                                         return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), array( 'status' => 400 ) );
987                                 }
988                         }
989
990                         $prepared_post->post_author = $post_author;
991                 }
992
993                 // Post password.
994                 if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) {
995                         $prepared_post->post_password = $request['password'];
996
997                         if ( '' !== $request['password'] ) {
998                                 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
999                                         return new WP_Error( 'rest_invalid_field', __( 'A post can not be sticky and have a password.' ), array( 'status' => 400 ) );
1000                                 }
1001
1002                                 if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) {
1003                                         return new WP_Error( 'rest_invalid_field', __( 'A sticky post can not be password protected.' ), array( 'status' => 400 ) );
1004                                 }
1005                         }
1006                 }
1007
1008                 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
1009                         if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) {
1010                                 return new WP_Error( 'rest_invalid_field', __( 'A password protected post can not be set to sticky.' ), array( 'status' => 400 ) );
1011                         }
1012                 }
1013
1014                 // Parent.
1015                 if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) {
1016                         if ( 0 === (int) $request['parent'] ) {
1017                                 $prepared_post->post_parent = 0;
1018                         } else {
1019                                 $parent = get_post( (int) $request['parent'] );
1020                                 if ( empty( $parent ) ) {
1021                                         return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post parent ID.' ), array( 'status' => 400 ) );
1022                                 }
1023                                 $prepared_post->post_parent = (int) $parent->ID;
1024                         }
1025                 }
1026
1027                 // Menu order.
1028                 if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) {
1029                         $prepared_post->menu_order = (int) $request['menu_order'];
1030                 }
1031
1032                 // Comment status.
1033                 if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) {
1034                         $prepared_post->comment_status = $request['comment_status'];
1035                 }
1036
1037                 // Ping status.
1038                 if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) {
1039                         $prepared_post->ping_status = $request['ping_status'];
1040                 }
1041
1042                 /**
1043                  * Filters a post before it is inserted via the REST API.
1044                  *
1045                  * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1046                  *
1047                  * @since 4.7.0
1048                  *
1049                  * @param stdClass        $prepared_post An object representing a single post prepared
1050                  *                                       for inserting or updating the database.
1051                  * @param WP_REST_Request $request       Request object.
1052                  */
1053                 return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request );
1054
1055         }
1056
1057         /**
1058          * Determines validity and normalizes the given status parameter.
1059          *
1060          * @since 4.7.0
1061          * @access protected
1062          *
1063          * @param string $post_status Post status.
1064          * @param object $post_type   Post type.
1065          * @return string|WP_Error Post status or WP_Error if lacking the proper permission.
1066          */
1067         protected function handle_status_param( $post_status, $post_type ) {
1068
1069                 switch ( $post_status ) {
1070                         case 'draft':
1071                         case 'pending':
1072                                 break;
1073                         case 'private':
1074                                 if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1075                                         return new WP_Error( 'rest_cannot_publish', __( 'Sorry, you are not allowed to create private posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) );
1076                                 }
1077                                 break;
1078                         case 'publish':
1079                         case 'future':
1080                                 if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1081                                         return new WP_Error( 'rest_cannot_publish', __( 'Sorry, you are not allowed to publish posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) );
1082                                 }
1083                                 break;
1084                         default:
1085                                 if ( ! get_post_status_object( $post_status ) ) {
1086                                         $post_status = 'draft';
1087                                 }
1088                                 break;
1089                 }
1090
1091                 return $post_status;
1092         }
1093
1094         /**
1095          * Determines the featured media based on a request param.
1096          *
1097          * @since 4.7.0
1098          * @access protected
1099          *
1100          * @param int $featured_media Featured Media ID.
1101          * @param int $post_id        Post ID.
1102          * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
1103          */
1104         protected function handle_featured_media( $featured_media, $post_id ) {
1105
1106                 $featured_media = (int) $featured_media;
1107                 if ( $featured_media ) {
1108                         $result = set_post_thumbnail( $post_id, $featured_media );
1109                         if ( $result ) {
1110                                 return true;
1111                         } else {
1112                                 return new WP_Error( 'rest_invalid_featured_media', __( 'Invalid featured media ID.' ), array( 'status' => 400 ) );
1113                         }
1114                 } else {
1115                         return delete_post_thumbnail( $post_id );
1116                 }
1117
1118         }
1119
1120         /**
1121          * Sets the template for a post.
1122          *
1123          * @since 4.7.0
1124          * @access public
1125          *
1126          * @param string  $template Page template filename.
1127          * @param integer $post_id  Post ID.
1128          */
1129         public function handle_template( $template, $post_id ) {
1130                 if ( in_array( $template, array_keys( wp_get_theme()->get_page_templates( get_post( $post_id ) ) ), true ) ) {
1131                         update_post_meta( $post_id, '_wp_page_template', $template );
1132                 } else {
1133                         update_post_meta( $post_id, '_wp_page_template', '' );
1134                 }
1135         }
1136
1137         /**
1138          * Updates the post's terms from a REST request.
1139          *
1140          * @since 4.7.0
1141          * @access protected
1142          *
1143          * @param int             $post_id The post ID to update the terms form.
1144          * @param WP_REST_Request $request The request object with post and terms data.
1145          * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null.
1146          */
1147         protected function handle_terms( $post_id, $request ) {
1148                 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1149
1150                 foreach ( $taxonomies as $taxonomy ) {
1151                         $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1152
1153                         if ( ! isset( $request[ $base ] ) ) {
1154                                 continue;
1155                         }
1156
1157                         $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name );
1158
1159                         if ( is_wp_error( $result ) ) {
1160                                 return $result;
1161                         }
1162                 }
1163         }
1164
1165         /**
1166          * Checks whether current user can assign all terms sent with the current request.
1167          *
1168          * @since 4.7.0
1169          *
1170          * @param WP_REST_Request $request The request object with post and terms data.
1171          * @return bool Whether the current user can assign the provided terms.
1172          */
1173         protected function check_assign_terms_permission( $request ) {
1174                 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1175                 foreach ( $taxonomies as $taxonomy ) {
1176                         $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1177
1178                         if ( ! isset( $request[ $base ] ) ) {
1179                                 continue;
1180                         }
1181
1182                         foreach ( $request[ $base ] as $term_id ) {
1183                                 // Invalid terms will be rejected later.
1184                                 if ( ! get_term( $term_id, $taxonomy->name ) ) {
1185                                         continue;
1186                                 }
1187
1188                                 if ( ! current_user_can( 'assign_term', (int) $term_id ) ) {
1189                                         return false;
1190                                 }
1191                         }
1192                 }
1193
1194                 return true;
1195         }
1196
1197         /**
1198          * Checks if a given post type can be viewed or managed.
1199          *
1200          * @since 4.7.0
1201          * @access protected
1202          *
1203          * @param object|string $post_type Post type name or object.
1204          * @return bool Whether the post type is allowed in REST.
1205          */
1206         protected function check_is_post_type_allowed( $post_type ) {
1207                 if ( ! is_object( $post_type ) ) {
1208                         $post_type = get_post_type_object( $post_type );
1209                 }
1210
1211                 if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) {
1212                         return true;
1213                 }
1214
1215                 return false;
1216         }
1217
1218         /**
1219          * Checks if a post can be read.
1220          *
1221          * Correctly handles posts with the inherit status.
1222          *
1223          * @since 4.7.0
1224          * @access public
1225          *
1226          * @param object $post Post object.
1227          * @return bool Whether the post can be read.
1228          */
1229         public function check_read_permission( $post ) {
1230                 $post_type = get_post_type_object( $post->post_type );
1231                 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1232                         return false;
1233                 }
1234
1235                 // Is the post readable?
1236                 if ( 'publish' === $post->post_status || current_user_can( $post_type->cap->read_post, $post->ID ) ) {
1237                         return true;
1238                 }
1239
1240                 $post_status_obj = get_post_status_object( $post->post_status );
1241                 if ( $post_status_obj && $post_status_obj->public ) {
1242                         return true;
1243                 }
1244
1245                 // Can we read the parent if we're inheriting?
1246                 if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
1247                         $parent = get_post( $post->post_parent );
1248                         return $this->check_read_permission( $parent );
1249                 }
1250
1251                 /*
1252                  * If there isn't a parent, but the status is set to inherit, assume
1253                  * it's published (as per get_post_status()).
1254                  */
1255                 if ( 'inherit' === $post->post_status ) {
1256                         return true;
1257                 }
1258
1259                 return false;
1260         }
1261
1262         /**
1263          * Checks if a post can be edited.
1264          *
1265          * @since 4.7.0
1266          * @access protected
1267          *
1268          * @param object $post Post object.
1269          * @return bool Whether the post can be edited.
1270          */
1271         protected function check_update_permission( $post ) {
1272                 $post_type = get_post_type_object( $post->post_type );
1273
1274                 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1275                         return false;
1276                 }
1277
1278                 return current_user_can( $post_type->cap->edit_post, $post->ID );
1279         }
1280
1281         /**
1282          * Checks if a post can be created.
1283          *
1284          * @since 4.7.0
1285          * @access protected
1286          *
1287          * @param object $post Post object.
1288          * @return bool Whether the post can be created.
1289          */
1290         protected function check_create_permission( $post ) {
1291                 $post_type = get_post_type_object( $post->post_type );
1292
1293                 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1294                         return false;
1295                 }
1296
1297                 return current_user_can( $post_type->cap->create_posts );
1298         }
1299
1300         /**
1301          * Checks if a post can be deleted.
1302          *
1303          * @since 4.7.0
1304          * @access protected
1305          *
1306          * @param object $post Post object.
1307          * @return bool Whether the post can be deleted.
1308          */
1309         protected function check_delete_permission( $post ) {
1310                 $post_type = get_post_type_object( $post->post_type );
1311
1312                 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1313                         return false;
1314                 }
1315
1316                 return current_user_can( $post_type->cap->delete_post, $post->ID );
1317         }
1318
1319         /**
1320          * Prepares a single post output for response.
1321          *
1322          * @since 4.7.0
1323          * @access public
1324          *
1325          * @param WP_Post         $post    Post object.
1326          * @param WP_REST_Request $request Request object.
1327          * @return WP_REST_Response Response object.
1328          */
1329         public function prepare_item_for_response( $post, $request ) {
1330                 $GLOBALS['post'] = $post;
1331
1332                 setup_postdata( $post );
1333
1334                 $schema = $this->get_item_schema();
1335
1336                 // Base fields for every post.
1337                 $data = array();
1338
1339                 if ( ! empty( $schema['properties']['id'] ) ) {
1340                         $data['id'] = $post->ID;
1341                 }
1342
1343                 if ( ! empty( $schema['properties']['date'] ) ) {
1344                         $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date );
1345                 }
1346
1347                 if ( ! empty( $schema['properties']['date_gmt'] ) ) {
1348                         $data['date_gmt'] = $this->prepare_date_response( $post->post_date_gmt );
1349                 }
1350
1351                 if ( ! empty( $schema['properties']['guid'] ) ) {
1352                         $data['guid'] = array(
1353                                 /** This filter is documented in wp-includes/post-template.php */
1354                                 'rendered' => apply_filters( 'get_the_guid', $post->guid ),
1355                                 'raw'      => $post->guid,
1356                         );
1357                 }
1358
1359                 if ( ! empty( $schema['properties']['modified'] ) ) {
1360                         $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified );
1361                 }
1362
1363                 if ( ! empty( $schema['properties']['modified_gmt'] ) ) {
1364                         $data['modified_gmt'] = $this->prepare_date_response( $post->post_modified_gmt );
1365                 }
1366
1367                 if ( ! empty( $schema['properties']['password'] ) ) {
1368                         $data['password'] = $post->post_password;
1369                 }
1370
1371                 if ( ! empty( $schema['properties']['slug'] ) ) {
1372                         $data['slug'] = $post->post_name;
1373                 }
1374
1375                 if ( ! empty( $schema['properties']['status'] ) ) {
1376                         $data['status'] = $post->post_status;
1377                 }
1378
1379                 if ( ! empty( $schema['properties']['type'] ) ) {
1380                         $data['type'] = $post->post_type;
1381                 }
1382
1383                 if ( ! empty( $schema['properties']['link'] ) ) {
1384                         $data['link'] = get_permalink( $post->ID );
1385                 }
1386
1387                 if ( ! empty( $schema['properties']['title'] ) ) {
1388                         add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1389
1390                         $data['title'] = array(
1391                                 'raw'      => $post->post_title,
1392                                 'rendered' => get_the_title( $post->ID ),
1393                         );
1394
1395                         remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1396                 }
1397
1398                 $has_password_filter = false;
1399
1400                 if ( $this->can_access_password_content( $post, $request ) ) {
1401                         // Allow access to the post, permissions already checked before.
1402                         add_filter( 'post_password_required', '__return_false' );
1403
1404                         $has_password_filter = true;
1405                 }
1406
1407                 if ( ! empty( $schema['properties']['content'] ) ) {
1408                         $data['content'] = array(
1409                                 'raw'       => $post->post_content,
1410                                 /** This filter is documented in wp-includes/post-template.php */
1411                                 'rendered'  => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
1412                                 'protected' => (bool) $post->post_password,
1413                         );
1414                 }
1415
1416                 if ( ! empty( $schema['properties']['excerpt'] ) ) {
1417                         /** This filter is documented in wp-includes/post-template.php */
1418                         $excerpt = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ) );
1419                         $data['excerpt'] = array(
1420                                 'raw'       => $post->post_excerpt,
1421                                 'rendered'  => post_password_required( $post ) ? '' : $excerpt,
1422                                 'protected' => (bool) $post->post_password,
1423                         );
1424                 }
1425
1426                 if ( $has_password_filter ) {
1427                         // Reset filter.
1428                         remove_filter( 'post_password_required', '__return_false' );
1429                 }
1430
1431                 if ( ! empty( $schema['properties']['author'] ) ) {
1432                         $data['author'] = (int) $post->post_author;
1433                 }
1434
1435                 if ( ! empty( $schema['properties']['featured_media'] ) ) {
1436                         $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID );
1437                 }
1438
1439                 if ( ! empty( $schema['properties']['parent'] ) ) {
1440                         $data['parent'] = (int) $post->post_parent;
1441                 }
1442
1443                 if ( ! empty( $schema['properties']['menu_order'] ) ) {
1444                         $data['menu_order'] = (int) $post->menu_order;
1445                 }
1446
1447                 if ( ! empty( $schema['properties']['comment_status'] ) ) {
1448                         $data['comment_status'] = $post->comment_status;
1449                 }
1450
1451                 if ( ! empty( $schema['properties']['ping_status'] ) ) {
1452                         $data['ping_status'] = $post->ping_status;
1453                 }
1454
1455                 if ( ! empty( $schema['properties']['sticky'] ) ) {
1456                         $data['sticky'] = is_sticky( $post->ID );
1457                 }
1458
1459                 if ( ! empty( $schema['properties']['template'] ) ) {
1460                         if ( $template = get_page_template_slug( $post->ID ) ) {
1461                                 $data['template'] = $template;
1462                         } else {
1463                                 $data['template'] = '';
1464                         }
1465                 }
1466
1467                 if ( ! empty( $schema['properties']['format'] ) ) {
1468                         $data['format'] = get_post_format( $post->ID );
1469
1470                         // Fill in blank post format.
1471                         if ( empty( $data['format'] ) ) {
1472                                 $data['format'] = 'standard';
1473                         }
1474                 }
1475
1476                 if ( ! empty( $schema['properties']['meta'] ) ) {
1477                         $data['meta'] = $this->meta->get_value( $post->ID, $request );
1478                 }
1479
1480                 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1481
1482                 foreach ( $taxonomies as $taxonomy ) {
1483                         $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1484
1485                         if ( ! empty( $schema['properties'][ $base ] ) ) {
1486                                 $terms = get_the_terms( $post, $taxonomy->name );
1487                                 $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
1488                         }
1489                 }
1490
1491                 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1492                 $data    = $this->add_additional_fields_to_object( $data, $request );
1493                 $data    = $this->filter_response_by_context( $data, $context );
1494
1495                 // Wrap the data in a response object.
1496                 $response = rest_ensure_response( $data );
1497
1498                 $response->add_links( $this->prepare_links( $post ) );
1499
1500                 /**
1501                  * Filters the post data for a response.
1502                  *
1503                  * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1504                  *
1505                  * @since 4.7.0
1506                  *
1507                  * @param WP_REST_Response $response The response object.
1508                  * @param WP_Post          $post     Post object.
1509                  * @param WP_REST_Request  $request  Request object.
1510                  */
1511                 return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );
1512         }
1513
1514         /**
1515          * Overwrites the default protected title format.
1516          *
1517          * By default, WordPress will show password protected posts with a title of
1518          * "Protected: %s", as the REST API communicates the protected status of a post
1519          * in a machine readable format, we remove the "Protected: " prefix.
1520          *
1521          * @return string Protected title format.
1522          */
1523         public function protected_title_format() {
1524                 return '%s';
1525         }
1526
1527         /**
1528          * Prepares links for the request.
1529          *
1530          * @since 4.7.0
1531          * @access protected
1532          *
1533          * @param WP_Post $post Post object.
1534          * @return array Links for the given post.
1535          */
1536         protected function prepare_links( $post ) {
1537                 $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
1538
1539                 // Entity meta.
1540                 $links = array(
1541                         'self' => array(
1542                                 'href'   => rest_url( trailingslashit( $base ) . $post->ID ),
1543                         ),
1544                         'collection' => array(
1545                                 'href'   => rest_url( $base ),
1546                         ),
1547                         'about'      => array(
1548                                 'href'   => rest_url( 'wp/v2/types/' . $this->post_type ),
1549                         ),
1550                 );
1551
1552                 if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) )
1553                         && ! empty( $post->post_author ) ) {
1554                         $links['author'] = array(
1555                                 'href'       => rest_url( 'wp/v2/users/' . $post->post_author ),
1556                                 'embeddable' => true,
1557                         );
1558                 }
1559
1560                 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) {
1561                         $replies_url = rest_url( 'wp/v2/comments' );
1562                         $replies_url = add_query_arg( 'post', $post->ID, $replies_url );
1563
1564                         $links['replies'] = array(
1565                                 'href'       => $replies_url,
1566                                 'embeddable' => true,
1567                         );
1568                 }
1569
1570                 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) {
1571                         $links['version-history'] = array(
1572                                 'href' => rest_url( trailingslashit( $base ) . $post->ID . '/revisions' ),
1573                         );
1574                 }
1575
1576                 $post_type_obj = get_post_type_object( $post->post_type );
1577
1578                 if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) {
1579                         $links['up'] = array(
1580                                 'href'       => rest_url( trailingslashit( $base ) . (int) $post->post_parent ),
1581                                 'embeddable' => true,
1582                         );
1583                 }
1584
1585                 // If we have a featured media, add that.
1586                 if ( $featured_media = get_post_thumbnail_id( $post->ID ) ) {
1587                         $image_url = rest_url( 'wp/v2/media/' . $featured_media );
1588
1589                         $links['https://api.w.org/featuredmedia'] = array(
1590                                 'href'       => $image_url,
1591                                 'embeddable' => true,
1592                         );
1593                 }
1594
1595                 if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
1596                         $attachments_url = rest_url( 'wp/v2/media' );
1597                         $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url );
1598
1599                         $links['https://api.w.org/attachment'] = array(
1600                                 'href' => $attachments_url,
1601                         );
1602                 }
1603
1604                 $taxonomies = get_object_taxonomies( $post->post_type );
1605
1606                 if ( ! empty( $taxonomies ) ) {
1607                         $links['https://api.w.org/term'] = array();
1608
1609                         foreach ( $taxonomies as $tax ) {
1610                                 $taxonomy_obj = get_taxonomy( $tax );
1611
1612                                 // Skip taxonomies that are not public.
1613                                 if ( empty( $taxonomy_obj->show_in_rest ) ) {
1614                                         continue;
1615                                 }
1616
1617                                 $tax_base = ! empty( $taxonomy_obj->rest_base ) ? $taxonomy_obj->rest_base : $tax;
1618
1619                                 $terms_url = add_query_arg(
1620                                         'post',
1621                                         $post->ID,
1622                                         rest_url( 'wp/v2/' . $tax_base )
1623                                 );
1624
1625                                 $links['https://api.w.org/term'][] = array(
1626                                         'href'       => $terms_url,
1627                                         'taxonomy'   => $tax,
1628                                         'embeddable' => true,
1629                                 );
1630                         }
1631                 }
1632
1633                 return $links;
1634         }
1635
1636         /**
1637          * Retrieves the post's schema, conforming to JSON Schema.
1638          *
1639          * @since 4.7.0
1640          * @access public
1641          *
1642          * @return array Item schema data.
1643          */
1644         public function get_item_schema() {
1645
1646                 $schema = array(
1647                         '$schema'    => 'http://json-schema.org/schema#',
1648                         'title'      => $this->post_type,
1649                         'type'       => 'object',
1650                         // Base properties for every Post.
1651                         'properties' => array(
1652                                 'date'            => array(
1653                                         'description' => __( "The date the object was published, in the site's timezone." ),
1654                                         'type'        => 'string',
1655                                         'format'      => 'date-time',
1656                                         'context'     => array( 'view', 'edit', 'embed' ),
1657                                 ),
1658                                 'date_gmt'        => array(
1659                                         'description' => __( 'The date the object was published, as GMT.' ),
1660                                         'type'        => 'string',
1661                                         'format'      => 'date-time',
1662                                         'context'     => array( 'view', 'edit' ),
1663                                 ),
1664                                 'guid'            => array(
1665                                         'description' => __( 'The globally unique identifier for the object.' ),
1666                                         'type'        => 'object',
1667                                         'context'     => array( 'view', 'edit' ),
1668                                         'readonly'    => true,
1669                                         'properties'  => array(
1670                                                 'raw'      => array(
1671                                                         'description' => __( 'GUID for the object, as it exists in the database.' ),
1672                                                         'type'        => 'string',
1673                                                         'context'     => array( 'edit' ),
1674                                                         'readonly'    => true,
1675                                                 ),
1676                                                 'rendered' => array(
1677                                                         'description' => __( 'GUID for the object, transformed for display.' ),
1678                                                         'type'        => 'string',
1679                                                         'context'     => array( 'view', 'edit' ),
1680                                                         'readonly'    => true,
1681                                                 ),
1682                                         ),
1683                                 ),
1684                                 'id'              => array(
1685                                         'description' => __( 'Unique identifier for the object.' ),
1686                                         'type'        => 'integer',
1687                                         'context'     => array( 'view', 'edit', 'embed' ),
1688                                         'readonly'    => true,
1689                                 ),
1690                                 'link'            => array(
1691                                         'description' => __( 'URL to the object.' ),
1692                                         'type'        => 'string',
1693                                         'format'      => 'uri',
1694                                         'context'     => array( 'view', 'edit', 'embed' ),
1695                                         'readonly'    => true,
1696                                 ),
1697                                 'modified'        => array(
1698                                         'description' => __( "The date the object was last modified, in the site's timezone." ),
1699                                         'type'        => 'string',
1700                                         'format'      => 'date-time',
1701                                         'context'     => array( 'view', 'edit' ),
1702                                         'readonly'    => true,
1703                                 ),
1704                                 'modified_gmt'    => array(
1705                                         'description' => __( 'The date the object was last modified, as GMT.' ),
1706                                         'type'        => 'string',
1707                                         'format'      => 'date-time',
1708                                         'context'     => array( 'view', 'edit' ),
1709                                         'readonly'    => true,
1710                                 ),
1711                                 'slug'            => array(
1712                                         'description' => __( 'An alphanumeric identifier for the object unique to its type.' ),
1713                                         'type'        => 'string',
1714                                         'context'     => array( 'view', 'edit', 'embed' ),
1715                                         'arg_options' => array(
1716                                                 'sanitize_callback' => array( $this, 'sanitize_slug' ),
1717                                         ),
1718                                 ),
1719                                 'status'          => array(
1720                                         'description' => __( 'A named status for the object.' ),
1721                                         'type'        => 'string',
1722                                         'enum'        => array_keys( get_post_stati( array( 'internal' => false ) ) ),
1723                                         'context'     => array( 'edit' ),
1724                                 ),
1725                                 'type'            => array(
1726                                         'description' => __( 'Type of Post for the object.' ),
1727                                         'type'        => 'string',
1728                                         'context'     => array( 'view', 'edit', 'embed' ),
1729                                         'readonly'    => true,
1730                                 ),
1731                                 'password'        => array(
1732                                         'description' => __( 'A password to protect access to the content and excerpt.' ),
1733                                         'type'        => 'string',
1734                                         'context'     => array( 'edit' ),
1735                                 ),
1736                         ),
1737                 );
1738
1739                 $post_type_obj = get_post_type_object( $this->post_type );
1740
1741                 if ( $post_type_obj->hierarchical ) {
1742                         $schema['properties']['parent'] = array(
1743                                 'description' => __( 'The ID for the parent of the object.' ),
1744                                 'type'        => 'integer',
1745                                 'context'     => array( 'view', 'edit' ),
1746                         );
1747                 }
1748
1749                 $post_type_attributes = array(
1750                         'title',
1751                         'editor',
1752                         'author',
1753                         'excerpt',
1754                         'thumbnail',
1755                         'comments',
1756                         'revisions',
1757                         'page-attributes',
1758                         'post-formats',
1759                         'custom-fields',
1760                 );
1761                 $fixed_schemas = array(
1762                         'post' => array(
1763                                 'title',
1764                                 'editor',
1765                                 'author',
1766                                 'excerpt',
1767                                 'thumbnail',
1768                                 'comments',
1769                                 'revisions',
1770                                 'post-formats',
1771                                 'custom-fields',
1772                         ),
1773                         'page' => array(
1774                                 'title',
1775                                 'editor',
1776                                 'author',
1777                                 'excerpt',
1778                                 'thumbnail',
1779                                 'comments',
1780                                 'revisions',
1781                                 'page-attributes',
1782                                 'custom-fields',
1783                         ),
1784                         'attachment' => array(
1785                                 'title',
1786                                 'author',
1787                                 'comments',
1788                                 'revisions',
1789                                 'custom-fields',
1790                         ),
1791                 );
1792                 foreach ( $post_type_attributes as $attribute ) {
1793                         if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) {
1794                                 continue;
1795                         } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) {
1796                                 continue;
1797                         }
1798
1799                         switch ( $attribute ) {
1800
1801                                 case 'title':
1802                                         $schema['properties']['title'] = array(
1803                                                 'description' => __( 'The title for the object.' ),
1804                                                 'type'        => 'object',
1805                                                 'context'     => array( 'view', 'edit', 'embed' ),
1806                                                 'arg_options' => array(
1807                                                         'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1808                                                 ),
1809                                                 'properties'  => array(
1810                                                         'raw' => array(
1811                                                                 'description' => __( 'Title for the object, as it exists in the database.' ),
1812                                                                 'type'        => 'string',
1813                                                                 'context'     => array( 'edit' ),
1814                                                         ),
1815                                                         'rendered' => array(
1816                                                                 'description' => __( 'HTML title for the object, transformed for display.' ),
1817                                                                 'type'        => 'string',
1818                                                                 'context'     => array( 'view', 'edit', 'embed' ),
1819                                                                 'readonly'    => true,
1820                                                         ),
1821                                                 ),
1822                                         );
1823                                         break;
1824
1825                                 case 'editor':
1826                                         $schema['properties']['content'] = array(
1827                                                 'description' => __( 'The content for the object.' ),
1828                                                 'type'        => 'object',
1829                                                 'context'     => array( 'view', 'edit' ),
1830                                                 'arg_options' => array(
1831                                                         'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1832                                                 ),
1833                                                 'properties'  => array(
1834                                                         'raw' => array(
1835                                                                 'description' => __( 'Content for the object, as it exists in the database.' ),
1836                                                                 'type'        => 'string',
1837                                                                 'context'     => array( 'edit' ),
1838                                                         ),
1839                                                         'rendered' => array(
1840                                                                 'description' => __( 'HTML content for the object, transformed for display.' ),
1841                                                                 'type'        => 'string',
1842                                                                 'context'     => array( 'view', 'edit' ),
1843                                                                 'readonly'    => true,
1844                                                         ),
1845                                                         'protected'       => array(
1846                                                                 'description' => __( 'Whether the content is protected with a password.' ),
1847                                                                 'type'        => 'boolean',
1848                                                                 'context'     => array( 'view', 'edit', 'embed' ),
1849                                                                 'readonly'    => true,
1850                                                         ),
1851                                                 ),
1852                                         );
1853                                         break;
1854
1855                                 case 'author':
1856                                         $schema['properties']['author'] = array(
1857                                                 'description' => __( 'The ID for the author of the object.' ),
1858                                                 'type'        => 'integer',
1859                                                 'context'     => array( 'view', 'edit', 'embed' ),
1860                                         );
1861                                         break;
1862
1863                                 case 'excerpt':
1864                                         $schema['properties']['excerpt'] = array(
1865                                                 'description' => __( 'The excerpt for the object.' ),
1866                                                 'type'        => 'object',
1867                                                 'context'     => array( 'view', 'edit', 'embed' ),
1868                                                 'arg_options' => array(
1869                                                         'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1870                                                 ),
1871                                                 'properties'  => array(
1872                                                         'raw' => array(
1873                                                                 'description' => __( 'Excerpt for the object, as it exists in the database.' ),
1874                                                                 'type'        => 'string',
1875                                                                 'context'     => array( 'edit' ),
1876                                                         ),
1877                                                         'rendered' => array(
1878                                                                 'description' => __( 'HTML excerpt for the object, transformed for display.' ),
1879                                                                 'type'        => 'string',
1880                                                                 'context'     => array( 'view', 'edit', 'embed' ),
1881                                                                 'readonly'    => true,
1882                                                         ),
1883                                                         'protected'       => array(
1884                                                                 'description' => __( 'Whether the excerpt is protected with a password.' ),
1885                                                                 'type'        => 'boolean',
1886                                                                 'context'     => array( 'view', 'edit', 'embed' ),
1887                                                                 'readonly'    => true,
1888                                                         ),
1889                                                 ),
1890                                         );
1891                                         break;
1892
1893                                 case 'thumbnail':
1894                                         $schema['properties']['featured_media'] = array(
1895                                                 'description' => __( 'The ID of the featured media for the object.' ),
1896                                                 'type'        => 'integer',
1897                                                 'context'     => array( 'view', 'edit' ),
1898                                         );
1899                                         break;
1900
1901                                 case 'comments':
1902                                         $schema['properties']['comment_status'] = array(
1903                                                 'description' => __( 'Whether or not comments are open on the object.' ),
1904                                                 'type'        => 'string',
1905                                                 'enum'        => array( 'open', 'closed' ),
1906                                                 'context'     => array( 'view', 'edit' ),
1907                                         );
1908                                         $schema['properties']['ping_status'] = array(
1909                                                 'description' => __( 'Whether or not the object can be pinged.' ),
1910                                                 'type'        => 'string',
1911                                                 'enum'        => array( 'open', 'closed' ),
1912                                                 'context'     => array( 'view', 'edit' ),
1913                                         );
1914                                         break;
1915
1916                                 case 'page-attributes':
1917                                         $schema['properties']['menu_order'] = array(
1918                                                 'description' => __( 'The order of the object in relation to other object of its type.' ),
1919                                                 'type'        => 'integer',
1920                                                 'context'     => array( 'view', 'edit' ),
1921                                         );
1922                                         break;
1923
1924                                 case 'post-formats':
1925                                         $supports_formats = get_theme_support( 'post-formats' );
1926
1927                                         // Force to an array. Supports formats can return true even if empty in some cases.
1928                                         $supports_formats = is_array( $supports_formats ) ? array_values( $supports_formats[0] ) : array();
1929
1930                                         $supported_formats = array_merge( array( 'standard' ), $supports_formats );
1931
1932                                         $schema['properties']['format'] = array(
1933                                                 'description' => __( 'The format for the object.' ),
1934                                                 'type'        => 'string',
1935                                                 'enum'        => $supported_formats,
1936                                                 'context'     => array( 'view', 'edit' ),
1937                                         );
1938                                         break;
1939
1940                                 case 'custom-fields':
1941                                         $schema['properties']['meta'] = $this->meta->get_field_schema();
1942                                         break;
1943
1944                         }
1945                 }
1946
1947                 if ( 'post' === $this->post_type ) {
1948                         $schema['properties']['sticky'] = array(
1949                                 'description' => __( 'Whether or not the object should be treated as sticky.' ),
1950                                 'type'        => 'boolean',
1951                                 'context'     => array( 'view', 'edit' ),
1952                         );
1953                 }
1954
1955                 $schema['properties']['template'] = array(
1956                         'description' => __( 'The theme file to use to display the object.' ),
1957                         'type'        => 'string',
1958                         'enum'        => array_merge( array_keys( wp_get_theme()->get_page_templates( null, $this->post_type ) ), array( '' ) ),
1959                         'context'     => array( 'view', 'edit' ),
1960                 );
1961
1962                 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1963                 foreach ( $taxonomies as $taxonomy ) {
1964                         $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1965                         $schema['properties'][ $base ] = array(
1966                                 /* translators: %s: taxonomy name */
1967                                 'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.' ), $taxonomy->name ),
1968                                 'type'        => 'array',
1969                                 'items'       => array(
1970                                         'type'    => 'integer',
1971                                 ),
1972                                 'context'     => array( 'view', 'edit' ),
1973                         );
1974                 }
1975
1976                 return $this->add_additional_fields_schema( $schema );
1977         }
1978
1979         /**
1980          * Retrieves the query params for the posts collection.
1981          *
1982          * @since 4.7.0
1983          * @access public
1984          *
1985          * @return array Collection parameters.
1986          */
1987         public function get_collection_params() {
1988                 $query_params = parent::get_collection_params();
1989
1990                 $query_params['context']['default'] = 'view';
1991
1992                 $query_params['after'] = array(
1993                         'description'        => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
1994                         'type'               => 'string',
1995                         'format'             => 'date-time',
1996                 );
1997
1998                 if ( post_type_supports( $this->post_type, 'author' ) ) {
1999                         $query_params['author'] = array(
2000                                 'description'         => __( 'Limit result set to posts assigned to specific authors.' ),
2001                                 'type'                => 'array',
2002                                 'items'               => array(
2003                                         'type'            => 'integer',
2004                                 ),
2005                                 'default'             => array(),
2006                         );
2007                         $query_params['author_exclude'] = array(
2008                                 'description'         => __( 'Ensure result set excludes posts assigned to specific authors.' ),
2009                                 'type'                => 'array',
2010                                 'items'               => array(
2011                                         'type'            => 'integer',
2012                                 ),
2013                                 'default'             => array(),
2014                         );
2015                 }
2016
2017                 $query_params['before'] = array(
2018                         'description'        => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
2019                         'type'               => 'string',
2020                         'format'             => 'date-time',
2021                 );
2022
2023                 $query_params['exclude'] = array(
2024                         'description'        => __( 'Ensure result set excludes specific IDs.' ),
2025                         'type'               => 'array',
2026                         'items'              => array(
2027                                 'type'           => 'integer',
2028                         ),
2029                         'default'            => array(),
2030                 );
2031
2032                 $query_params['include'] = array(
2033                         'description'        => __( 'Limit result set to specific IDs.' ),
2034                         'type'               => 'array',
2035                         'items'              => array(
2036                                 'type'           => 'integer',
2037                         ),
2038                         'default'            => array(),
2039                 );
2040
2041                 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2042                         $query_params['menu_order'] = array(
2043                                 'description'        => __( 'Limit result set to posts with a specific menu_order value.' ),
2044                                 'type'               => 'integer',
2045                         );
2046                 }
2047
2048                 $query_params['offset'] = array(
2049                         'description'        => __( 'Offset the result set by a specific number of items.' ),
2050                         'type'               => 'integer',
2051                 );
2052
2053                 $query_params['order'] = array(
2054                         'description'        => __( 'Order sort attribute ascending or descending.' ),
2055                         'type'               => 'string',
2056                         'default'            => 'desc',
2057                         'enum'               => array( 'asc', 'desc' ),
2058                 );
2059
2060                 $query_params['orderby'] = array(
2061                         'description'        => __( 'Sort collection by object attribute.' ),
2062                         'type'               => 'string',
2063                         'default'            => 'date',
2064                         'enum'               => array(
2065                                 'date',
2066                                 'relevance',
2067                                 'id',
2068                                 'include',
2069                                 'title',
2070                                 'slug',
2071                         ),
2072                 );
2073
2074                 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2075                         $query_params['orderby']['enum'][] = 'menu_order';
2076                 }
2077
2078                 $post_type = get_post_type_object( $this->post_type );
2079
2080                 if ( $post_type->hierarchical || 'attachment' === $this->post_type ) {
2081                         $query_params['parent'] = array(
2082                                 'description'       => __( 'Limit result set to those of particular parent IDs.' ),
2083                                 'type'              => 'array',
2084                                 'items'             => array(
2085                                         'type'          => 'integer',
2086                                 ),
2087                                 'default'           => array(),
2088                         );
2089                         $query_params['parent_exclude'] = array(
2090                                 'description'       => __( 'Limit result set to all items except those of a particular parent ID.' ),
2091                                 'type'              => 'array',
2092                                 'items'             => array(
2093                                         'type'          => 'integer',
2094                                 ),
2095                                 'default'           => array(),
2096                         );
2097                 }
2098
2099                 $query_params['slug'] = array(
2100                         'description'       => __( 'Limit result set to posts with one or more specific slugs.' ),
2101                         'type'              => 'array',
2102                         'items'             => array(
2103                                 'type'          => 'string',
2104                         ),
2105                         'sanitize_callback' => 'wp_parse_slug_list',
2106                 );
2107
2108                 $query_params['status'] = array(
2109                         'default'           => 'publish',
2110                         'description'       => __( 'Limit result set to posts assigned one or more statuses.' ),
2111                         'type'              => 'array',
2112                         'items'             => array(
2113                                 'enum'          => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
2114                                 'type'          => 'string',
2115                         ),
2116                         'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
2117                 );
2118
2119                 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2120
2121                 foreach ( $taxonomies as $taxonomy ) {
2122                         $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
2123
2124                         $query_params[ $base ] = array(
2125                                 /* translators: %s: taxonomy name */
2126                                 'description'       => sprintf( __( 'Limit result set to all items that have the specified term assigned in the %s taxonomy.' ), $base ),
2127                                 'type'              => 'array',
2128                                 'items'             => array(
2129                                         'type'          => 'integer',
2130                                 ),
2131                                 'default'           => array(),
2132                         );
2133
2134                         $query_params[ $base . '_exclude' ] = array(
2135                                 /* translators: %s: taxonomy name */
2136                                 'description' => sprintf( __( 'Limit result set to all items except those that have the specified term assigned in the %s taxonomy.' ), $base ),
2137                                 'type'        => 'array',
2138                                 'items'       => array(
2139                                         'type'    => 'integer',
2140                                 ),
2141                                 'default'           => array(),
2142                         );
2143                 }
2144
2145                 if ( 'post' === $this->post_type ) {
2146                         $query_params['sticky'] = array(
2147                                 'description'       => __( 'Limit result set to items that are sticky.' ),
2148                                 'type'              => 'boolean',
2149                         );
2150                 }
2151
2152                 /**
2153                  * Filter collection parameters for the posts controller.
2154                  *
2155                  * The dynamic part of the filter `$this->post_type` refers to the post
2156                  * type slug for the controller.
2157                  *
2158                  * This filter registers the collection parameter, but does not map the
2159                  * collection parameter to an internal WP_Query parameter. Use the
2160                  * `rest_{$this->post_type}_query` filter to set WP_Query parameters.
2161                  *
2162                  * @since 4.7.0
2163                  *
2164                  * @param array        $query_params JSON Schema-formatted collection parameters.
2165                  * @param WP_Post_Type $post_type    Post type object.
2166                  */
2167                 return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );
2168         }
2169
2170         /**
2171          * Sanitizes and validates the list of post statuses, including whether the
2172          * user can query private statuses.
2173          *
2174          * @since 4.7.0
2175          * @access public
2176          *
2177          * @param  string|array    $statuses  One or more post statuses.
2178          * @param  WP_REST_Request $request   Full details about the request.
2179          * @param  string          $parameter Additional parameter to pass to validation.
2180          * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
2181          */
2182         public function sanitize_post_statuses( $statuses, $request, $parameter ) {
2183                 $statuses = wp_parse_slug_list( $statuses );
2184
2185                 // The default status is different in WP_REST_Attachments_Controller
2186                 $attributes = $request->get_attributes();
2187                 $default_status = $attributes['args']['status']['default'];
2188
2189                 foreach ( $statuses as $status ) {
2190                         if ( $status === $default_status ) {
2191                                 continue;
2192                         }
2193
2194                         $post_type_obj = get_post_type_object( $this->post_type );
2195
2196                         if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
2197                                 $result = rest_validate_request_arg( $status, $request, $parameter );
2198                                 if ( is_wp_error( $result ) ) {
2199                                         return $result;
2200                                 }
2201                         } else {
2202                                 return new WP_Error( 'rest_forbidden_status', __( 'Status is forbidden.' ), array( 'status' => rest_authorization_required_code() ) );
2203                         }
2204                 }
2205
2206                 return $statuses;
2207         }
2208 }