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