]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php
WordPress 4.7.2-scripts
[autoinstalls/wordpress.git] / wp-includes / rest-api / endpoints / class-wp-rest-comments-controller.php
1 <?php
2 /**
3  * REST API: WP_REST_Comments_Controller class
4  *
5  * @package WordPress
6  * @subpackage REST_API
7  * @since 4.7.0
8  */
9
10 /**
11  * Core controller used to access comments via the REST API.
12  *
13  * @since 4.7.0
14  *
15  * @see WP_REST_Controller
16  */
17 class WP_REST_Comments_Controller extends WP_REST_Controller {
18
19         /**
20          * Instance of a comment meta fields object.
21          *
22          * @since 4.7.0
23          * @access protected
24          * @var WP_REST_Comment_Meta_Fields
25          */
26         protected $meta;
27
28         /**
29          * Constructor.
30          *
31          * @since 4.7.0
32          * @access public
33          */
34         public function __construct() {
35                 $this->namespace = 'wp/v2';
36                 $this->rest_base = 'comments';
37
38                 $this->meta = new WP_REST_Comment_Meta_Fields();
39         }
40
41         /**
42          * Registers the routes for the objects of the controller.
43          *
44          * @since 4.7.0
45          * @access public
46          */
47         public function register_routes() {
48
49                 register_rest_route( $this->namespace, '/' . $this->rest_base, array(
50                         array(
51                                 'methods'   => WP_REST_Server::READABLE,
52                                 'callback'  => array( $this, 'get_items' ),
53                                 'permission_callback' => array( $this, 'get_items_permissions_check' ),
54                                 'args'      => $this->get_collection_params(),
55                         ),
56                         array(
57                                 'methods'  => WP_REST_Server::CREATABLE,
58                                 'callback' => array( $this, 'create_item' ),
59                                 'permission_callback' => array( $this, 'create_item_permissions_check' ),
60                                 'args'     => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
61                         ),
62                         'schema' => array( $this, 'get_public_item_schema' ),
63                 ) );
64
65                 register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
66                         'args' => array(
67                                 'id' => array(
68                                         'description' => __( 'Unique identifier for the object.' ),
69                                         'type'        => 'integer',
70                                 ),
71                         ),
72                         array(
73                                 'methods'  => WP_REST_Server::READABLE,
74                                 'callback' => array( $this, 'get_item' ),
75                                 'permission_callback' => array( $this, 'get_item_permissions_check' ),
76                                 'args'     => array(
77                                         'context'          => $this->get_context_param( array( 'default' => 'view' ) ),
78                                         'password' => array(
79                                                 'description' => __( 'The password for the post if it is password protected.' ),
80                                                 'type'        => 'string',
81                                         ),
82                                 ),
83                         ),
84                         array(
85                                 'methods'  => WP_REST_Server::EDITABLE,
86                                 'callback' => array( $this, 'update_item' ),
87                                 'permission_callback' => array( $this, 'update_item_permissions_check' ),
88                                 'args'     => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
89                         ),
90                         array(
91                                 'methods'  => WP_REST_Server::DELETABLE,
92                                 'callback' => array( $this, 'delete_item' ),
93                                 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
94                                 'args'     => array(
95                                         'force'    => array(
96                                                 'type'        => 'boolean',
97                                                 'default'     => false,
98                                                 'description' => __( 'Whether to bypass trash and force deletion.' ),
99                                         ),
100                                         'password' => array(
101                                                 'description' => __( 'The password for the post if it is password protected.' ),
102                                                 'type'        => 'string',
103                                         ),
104                                 ),
105                         ),
106                         'schema' => array( $this, 'get_public_item_schema' ),
107                 ) );
108         }
109
110         /**
111          * Checks if a given request has access to read comments.
112          *
113          * @since 4.7.0
114          * @access public
115          *
116          * @param WP_REST_Request $request Full details about the request.
117          * @return WP_Error|bool True if the request has read access, error object otherwise.
118          */
119         public function get_items_permissions_check( $request ) {
120
121                 if ( ! empty( $request['post'] ) ) {
122                         foreach ( (array) $request['post'] as $post_id ) {
123                                 $post = get_post( $post_id );
124
125                                 if ( ! empty( $post_id ) && $post && ! $this->check_read_post_permission( $post, $request ) ) {
126                                         return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
127                                 } elseif ( 0 === $post_id && ! current_user_can( 'moderate_comments' ) ) {
128                                         return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read comments without a post.' ), array( 'status' => rest_authorization_required_code() ) );
129                                 }
130                         }
131                 }
132
133                 if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
134                         return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
135                 }
136
137                 if ( ! current_user_can( 'edit_posts' ) ) {
138                         $protected_params = array( 'author', 'author_exclude', 'author_email', 'type', 'status' );
139                         $forbidden_params = array();
140
141                         foreach ( $protected_params as $param ) {
142                                 if ( 'status' === $param ) {
143                                         if ( 'approve' !== $request[ $param ] ) {
144                                                 $forbidden_params[] = $param;
145                                         }
146                                 } elseif ( 'type' === $param ) {
147                                         if ( 'comment' !== $request[ $param ] ) {
148                                                 $forbidden_params[] = $param;
149                                         }
150                                 } elseif ( ! empty( $request[ $param ] ) ) {
151                                         $forbidden_params[] = $param;
152                                 }
153                         }
154
155                         if ( ! empty( $forbidden_params ) ) {
156                                 return new WP_Error( 'rest_forbidden_param', sprintf( __( 'Query parameter not permitted: %s' ), implode( ', ', $forbidden_params ) ), array( 'status' => rest_authorization_required_code() ) );
157                         }
158                 }
159
160                 return true;
161         }
162
163         /**
164          * Retrieves a list of comment items.
165          *
166          * @since 4.7.0
167          * @access public
168          *
169          * @param WP_REST_Request $request Full details about the request.
170          * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
171          */
172         public function get_items( $request ) {
173
174                 // Retrieve the list of registered collection query parameters.
175                 $registered = $this->get_collection_params();
176
177                 /*
178                  * This array defines mappings between public API query parameters whose
179                  * values are accepted as-passed, and their internal WP_Query parameter
180                  * name equivalents (some are the same). Only values which are also
181                  * present in $registered will be set.
182                  */
183                 $parameter_mappings = array(
184                         'author'         => 'author__in',
185                         'author_email'   => 'author_email',
186                         'author_exclude' => 'author__not_in',
187                         'exclude'        => 'comment__not_in',
188                         'include'        => 'comment__in',
189                         'offset'         => 'offset',
190                         'order'          => 'order',
191                         'parent'         => 'parent__in',
192                         'parent_exclude' => 'parent__not_in',
193                         'per_page'       => 'number',
194                         'post'           => 'post__in',
195                         'search'         => 'search',
196                         'status'         => 'status',
197                         'type'           => 'type',
198                 );
199
200                 $prepared_args = array();
201
202                 /*
203                  * For each known parameter which is both registered and present in the request,
204                  * set the parameter's value on the query $prepared_args.
205                  */
206                 foreach ( $parameter_mappings as $api_param => $wp_param ) {
207                         if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
208                                 $prepared_args[ $wp_param ] = $request[ $api_param ];
209                         }
210                 }
211
212                 // Ensure certain parameter values default to empty strings.
213                 foreach ( array( 'author_email', 'search' ) as $param ) {
214                         if ( ! isset( $prepared_args[ $param ] ) ) {
215                                 $prepared_args[ $param ] = '';
216                         }
217                 }
218
219                 if ( isset( $registered['orderby'] ) ) {
220                         $prepared_args['orderby'] = $this->normalize_query_param( $request['orderby'] );
221                 }
222
223                 $prepared_args['no_found_rows'] = false;
224
225                 $prepared_args['date_query'] = array();
226
227                 // Set before into date query. Date query must be specified as an array of an array.
228                 if ( isset( $registered['before'], $request['before'] ) ) {
229                         $prepared_args['date_query'][0]['before'] = $request['before'];
230                 }
231
232                 // Set after into date query. Date query must be specified as an array of an array.
233                 if ( isset( $registered['after'], $request['after'] ) ) {
234                         $prepared_args['date_query'][0]['after'] = $request['after'];
235                 }
236
237                 if ( isset( $registered['page'] ) && empty( $request['offset'] ) ) {
238                         $prepared_args['offset'] = $prepared_args['number'] * ( absint( $request['page'] ) - 1 );
239                 }
240
241                 /**
242                  * Filters arguments, before passing to WP_Comment_Query, when querying comments via the REST API.
243                  *
244                  * @since 4.7.0
245                  *
246                  * @link https://developer.wordpress.org/reference/classes/wp_comment_query/
247                  *
248                  * @param array           $prepared_args Array of arguments for WP_Comment_Query.
249                  * @param WP_REST_Request $request       The current request.
250                  */
251                 $prepared_args = apply_filters( 'rest_comment_query', $prepared_args, $request );
252
253                 $query = new WP_Comment_Query;
254                 $query_result = $query->query( $prepared_args );
255
256                 $comments = array();
257
258                 foreach ( $query_result as $comment ) {
259                         if ( ! $this->check_read_permission( $comment, $request ) ) {
260                                 continue;
261                         }
262
263                         $data = $this->prepare_item_for_response( $comment, $request );
264                         $comments[] = $this->prepare_response_for_collection( $data );
265                 }
266
267                 $total_comments = (int) $query->found_comments;
268                 $max_pages      = (int) $query->max_num_pages;
269
270                 if ( $total_comments < 1 ) {
271                         // Out-of-bounds, run the query again without LIMIT for total count.
272                         unset( $prepared_args['number'], $prepared_args['offset'] );
273
274                         $query = new WP_Comment_Query;
275                         $prepared_args['count'] = true;
276
277                         $total_comments = $query->query( $prepared_args );
278                         $max_pages = ceil( $total_comments / $request['per_page'] );
279                 }
280
281                 $response = rest_ensure_response( $comments );
282                 $response->header( 'X-WP-Total', $total_comments );
283                 $response->header( 'X-WP-TotalPages', $max_pages );
284
285                 $base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
286
287                 if ( $request['page'] > 1 ) {
288                         $prev_page = $request['page'] - 1;
289
290                         if ( $prev_page > $max_pages ) {
291                                 $prev_page = $max_pages;
292                         }
293
294                         $prev_link = add_query_arg( 'page', $prev_page, $base );
295                         $response->link_header( 'prev', $prev_link );
296                 }
297
298                 if ( $max_pages > $request['page'] ) {
299                         $next_page = $request['page'] + 1;
300                         $next_link = add_query_arg( 'page', $next_page, $base );
301
302                         $response->link_header( 'next', $next_link );
303                 }
304
305                 return $response;
306         }
307
308         /**
309          * Get the comment, if the ID is valid.
310          *
311          * @since 4.7.2
312          *
313          * @param int $id Supplied ID.
314          * @return WP_Comment|WP_Error Comment object if ID is valid, WP_Error otherwise.
315          */
316         protected function get_comment( $id ) {
317                 $error = new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
318                 if ( (int) $id <= 0 ) {
319                         return $error;
320                 }
321
322                 $id = (int) $id;
323                 $comment = get_comment( $id );
324                 if ( empty( $comment ) ) {
325                         return $error;
326                 }
327
328                 if ( ! empty( $comment->comment_post_ID ) ) {
329                         $post = get_post( (int) $comment->comment_post_ID );
330                         if ( empty( $post ) ) {
331                                 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
332                         }
333                 }
334
335                 return $comment;
336         }
337
338         /**
339          * Checks if a given request has access to read the comment.
340          *
341          * @since 4.7.0
342          * @access public
343          *
344          * @param WP_REST_Request $request Full details about the request.
345          * @return WP_Error|bool True if the request has read access for the item, error object otherwise.
346          */
347         public function get_item_permissions_check( $request ) {
348                 $comment = $this->get_comment( $request['id'] );
349                 if ( is_wp_error( $comment ) ) {
350                         return $comment;
351                 }
352
353                 if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
354                         return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
355                 }
356
357                 $post = get_post( $comment->comment_post_ID );
358
359                 if ( ! $this->check_read_permission( $comment, $request ) ) {
360                         return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read this comment.' ), array( 'status' => rest_authorization_required_code() ) );
361                 }
362
363                 if ( $post && ! $this->check_read_post_permission( $post, $request ) ) {
364                         return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
365                 }
366
367                 return true;
368         }
369
370         /**
371          * Retrieves a comment.
372          *
373          * @since 4.7.0
374          * @access public
375          *
376          * @param WP_REST_Request $request Full details about the request.
377          * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
378          */
379         public function get_item( $request ) {
380                 $comment = $this->get_comment( $request['id'] );
381                 if ( is_wp_error( $comment ) ) {
382                         return $comment;
383                 }
384
385                 $data = $this->prepare_item_for_response( $comment, $request );
386                 $response = rest_ensure_response( $data );
387
388                 return $response;
389         }
390
391         /**
392          * Checks if a given request has access to create a comment.
393          *
394          * @since 4.7.0
395          * @access public
396          *
397          * @param WP_REST_Request $request Full details about the request.
398          * @return WP_Error|bool True if the request has access to create items, error object otherwise.
399          */
400         public function create_item_permissions_check( $request ) {
401                 if ( ! is_user_logged_in() ) {
402                         if ( get_option( 'comment_registration' ) ) {
403                                 return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
404                         }
405
406                         /**
407                          * Filter whether comments can be created without authentication.
408                          *
409                          * Enables creating comments for anonymous users.
410                          *
411                          * @since 4.7.0
412                          *
413                          * @param bool $allow_anonymous Whether to allow anonymous comments to
414                          *                              be created. Default `false`.
415                          * @param WP_REST_Request $request Request used to generate the
416                          *                                 response.
417                          */
418                         $allow_anonymous = apply_filters( 'rest_allow_anonymous_comments', false, $request );
419                         if ( ! $allow_anonymous ) {
420                                 return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
421                         }
422                 }
423
424                 // Limit who can set comment `author`, `author_ip` or `status` to anything other than the default.
425                 if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( 'moderate_comments' ) ) {
426                         return new WP_Error( 'rest_comment_invalid_author',
427                                 /* translators: %s: request parameter */
428                                 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ),
429                                 array( 'status' => rest_authorization_required_code() )
430                         );
431                 }
432
433                 if ( isset( $request['author_ip'] ) && ! current_user_can( 'moderate_comments' ) ) {
434                         if ( empty( $_SERVER['REMOTE_ADDR'] ) || $request['author_ip'] !== $_SERVER['REMOTE_ADDR'] ) {
435                                 return new WP_Error( 'rest_comment_invalid_author_ip',
436                                         /* translators: %s: request parameter */
437                                         sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author_ip' ),
438                                         array( 'status' => rest_authorization_required_code() )
439                                 );
440                         }
441                 }
442
443                 if ( isset( $request['status'] ) && ! current_user_can( 'moderate_comments' ) ) {
444                         return new WP_Error( 'rest_comment_invalid_status',
445                                 /* translators: %s: request parameter */
446                                 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'status' ),
447                                 array( 'status' => rest_authorization_required_code() )
448                         );
449                 }
450
451                 if ( empty( $request['post'] ) ) {
452                         return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
453                 }
454
455                 $post = get_post( (int) $request['post'] );
456                 if ( ! $post ) {
457                         return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
458                 }
459
460                 if ( 'draft' === $post->post_status ) {
461                         return new WP_Error( 'rest_comment_draft_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
462                 }
463
464                 if ( 'trash' === $post->post_status ) {
465                         return new WP_Error( 'rest_comment_trash_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
466                 }
467
468                 if ( ! $this->check_read_post_permission( $post, $request ) ) {
469                         return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
470                 }
471
472                 if ( ! comments_open( $post->ID ) ) {
473                         return new WP_Error( 'rest_comment_closed', __( 'Sorry, comments are closed for this item.' ), array( 'status' => 403 ) );
474                 }
475
476                 return true;
477         }
478
479         /**
480          * Creates a comment.
481          *
482          * @since 4.7.0
483          * @access public
484          *
485          * @param WP_REST_Request $request Full details about the request.
486          * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
487          */
488         public function create_item( $request ) {
489                 if ( ! empty( $request['id'] ) ) {
490                         return new WP_Error( 'rest_comment_exists', __( 'Cannot create existing comment.' ), array( 'status' => 400 ) );
491                 }
492
493                 // Do not allow comments to be created with a non-default type.
494                 if ( ! empty( $request['type'] ) && 'comment' !== $request['type'] ) {
495                         return new WP_Error( 'rest_invalid_comment_type', __( 'Cannot create a comment with that type.' ), array( 'status' => 400 ) );
496                 }
497
498                 $prepared_comment = $this->prepare_item_for_database( $request );
499                 if ( is_wp_error( $prepared_comment ) ) {
500                         return $prepared_comment;
501                 }
502
503                 $prepared_comment['comment_type'] = '';
504
505                 /*
506                  * Do not allow a comment to be created with missing or empty
507                  * comment_content. See wp_handle_comment_submission().
508                  */
509                 if ( empty( $prepared_comment['comment_content'] ) ) {
510                         return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
511                 }
512
513                 // Setting remaining values before wp_insert_comment so we can use wp_allow_comment().
514                 if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) {
515                         $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true );
516                 }
517
518                 // Set author data if the user's logged in.
519                 $missing_author = empty( $prepared_comment['user_id'] )
520                         && empty( $prepared_comment['comment_author'] )
521                         && empty( $prepared_comment['comment_author_email'] )
522                         && empty( $prepared_comment['comment_author_url'] );
523
524                 if ( is_user_logged_in() && $missing_author ) {
525                         $user = wp_get_current_user();
526
527                         $prepared_comment['user_id'] = $user->ID;
528                         $prepared_comment['comment_author'] = $user->display_name;
529                         $prepared_comment['comment_author_email'] = $user->user_email;
530                         $prepared_comment['comment_author_url'] = $user->user_url;
531                 }
532
533                 // Honor the discussion setting that requires a name and email address of the comment author.
534                 if ( get_option( 'require_name_email' ) ) {
535                         if ( empty( $prepared_comment['comment_author'] ) || empty( $prepared_comment['comment_author_email'] ) ) {
536                                 return new WP_Error( 'rest_comment_author_data_required', __( 'Creating a comment requires valid author name and email values.' ), array( 'status' => 400 ) );
537                         }
538                 }
539
540                 if ( ! isset( $prepared_comment['comment_author_email'] ) ) {
541                         $prepared_comment['comment_author_email'] = '';
542                 }
543
544                 if ( ! isset( $prepared_comment['comment_author_url'] ) ) {
545                         $prepared_comment['comment_author_url'] = '';
546                 }
547
548                 if ( ! isset( $prepared_comment['comment_agent'] ) ) {
549                         $prepared_comment['comment_agent'] = '';
550                 }
551
552                 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_comment );
553                 if ( is_wp_error( $check_comment_lengths ) ) {
554                         $error_code = $check_comment_lengths->get_error_code();
555                         return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
556                 }
557
558                 $prepared_comment['comment_approved'] = wp_allow_comment( $prepared_comment, true );
559
560                 if ( is_wp_error( $prepared_comment['comment_approved'] ) ) {
561                         $error_code    = $prepared_comment['comment_approved']->get_error_code();
562                         $error_message = $prepared_comment['comment_approved']->get_error_message();
563
564                         if ( 'comment_duplicate' === $error_code ) {
565                                 return new WP_Error( $error_code, $error_message, array( 'status' => 409 ) );
566                         }
567
568                         if ( 'comment_flood' === $error_code ) {
569                                 return new WP_Error( $error_code, $error_message, array( 'status' => 400 ) );
570                         }
571
572                         return $prepared_comment['comment_approved'];
573                 }
574
575                 /**
576                  * Filters a comment before it is inserted via the REST API.
577                  *
578                  * Allows modification of the comment right before it is inserted via wp_insert_comment().
579                  *
580                  * @since 4.7.0
581                  *
582                  * @param array           $prepared_comment The prepared comment data for wp_insert_comment().
583                  * @param WP_REST_Request $request          Request used to insert the comment.
584                  */
585                 $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request );
586
587                 $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) );
588
589                 if ( ! $comment_id ) {
590                         return new WP_Error( 'rest_comment_failed_create', __( 'Creating comment failed.' ), array( 'status' => 500 ) );
591                 }
592
593                 if ( isset( $request['status'] ) ) {
594                         $this->handle_status_param( $request['status'], $comment_id );
595                 }
596
597                 $comment = get_comment( $comment_id );
598
599                 /**
600                  * Fires after a comment is created or updated via the REST API.
601                  *
602                  * @since 4.7.0
603                  *
604                  * @param WP_Comment      $comment  Inserted or updated comment object.
605                  * @param WP_REST_Request $request  Request object.
606                  * @param bool            $creating True when creating a comment, false
607                  *                                  when updating.
608                  */
609                 do_action( 'rest_insert_comment', $comment, $request, true );
610
611                 $schema = $this->get_item_schema();
612
613                 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
614                         $meta_update = $this->meta->update_value( $request['meta'], $comment_id );
615
616                         if ( is_wp_error( $meta_update ) ) {
617                                 return $meta_update;
618                         }
619                 }
620
621                 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
622
623                 if ( is_wp_error( $fields_update ) ) {
624                         return $fields_update;
625                 }
626
627                 $context = current_user_can( 'moderate_comments' ) ? 'edit' : 'view';
628
629                 $request->set_param( 'context', $context );
630
631                 $response = $this->prepare_item_for_response( $comment, $request );
632                 $response = rest_ensure_response( $response );
633
634                 $response->set_status( 201 );
635                 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment_id ) ) );
636
637
638                 return $response;
639         }
640
641         /**
642          * Checks if a given REST request has access to update a comment.
643          *
644          * @since 4.7.0
645          * @access public
646          *
647          * @param WP_REST_Request $request Full details about the request.
648          * @return WP_Error|bool True if the request has access to update the item, error object otherwise.
649          */
650         public function update_item_permissions_check( $request ) {
651                 $comment = $this->get_comment( $request['id'] );
652                 if ( is_wp_error( $comment ) ) {
653                         return $comment;
654                 }
655
656                 if ( ! $this->check_edit_permission( $comment ) ) {
657                         return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this comment.' ), array( 'status' => rest_authorization_required_code() ) );
658                 }
659
660                 return true;
661         }
662
663         /**
664          * Updates a comment.
665          *
666          * @since 4.7.0
667          * @access public
668          *
669          * @param WP_REST_Request $request Full details about the request.
670          * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
671          */
672         public function update_item( $request ) {
673                 $comment = $this->get_comment( $request['id'] );
674                 if ( is_wp_error( $comment ) ) {
675                         return $comment;
676                 }
677
678                 $id = $comment->comment_ID;
679
680                 if ( isset( $request['type'] ) && get_comment_type( $id ) !== $request['type'] ) {
681                         return new WP_Error( 'rest_comment_invalid_type', __( 'Sorry, you are not allowed to change the comment type.' ), array( 'status' => 404 ) );
682                 }
683
684                 $prepared_args = $this->prepare_item_for_database( $request );
685
686                 if ( is_wp_error( $prepared_args ) ) {
687                         return $prepared_args;
688                 }
689
690                 if ( ! empty( $prepared_args['comment_post_ID'] ) ) {
691                         $post = get_post( $prepared_args['comment_post_ID'] );
692                         if ( empty( $post ) ) {
693                                 return new WP_Error( 'rest_comment_invalid_post_id', __( 'Invalid post ID.' ), array( 'status' => 403 ) );
694                         }
695                 }
696
697                 if ( empty( $prepared_args ) && isset( $request['status'] ) ) {
698                         // Only the comment status is being changed.
699                         $change = $this->handle_status_param( $request['status'], $id );
700
701                         if ( ! $change ) {
702                                 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment status failed.' ), array( 'status' => 500 ) );
703                         }
704                 } elseif ( ! empty( $prepared_args ) ) {
705                         if ( is_wp_error( $prepared_args ) ) {
706                                 return $prepared_args;
707                         }
708
709                         if ( isset( $prepared_args['comment_content'] ) && empty( $prepared_args['comment_content'] ) ) {
710                                 return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
711                         }
712
713                         $prepared_args['comment_ID'] = $id;
714
715                         $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args );
716                         if ( is_wp_error( $check_comment_lengths ) ) {
717                                 $error_code = $check_comment_lengths->get_error_code();
718                                 return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
719                         }
720
721                         $updated = wp_update_comment( wp_slash( (array) $prepared_args ) );
722
723                         if ( false === $updated ) {
724                                 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment failed.' ), array( 'status' => 500 ) );
725                         }
726
727                         if ( isset( $request['status'] ) ) {
728                                 $this->handle_status_param( $request['status'], $id );
729                         }
730                 }
731
732                 $comment = get_comment( $id );
733
734                 /* This action is documented in lib/endpoints/class-wp-rest-comments-controller.php */
735                 do_action( 'rest_insert_comment', $comment, $request, false );
736
737                 $schema = $this->get_item_schema();
738
739                 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
740                         $meta_update = $this->meta->update_value( $request['meta'], $id );
741
742                         if ( is_wp_error( $meta_update ) ) {
743                                 return $meta_update;
744                         }
745                 }
746
747                 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
748
749                 if ( is_wp_error( $fields_update ) ) {
750                         return $fields_update;
751                 }
752
753                 $request->set_param( 'context', 'edit' );
754
755                 $response = $this->prepare_item_for_response( $comment, $request );
756
757                 return rest_ensure_response( $response );
758         }
759
760         /**
761          * Checks if a given request has access to delete a comment.
762          *
763          * @since 4.7.0
764          * @access public
765          *
766          * @param WP_REST_Request $request Full details about the request.
767          * @return WP_Error|bool True if the request has access to delete the item, error object otherwise.
768          */
769         public function delete_item_permissions_check( $request ) {
770                 $comment = $this->get_comment( $request['id'] );
771                 if ( is_wp_error( $comment ) ) {
772                         return $comment;
773                 }
774
775                 if ( ! $this->check_edit_permission( $comment ) ) {
776                         return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => rest_authorization_required_code() ) );
777                 }
778                 return true;
779         }
780
781         /**
782          * Deletes a comment.
783          *
784          * @since 4.7.0
785          * @access public
786          *
787          * @param WP_REST_Request $request Full details about the request.
788          * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
789          */
790         public function delete_item( $request ) {
791                 $comment = $this->get_comment( $request['id'] );
792                 if ( is_wp_error( $comment ) ) {
793                         return $comment;
794                 }
795
796                 $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
797
798                 /**
799                  * Filters whether a comment can be trashed.
800                  *
801                  * Return false to disable trash support for the post.
802                  *
803                  * @since 4.7.0
804                  *
805                  * @param bool    $supports_trash Whether the post type support trashing.
806                  * @param WP_Post $comment        The comment object being considered for trashing support.
807                  */
808                 $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );
809
810                 $request->set_param( 'context', 'edit' );
811
812                 if ( $force ) {
813                         $previous = $this->prepare_item_for_response( $comment, $request );
814                         $result = wp_delete_comment( $comment->comment_ID, true );
815                         $response = new WP_REST_Response();
816                         $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
817                 } else {
818                         // If this type doesn't support trashing, error out.
819                         if ( ! $supports_trash ) {
820                                 return new WP_Error( 'rest_trash_not_supported', __( 'The comment does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
821                         }
822
823                         if ( 'trash' === $comment->comment_approved ) {
824                                 return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) );
825                         }
826
827                         $result = wp_trash_comment( $comment->comment_ID );
828                         $comment = get_comment( $comment->comment_ID );
829                         $response = $this->prepare_item_for_response( $comment, $request );
830                 }
831
832                 if ( ! $result ) {
833                         return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) );
834                 }
835
836                 /**
837                  * Fires after a comment is deleted via the REST API.
838                  *
839                  * @since 4.7.0
840                  *
841                  * @param WP_Comment       $comment  The deleted comment data.
842                  * @param WP_REST_Response $response The response returned from the API.
843                  * @param WP_REST_Request  $request  The request sent to the API.
844                  */
845                 do_action( 'rest_delete_comment', $comment, $response, $request );
846
847                 return $response;
848         }
849
850         /**
851          * Prepares a single comment output for response.
852          *
853          * @since 4.7.0
854          * @access public
855          *
856          * @param WP_Comment      $comment Comment object.
857          * @param WP_REST_Request $request Request object.
858          * @return WP_REST_Response Response object.
859          */
860         public function prepare_item_for_response( $comment, $request ) {
861                 $data = array(
862                         'id'                 => (int) $comment->comment_ID,
863                         'post'               => (int) $comment->comment_post_ID,
864                         'parent'             => (int) $comment->comment_parent,
865                         'author'             => (int) $comment->user_id,
866                         'author_name'        => $comment->comment_author,
867                         'author_email'       => $comment->comment_author_email,
868                         'author_url'         => $comment->comment_author_url,
869                         'author_ip'          => $comment->comment_author_IP,
870                         'author_user_agent'  => $comment->comment_agent,
871                         'date'               => mysql_to_rfc3339( $comment->comment_date ),
872                         'date_gmt'           => mysql_to_rfc3339( $comment->comment_date_gmt ),
873                         'content'            => array(
874                                 /** This filter is documented in wp-includes/comment-template.php */
875                                 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ),
876                                 'raw'      => $comment->comment_content,
877                         ),
878                         'link'               => get_comment_link( $comment ),
879                         'status'             => $this->prepare_status_response( $comment->comment_approved ),
880                         'type'               => get_comment_type( $comment->comment_ID ),
881                 );
882
883                 $schema = $this->get_item_schema();
884
885                 if ( ! empty( $schema['properties']['author_avatar_urls'] ) ) {
886                         $data['author_avatar_urls'] = rest_get_avatar_urls( $comment->comment_author_email );
887                 }
888
889                 if ( ! empty( $schema['properties']['meta'] ) ) {
890                         $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
891                 }
892
893                 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
894                 $data    = $this->add_additional_fields_to_object( $data, $request );
895                 $data    = $this->filter_response_by_context( $data, $context );
896
897                 // Wrap the data in a response object.
898                 $response = rest_ensure_response( $data );
899
900                 $response->add_links( $this->prepare_links( $comment ) );
901
902                 /**
903                  * Filters a comment returned from the API.
904                  *
905                  * Allows modification of the comment right before it is returned.
906                  *
907                  * @since 4.7.0
908                  *
909                  * @param WP_REST_Response  $response The response object.
910                  * @param WP_Comment        $comment  The original comment object.
911                  * @param WP_REST_Request   $request  Request used to generate the response.
912                  */
913                 return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
914         }
915
916         /**
917          * Prepares links for the request.
918          *
919          * @since 4.7.0
920          * @access protected
921          *
922          * @param WP_Comment $comment Comment object.
923          * @return array Links for the given comment.
924          */
925         protected function prepare_links( $comment ) {
926                 $links = array(
927                         'self' => array(
928                                 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ),
929                         ),
930                         'collection' => array(
931                                 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
932                         ),
933                 );
934
935                 if ( 0 !== (int) $comment->user_id ) {
936                         $links['author'] = array(
937                                 'href'       => rest_url( 'wp/v2/users/' . $comment->user_id ),
938                                 'embeddable' => true,
939                         );
940                 }
941
942                 if ( 0 !== (int) $comment->comment_post_ID ) {
943                         $post = get_post( $comment->comment_post_ID );
944
945                         if ( ! empty( $post->ID ) ) {
946                                 $obj = get_post_type_object( $post->post_type );
947                                 $base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
948
949                                 $links['up'] = array(
950                                         'href'       => rest_url( 'wp/v2/' . $base . '/' . $comment->comment_post_ID ),
951                                         'embeddable' => true,
952                                         'post_type'  => $post->post_type,
953                                 );
954                         }
955                 }
956
957                 if ( 0 !== (int) $comment->comment_parent ) {
958                         $links['in-reply-to'] = array(
959                                 'href'       => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ),
960                                 'embeddable' => true,
961                         );
962                 }
963
964                 // Only grab one comment to verify the comment has children.
965                 $comment_children = $comment->get_children( array(
966                         'number' => 1,
967                         'count'  => true
968                 ) );
969
970                 if ( ! empty( $comment_children ) ) {
971                         $args = array(
972                                 'parent' => $comment->comment_ID
973                         );
974
975                         $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
976
977                         $links['children'] = array(
978                                 'href' => $rest_url,
979                         );
980                 }
981
982                 return $links;
983         }
984
985         /**
986          * Prepends internal property prefix to query parameters to match our response fields.
987          *
988          * @since 4.7.0
989          * @access protected
990          *
991          * @param string $query_param Query parameter.
992          * @return string The normalized query parameter.
993          */
994         protected function normalize_query_param( $query_param ) {
995                 $prefix = 'comment_';
996
997                 switch ( $query_param ) {
998                         case 'id':
999                                 $normalized = $prefix . 'ID';
1000                                 break;
1001                         case 'post':
1002                                 $normalized = $prefix . 'post_ID';
1003                                 break;
1004                         case 'parent':
1005                                 $normalized = $prefix . 'parent';
1006                                 break;
1007                         case 'include':
1008                                 $normalized = 'comment__in';
1009                                 break;
1010                         default:
1011                                 $normalized = $prefix . $query_param;
1012                                 break;
1013                 }
1014
1015                 return $normalized;
1016         }
1017
1018         /**
1019          * Checks comment_approved to set comment status for single comment output.
1020          *
1021          * @since 4.7.0
1022          * @access protected
1023          *
1024          * @param string|int $comment_approved comment status.
1025          * @return string Comment status.
1026          */
1027         protected function prepare_status_response( $comment_approved ) {
1028
1029                 switch ( $comment_approved ) {
1030                         case 'hold':
1031                         case '0':
1032                                 $status = 'hold';
1033                                 break;
1034
1035                         case 'approve':
1036                         case '1':
1037                                 $status = 'approved';
1038                                 break;
1039
1040                         case 'spam':
1041                         case 'trash':
1042                         default:
1043                                 $status = $comment_approved;
1044                                 break;
1045                 }
1046
1047                 return $status;
1048         }
1049
1050         /**
1051          * Prepares a single comment to be inserted into the database.
1052          *
1053          * @since 4.7.0
1054          * @access protected
1055          *
1056          * @param WP_REST_Request $request Request object.
1057          * @return array|WP_Error Prepared comment, otherwise WP_Error object.
1058          */
1059         protected function prepare_item_for_database( $request ) {
1060                 $prepared_comment = array();
1061
1062                 /*
1063                  * Allow the comment_content to be set via the 'content' or
1064                  * the 'content.raw' properties of the Request object.
1065                  */
1066                 if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
1067                         $prepared_comment['comment_content'] = $request['content'];
1068                 } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
1069                         $prepared_comment['comment_content'] = $request['content']['raw'];
1070                 }
1071
1072                 if ( isset( $request['post'] ) ) {
1073                         $prepared_comment['comment_post_ID'] = (int) $request['post'];
1074                 }
1075
1076                 if ( isset( $request['parent'] ) ) {
1077                         $prepared_comment['comment_parent'] = $request['parent'];
1078                 }
1079
1080                 if ( isset( $request['author'] ) ) {
1081                         $user = new WP_User( $request['author'] );
1082
1083                         if ( $user->exists() ) {
1084                                 $prepared_comment['user_id'] = $user->ID;
1085                                 $prepared_comment['comment_author'] = $user->display_name;
1086                                 $prepared_comment['comment_author_email'] = $user->user_email;
1087                                 $prepared_comment['comment_author_url'] = $user->user_url;
1088                         } else {
1089                                 return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) );
1090                         }
1091                 }
1092
1093                 if ( isset( $request['author_name'] ) ) {
1094                         $prepared_comment['comment_author'] = $request['author_name'];
1095                 }
1096
1097                 if ( isset( $request['author_email'] ) ) {
1098                         $prepared_comment['comment_author_email'] = $request['author_email'];
1099                 }
1100
1101                 if ( isset( $request['author_url'] ) ) {
1102                         $prepared_comment['comment_author_url'] = $request['author_url'];
1103                 }
1104
1105                 if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) {
1106                         $prepared_comment['comment_author_IP'] = $request['author_ip'];
1107                 } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) {
1108                         $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1109                 } else {
1110                         $prepared_comment['comment_author_IP'] = '127.0.0.1';
1111                 }
1112
1113                 if ( ! empty( $request['author_user_agent'] ) ) {
1114                         $prepared_comment['comment_agent'] = $request['author_user_agent'];
1115                 } elseif ( $request->get_header( 'user_agent' ) ) {
1116                         $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' );
1117                 }
1118
1119                 if ( ! empty( $request['date'] ) ) {
1120                         $date_data = rest_get_date_with_gmt( $request['date'] );
1121
1122                         if ( ! empty( $date_data ) ) {
1123                                 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1124                         }
1125                 } elseif ( ! empty( $request['date_gmt'] ) ) {
1126                         $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
1127
1128                         if ( ! empty( $date_data ) ) {
1129                                 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1130                         }
1131                 }
1132
1133                 /**
1134                  * Filters a comment after it is prepared for the database.
1135                  *
1136                  * Allows modification of the comment right after it is prepared for the database.
1137                  *
1138                  * @since 4.7.0
1139                  *
1140                  * @param array           $prepared_comment The prepared comment data for `wp_insert_comment`.
1141                  * @param WP_REST_Request $request          The current request.
1142                  */
1143                 return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request );
1144         }
1145
1146         /**
1147          * Retrieves the comment's schema, conforming to JSON Schema.
1148          *
1149          * @since 4.7.0
1150          * @access public
1151          *
1152          * @return array
1153          */
1154         public function get_item_schema() {
1155                 $schema = array(
1156                         '$schema'              => 'http://json-schema.org/schema#',
1157                         'title'                => 'comment',
1158                         'type'                 => 'object',
1159                         'properties'           => array(
1160                                 'id'               => array(
1161                                         'description'  => __( 'Unique identifier for the object.' ),
1162                                         'type'         => 'integer',
1163                                         'context'      => array( 'view', 'edit', 'embed' ),
1164                                         'readonly'     => true,
1165                                 ),
1166                                 'author'           => array(
1167                                         'description'  => __( 'The ID of the user object, if author was a user.' ),
1168                                         'type'         => 'integer',
1169                                         'context'      => array( 'view', 'edit', 'embed' ),
1170                                 ),
1171                                 'author_email'     => array(
1172                                         'description'  => __( 'Email address for the object author.' ),
1173                                         'type'         => 'string',
1174                                         'format'       => 'email',
1175                                         'context'      => array( 'edit' ),
1176                                         'arg_options'  => array(
1177                                                 'sanitize_callback' => array( $this, 'check_comment_author_email' ),
1178                                                 'validate_callback' => null, // skip built-in validation of 'email'.
1179                                         ),
1180                                 ),
1181                                 'author_ip'     => array(
1182                                         'description'  => __( 'IP address for the object author.' ),
1183                                         'type'         => 'string',
1184                                         'format'       => 'ip',
1185                                         'context'      => array( 'edit' ),
1186                                 ),
1187                                 'author_name'     => array(
1188                                         'description'  => __( 'Display name for the object author.' ),
1189                                         'type'         => 'string',
1190                                         'context'      => array( 'view', 'edit', 'embed' ),
1191                                         'arg_options'  => array(
1192                                                 'sanitize_callback' => 'sanitize_text_field',
1193                                         ),
1194                                 ),
1195                                 'author_url'       => array(
1196                                         'description'  => __( 'URL for the object author.' ),
1197                                         'type'         => 'string',
1198                                         'format'       => 'uri',
1199                                         'context'      => array( 'view', 'edit', 'embed' ),
1200                                 ),
1201                                 'author_user_agent'     => array(
1202                                         'description'  => __( 'User agent for the object author.' ),
1203                                         'type'         => 'string',
1204                                         'context'      => array( 'edit' ),
1205                                         'arg_options'  => array(
1206                                                 'sanitize_callback' => 'sanitize_text_field',
1207                                         ),
1208                                 ),
1209                                 'content'          => array(
1210                                         'description'     => __( 'The content for the object.' ),
1211                                         'type'            => 'object',
1212                                         'context'         => array( 'view', 'edit', 'embed' ),
1213                                         'arg_options'     => array(
1214                                                 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1215                                         ),
1216                                         'properties'      => array(
1217                                                 'raw'         => array(
1218                                                         'description'     => __( 'Content for the object, as it exists in the database.' ),
1219                                                         'type'            => 'string',
1220                                                         'context'         => array( 'edit' ),
1221                                                 ),
1222                                                 'rendered'    => array(
1223                                                         'description'     => __( 'HTML content for the object, transformed for display.' ),
1224                                                         'type'            => 'string',
1225                                                         'context'         => array( 'view', 'edit', 'embed' ),
1226                                                         'readonly'        => true,
1227                                                 ),
1228                                         ),
1229                                 ),
1230                                 'date'             => array(
1231                                         'description'  => __( "The date the object was published, in the site's timezone." ),
1232                                         'type'         => 'string',
1233                                         'format'       => 'date-time',
1234                                         'context'      => array( 'view', 'edit', 'embed' ),
1235                                 ),
1236                                 'date_gmt'         => array(
1237                                         'description'  => __( 'The date the object was published, as GMT.' ),
1238                                         'type'         => 'string',
1239                                         'format'       => 'date-time',
1240                                         'context'      => array( 'view', 'edit' ),
1241                                 ),
1242                                 'link'             => array(
1243                                         'description'  => __( 'URL to the object.' ),
1244                                         'type'         => 'string',
1245                                         'format'       => 'uri',
1246                                         'context'      => array( 'view', 'edit', 'embed' ),
1247                                         'readonly'     => true,
1248                                 ),
1249                                 'parent'           => array(
1250                                         'description'  => __( 'The ID for the parent of the object.' ),
1251                                         'type'         => 'integer',
1252                                         'context'      => array( 'view', 'edit', 'embed' ),
1253                                         'default'      => 0,
1254                                 ),
1255                                 'post'             => array(
1256                                         'description'  => __( 'The ID of the associated post object.' ),
1257                                         'type'         => 'integer',
1258                                         'context'      => array( 'view', 'edit' ),
1259                                         'default'      => 0,
1260                                 ),
1261                                 'status'           => array(
1262                                         'description'  => __( 'State of the object.' ),
1263                                         'type'         => 'string',
1264                                         'context'      => array( 'view', 'edit' ),
1265                                         'arg_options'  => array(
1266                                                 'sanitize_callback' => 'sanitize_key',
1267                                         ),
1268                                 ),
1269                                 'type'             => array(
1270                                         'description'  => __( 'Type of Comment for the object.' ),
1271                                         'type'         => 'string',
1272                                         'context'      => array( 'view', 'edit', 'embed' ),
1273                                         'readonly'     => true,
1274                                 ),
1275                         ),
1276                 );
1277
1278                 if ( get_option( 'show_avatars' ) ) {
1279                         $avatar_properties = array();
1280
1281                         $avatar_sizes = rest_get_avatar_sizes();
1282                         foreach ( $avatar_sizes as $size ) {
1283                                 $avatar_properties[ $size ] = array(
1284                                         /* translators: %d: avatar image size in pixels */
1285                                         'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
1286                                         'type'        => 'string',
1287                                         'format'      => 'uri',
1288                                         'context'     => array( 'embed', 'view', 'edit' ),
1289                                 );
1290                         }
1291
1292                         $schema['properties']['author_avatar_urls'] = array(
1293                                 'description'   => __( 'Avatar URLs for the object author.' ),
1294                                 'type'          => 'object',
1295                                 'context'       => array( 'view', 'edit', 'embed' ),
1296                                 'readonly'      => true,
1297                                 'properties'    => $avatar_properties,
1298                         );
1299                 }
1300
1301                 $schema['properties']['meta'] = $this->meta->get_field_schema();
1302
1303                 return $this->add_additional_fields_schema( $schema );
1304         }
1305
1306         /**
1307          * Retrieves the query params for collections.
1308          *
1309          * @since 4.7.0
1310          * @access public
1311          *
1312          * @return array Comments collection parameters.
1313          */
1314         public function get_collection_params() {
1315                 $query_params = parent::get_collection_params();
1316
1317                 $query_params['context']['default'] = 'view';
1318
1319                 $query_params['after'] = array(
1320                         'description'       => __( 'Limit response to comments published after a given ISO8601 compliant date.' ),
1321                         'type'              => 'string',
1322                         'format'            => 'date-time',
1323                 );
1324
1325                 $query_params['author'] = array(
1326                         'description'       => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ),
1327                         'type'              => 'array',
1328                         'items'             => array(
1329                                 'type'          => 'integer',
1330                         ),
1331                 );
1332
1333                 $query_params['author_exclude'] = array(
1334                         'description'       => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ),
1335                         'type'              => 'array',
1336                         'items'             => array(
1337                                 'type'          => 'integer',
1338                         ),
1339                 );
1340
1341                 $query_params['author_email'] = array(
1342                         'default'           => null,
1343                         'description'       => __( 'Limit result set to that from a specific author email. Requires authorization.' ),
1344                         'format'            => 'email',
1345                         'type'              => 'string',
1346                 );
1347
1348                 $query_params['before'] = array(
1349                         'description'       => __( 'Limit response to comments published before a given ISO8601 compliant date.' ),
1350                         'type'              => 'string',
1351                         'format'            => 'date-time',
1352                 );
1353
1354                 $query_params['exclude'] = array(
1355                         'description'        => __( 'Ensure result set excludes specific IDs.' ),
1356                         'type'               => 'array',
1357                         'items'              => array(
1358                                 'type'           => 'integer',
1359                         ),
1360                         'default'            => array(),
1361                 );
1362
1363                 $query_params['include'] = array(
1364                         'description'        => __( 'Limit result set to specific IDs.' ),
1365                         'type'               => 'array',
1366                         'items'              => array(
1367                                 'type'           => 'integer',
1368                         ),
1369                         'default'            => array(),
1370                 );
1371
1372                 $query_params['offset'] = array(
1373                         'description'        => __( 'Offset the result set by a specific number of items.' ),
1374                         'type'               => 'integer',
1375                 );
1376
1377                 $query_params['order']      = array(
1378                         'description'           => __( 'Order sort attribute ascending or descending.' ),
1379                         'type'                  => 'string',
1380                         'default'               => 'desc',
1381                         'enum'                  => array(
1382                                 'asc',
1383                                 'desc',
1384                         ),
1385                 );
1386
1387                 $query_params['orderby']    = array(
1388                         'description'           => __( 'Sort collection by object attribute.' ),
1389                         'type'                  => 'string',
1390                         'default'               => 'date_gmt',
1391                         'enum'                  => array(
1392                                 'date',
1393                                 'date_gmt',
1394                                 'id',
1395                                 'include',
1396                                 'post',
1397                                 'parent',
1398                                 'type',
1399                         ),
1400                 );
1401
1402                 $query_params['parent'] = array(
1403                         'default'           => array(),
1404                         'description'       => __( 'Limit result set to comments of specific parent IDs.' ),
1405                         'type'              => 'array',
1406                         'items'             => array(
1407                                 'type'          => 'integer',
1408                         ),
1409                 );
1410
1411                 $query_params['parent_exclude'] = array(
1412                         'default'           => array(),
1413                         'description'       => __( 'Ensure result set excludes specific parent IDs.' ),
1414                         'type'              => 'array',
1415                         'items'             => array(
1416                                 'type'          => 'integer',
1417                         ),
1418                 );
1419
1420                 $query_params['post']   = array(
1421                         'default'           => array(),
1422                         'description'       => __( 'Limit result set to comments assigned to specific post IDs.' ),
1423                         'type'              => 'array',
1424                         'items'             => array(
1425                                 'type'          => 'integer',
1426                         ),
1427                 );
1428
1429                 $query_params['status'] = array(
1430                         'default'           => 'approve',
1431                         'description'       => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ),
1432                         'sanitize_callback' => 'sanitize_key',
1433                         'type'              => 'string',
1434                         'validate_callback' => 'rest_validate_request_arg',
1435                 );
1436
1437                 $query_params['type'] = array(
1438                         'default'           => 'comment',
1439                         'description'       => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ),
1440                         'sanitize_callback' => 'sanitize_key',
1441                         'type'              => 'string',
1442                         'validate_callback' => 'rest_validate_request_arg',
1443                 );
1444
1445                 $query_params['password'] = array(
1446                         'description' => __( 'The password for the post if it is password protected.' ),
1447                         'type'        => 'string',
1448                 );
1449
1450                 /**
1451                  * Filter collection parameters for the comments controller.
1452                  *
1453                  * This filter registers the collection parameter, but does not map the
1454                  * collection parameter to an internal WP_Comment_Query parameter. Use the
1455                  * `rest_comment_query` filter to set WP_Comment_Query parameters.
1456                  *
1457                  * @since 4.7.0
1458                  *
1459                  * @param array $query_params JSON Schema-formatted collection parameters.
1460                  */
1461                 return apply_filters( 'rest_comment_collection_params', $query_params );
1462         }
1463
1464         /**
1465          * Sets the comment_status of a given comment object when creating or updating a comment.
1466          *
1467          * @since 4.7.0
1468          * @access protected
1469          *
1470          * @param string|int $new_status New comment status.
1471          * @param int        $comment_id Comment ID.
1472          * @return bool Whether the status was changed.
1473          */
1474         protected function handle_status_param( $new_status, $comment_id ) {
1475                 $old_status = wp_get_comment_status( $comment_id );
1476
1477                 if ( $new_status === $old_status ) {
1478                         return false;
1479                 }
1480
1481                 switch ( $new_status ) {
1482                         case 'approved' :
1483                         case 'approve':
1484                         case '1':
1485                                 $changed = wp_set_comment_status( $comment_id, 'approve' );
1486                                 break;
1487                         case 'hold':
1488                         case '0':
1489                                 $changed = wp_set_comment_status( $comment_id, 'hold' );
1490                                 break;
1491                         case 'spam' :
1492                                 $changed = wp_spam_comment( $comment_id );
1493                                 break;
1494                         case 'unspam' :
1495                                 $changed = wp_unspam_comment( $comment_id );
1496                                 break;
1497                         case 'trash' :
1498                                 $changed = wp_trash_comment( $comment_id );
1499                                 break;
1500                         case 'untrash' :
1501                                 $changed = wp_untrash_comment( $comment_id );
1502                                 break;
1503                         default :
1504                                 $changed = false;
1505                                 break;
1506                 }
1507
1508                 return $changed;
1509         }
1510
1511         /**
1512          * Checks if the post can be read.
1513          *
1514          * Correctly handles posts with the inherit status.
1515          *
1516          * @since 4.7.0
1517          * @access protected
1518          *
1519          * @param WP_Post         $post    Post object.
1520          * @param WP_REST_Request $request Request data to check.
1521          * @return bool Whether post can be read.
1522          */
1523         protected function check_read_post_permission( $post, $request ) {
1524                 $posts_controller = new WP_REST_Posts_Controller( $post->post_type );
1525                 $post_type = get_post_type_object( $post->post_type );
1526
1527                 $has_password_filter = false;
1528
1529                 // Only check password if a specific post was queried for or a single comment
1530                 $requested_post = ! empty( $request['post'] ) && 1 === count( $request['post'] );
1531                 $requested_comment = ! empty( $request['id'] );
1532                 if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) {
1533                         add_filter( 'post_password_required', '__return_false' );
1534
1535                         $has_password_filter = true;
1536                 }
1537
1538                 if ( post_password_required( $post ) ) {
1539                         $result = current_user_can( $post_type->cap->edit_post, $post->ID );
1540                 } else {
1541                         $result = $posts_controller->check_read_permission( $post );
1542                 }
1543
1544                 if ( $has_password_filter ) {
1545                         remove_filter( 'post_password_required', '__return_false' );
1546                 }
1547
1548                 return $result;
1549         }
1550
1551         /**
1552          * Checks if the comment can be read.
1553          *
1554          * @since 4.7.0
1555          * @access protected
1556          *
1557          * @param WP_Comment      $comment Comment object.
1558          * @param WP_REST_Request $request Request data to check.
1559          * @return bool Whether the comment can be read.
1560          */
1561         protected function check_read_permission( $comment, $request ) {
1562                 if ( ! empty( $comment->comment_post_ID ) ) {
1563                         $post = get_post( $comment->comment_post_ID );
1564                         if ( $post ) {
1565                                 if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) {
1566                                         return true;
1567                                 }
1568                         }
1569                 }
1570
1571                 if ( 0 === get_current_user_id() ) {
1572                         return false;
1573                 }
1574
1575                 if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) {
1576                         return false;
1577                 }
1578
1579                 if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) {
1580                         return true;
1581                 }
1582
1583                 return current_user_can( 'edit_comment', $comment->comment_ID );
1584         }
1585
1586         /**
1587          * Checks if a comment can be edited or deleted.
1588          *
1589          * @since 4.7.0
1590          * @access protected
1591          *
1592          * @param object $comment Comment object.
1593          * @return bool Whether the comment can be edited or deleted.
1594          */
1595         protected function check_edit_permission( $comment ) {
1596                 if ( 0 === (int) get_current_user_id() ) {
1597                         return false;
1598                 }
1599
1600                 if ( ! current_user_can( 'moderate_comments' ) ) {
1601                         return false;
1602                 }
1603
1604                 return current_user_can( 'edit_comment', $comment->comment_ID );
1605         }
1606
1607         /**
1608          * Checks a comment author email for validity.
1609          *
1610          * Accepts either a valid email address or empty string as a valid comment
1611          * author email address. Setting the comment author email to an empty
1612          * string is allowed when a comment is being updated.
1613          *
1614          * @since 4.7.0
1615          *
1616          * @param string          $value   Author email value submitted.
1617          * @param WP_REST_Request $request Full details about the request.
1618          * @param string          $param   The parameter name.
1619          * @return WP_Error|string The sanitized email address, if valid,
1620          *                         otherwise an error.
1621          */
1622         public function check_comment_author_email( $value, $request, $param ) {
1623                 $email = (string) $value;
1624                 if ( empty( $email ) ) {
1625                         return $email;
1626                 }
1627
1628                 $check_email = rest_validate_request_arg( $email, $request, $param );
1629                 if ( is_wp_error( $check_email ) ) {
1630                         return $check_email;
1631                 }
1632
1633                 return $email;
1634         }
1635 }