]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php
WordPress 4.7
[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 ( false === $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 ) && isset( $request['status'] ) ) {
668                         // Only the comment status is being changed.
669                         $change = $this->handle_status_param( $request['status'], $id );
670
671                         if ( ! $change ) {
672                                 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment status failed.' ), array( 'status' => 500 ) );
673                         }
674                 } elseif ( ! empty( $prepared_args ) ) {
675                         if ( is_wp_error( $prepared_args ) ) {
676                                 return $prepared_args;
677                         }
678
679                         if ( isset( $prepared_args['comment_content'] ) && empty( $prepared_args['comment_content'] ) ) {
680                                 return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
681                         }
682
683                         $prepared_args['comment_ID'] = $id;
684
685                         $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args );
686                         if ( is_wp_error( $check_comment_lengths ) ) {
687                                 $error_code = $check_comment_lengths->get_error_code();
688                                 return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
689                         }
690
691                         $updated = wp_update_comment( wp_slash( (array) $prepared_args ) );
692
693                         if ( 0 === $updated ) {
694                                 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment failed.' ), array( 'status' => 500 ) );
695                         }
696
697                         if ( isset( $request['status'] ) ) {
698                                 $this->handle_status_param( $request['status'], $id );
699                         }
700                 }
701
702                 $comment = get_comment( $id );
703
704                 /* This action is documented in lib/endpoints/class-wp-rest-comments-controller.php */
705                 do_action( 'rest_insert_comment', $comment, $request, false );
706
707                 $schema = $this->get_item_schema();
708
709                 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
710                         $meta_update = $this->meta->update_value( $request['meta'], $id );
711
712                         if ( is_wp_error( $meta_update ) ) {
713                                 return $meta_update;
714                         }
715                 }
716
717                 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
718
719                 if ( is_wp_error( $fields_update ) ) {
720                         return $fields_update;
721                 }
722
723                 $request->set_param( 'context', 'edit' );
724
725                 $response = $this->prepare_item_for_response( $comment, $request );
726
727                 return rest_ensure_response( $response );
728         }
729
730         /**
731          * Checks if a given request has access to delete a comment.
732          *
733          * @since 4.7.0
734          * @access public
735          *
736          * @param WP_REST_Request $request Full details about the request.
737          * @return WP_Error|bool True if the request has access to delete the item, error object otherwise.
738          */
739         public function delete_item_permissions_check( $request ) {
740                 $id      = (int) $request['id'];
741                 $comment = get_comment( $id );
742
743                 if ( ! $comment ) {
744                         return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
745                 }
746
747                 if ( ! $this->check_edit_permission( $comment ) ) {
748                         return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => rest_authorization_required_code() ) );
749                 }
750                 return true;
751         }
752
753         /**
754          * Deletes a comment.
755          *
756          * @since 4.7.0
757          * @access public
758          *
759          * @param WP_REST_Request $request Full details about the request.
760          * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
761          */
762         public function delete_item( $request ) {
763                 $id    = (int) $request['id'];
764                 $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
765
766                 $comment = get_comment( $id );
767
768                 if ( empty( $comment ) ) {
769                         return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
770                 }
771
772                 /**
773                  * Filters whether a comment can be trashed.
774                  *
775                  * Return false to disable trash support for the post.
776                  *
777                  * @since 4.7.0
778                  *
779                  * @param bool    $supports_trash Whether the post type support trashing.
780                  * @param WP_Post $comment        The comment object being considered for trashing support.
781                  */
782                 $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );
783
784                 $request->set_param( 'context', 'edit' );
785
786                 if ( $force ) {
787                         $previous = $this->prepare_item_for_response( $comment, $request );
788                         $result = wp_delete_comment( $comment->comment_ID, true );
789                         $response = new WP_REST_Response();
790                         $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
791                 } else {
792                         // If this type doesn't support trashing, error out.
793                         if ( ! $supports_trash ) {
794                                 return new WP_Error( 'rest_trash_not_supported', __( 'The comment does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
795                         }
796
797                         if ( 'trash' === $comment->comment_approved ) {
798                                 return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) );
799                         }
800
801                         $result = wp_trash_comment( $comment->comment_ID );
802                         $comment = get_comment( $comment->comment_ID );
803                         $response = $this->prepare_item_for_response( $comment, $request );
804                 }
805
806                 if ( ! $result ) {
807                         return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) );
808                 }
809
810                 /**
811                  * Fires after a comment is deleted via the REST API.
812                  *
813                  * @since 4.7.0
814                  *
815                  * @param WP_Comment       $comment  The deleted comment data.
816                  * @param WP_REST_Response $response The response returned from the API.
817                  * @param WP_REST_Request  $request  The request sent to the API.
818                  */
819                 do_action( 'rest_delete_comment', $comment, $response, $request );
820
821                 return $response;
822         }
823
824         /**
825          * Prepares a single comment output for response.
826          *
827          * @since 4.7.0
828          * @access public
829          *
830          * @param WP_Comment      $comment Comment object.
831          * @param WP_REST_Request $request Request object.
832          * @return WP_REST_Response Response object.
833          */
834         public function prepare_item_for_response( $comment, $request ) {
835                 $data = array(
836                         'id'                 => (int) $comment->comment_ID,
837                         'post'               => (int) $comment->comment_post_ID,
838                         'parent'             => (int) $comment->comment_parent,
839                         'author'             => (int) $comment->user_id,
840                         'author_name'        => $comment->comment_author,
841                         'author_email'       => $comment->comment_author_email,
842                         'author_url'         => $comment->comment_author_url,
843                         'author_ip'          => $comment->comment_author_IP,
844                         'author_user_agent'  => $comment->comment_agent,
845                         'date'               => mysql_to_rfc3339( $comment->comment_date ),
846                         'date_gmt'           => mysql_to_rfc3339( $comment->comment_date_gmt ),
847                         'content'            => array(
848                                 /** This filter is documented in wp-includes/comment-template.php */
849                                 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ),
850                                 'raw'      => $comment->comment_content,
851                         ),
852                         'link'               => get_comment_link( $comment ),
853                         'status'             => $this->prepare_status_response( $comment->comment_approved ),
854                         'type'               => get_comment_type( $comment->comment_ID ),
855                 );
856
857                 $schema = $this->get_item_schema();
858
859                 if ( ! empty( $schema['properties']['author_avatar_urls'] ) ) {
860                         $data['author_avatar_urls'] = rest_get_avatar_urls( $comment->comment_author_email );
861                 }
862
863                 if ( ! empty( $schema['properties']['meta'] ) ) {
864                         $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
865                 }
866
867                 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
868                 $data    = $this->add_additional_fields_to_object( $data, $request );
869                 $data    = $this->filter_response_by_context( $data, $context );
870
871                 // Wrap the data in a response object.
872                 $response = rest_ensure_response( $data );
873
874                 $response->add_links( $this->prepare_links( $comment ) );
875
876                 /**
877                  * Filters a comment returned from the API.
878                  *
879                  * Allows modification of the comment right before it is returned.
880                  *
881                  * @since 4.7.0
882                  *
883                  * @param WP_REST_Response  $response The response object.
884                  * @param WP_Comment        $comment  The original comment object.
885                  * @param WP_REST_Request   $request  Request used to generate the response.
886                  */
887                 return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
888         }
889
890         /**
891          * Prepares links for the request.
892          *
893          * @since 4.7.0
894          * @access protected
895          *
896          * @param WP_Comment $comment Comment object.
897          * @return array Links for the given comment.
898          */
899         protected function prepare_links( $comment ) {
900                 $links = array(
901                         'self' => array(
902                                 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ),
903                         ),
904                         'collection' => array(
905                                 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
906                         ),
907                 );
908
909                 if ( 0 !== (int) $comment->user_id ) {
910                         $links['author'] = array(
911                                 'href'       => rest_url( 'wp/v2/users/' . $comment->user_id ),
912                                 'embeddable' => true,
913                         );
914                 }
915
916                 if ( 0 !== (int) $comment->comment_post_ID ) {
917                         $post = get_post( $comment->comment_post_ID );
918
919                         if ( ! empty( $post->ID ) ) {
920                                 $obj = get_post_type_object( $post->post_type );
921                                 $base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
922
923                                 $links['up'] = array(
924                                         'href'       => rest_url( 'wp/v2/' . $base . '/' . $comment->comment_post_ID ),
925                                         'embeddable' => true,
926                                         'post_type'  => $post->post_type,
927                                 );
928                         }
929                 }
930
931                 if ( 0 !== (int) $comment->comment_parent ) {
932                         $links['in-reply-to'] = array(
933                                 'href'       => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ),
934                                 'embeddable' => true,
935                         );
936                 }
937
938                 // Only grab one comment to verify the comment has children.
939                 $comment_children = $comment->get_children( array(
940                         'number' => 1,
941                         'count'  => true
942                 ) );
943
944                 if ( ! empty( $comment_children ) ) {
945                         $args = array(
946                                 'parent' => $comment->comment_ID
947                         );
948
949                         $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
950
951                         $links['children'] = array(
952                                 'href' => $rest_url,
953                         );
954                 }
955
956                 return $links;
957         }
958
959         /**
960          * Prepends internal property prefix to query parameters to match our response fields.
961          *
962          * @since 4.7.0
963          * @access protected
964          *
965          * @param string $query_param Query parameter.
966          * @return string The normalized query parameter.
967          */
968         protected function normalize_query_param( $query_param ) {
969                 $prefix = 'comment_';
970
971                 switch ( $query_param ) {
972                         case 'id':
973                                 $normalized = $prefix . 'ID';
974                                 break;
975                         case 'post':
976                                 $normalized = $prefix . 'post_ID';
977                                 break;
978                         case 'parent':
979                                 $normalized = $prefix . 'parent';
980                                 break;
981                         case 'include':
982                                 $normalized = 'comment__in';
983                                 break;
984                         default:
985                                 $normalized = $prefix . $query_param;
986                                 break;
987                 }
988
989                 return $normalized;
990         }
991
992         /**
993          * Checks comment_approved to set comment status for single comment output.
994          *
995          * @since 4.7.0
996          * @access protected
997          *
998          * @param string|int $comment_approved comment status.
999          * @return string Comment status.
1000          */
1001         protected function prepare_status_response( $comment_approved ) {
1002
1003                 switch ( $comment_approved ) {
1004                         case 'hold':
1005                         case '0':
1006                                 $status = 'hold';
1007                                 break;
1008
1009                         case 'approve':
1010                         case '1':
1011                                 $status = 'approved';
1012                                 break;
1013
1014                         case 'spam':
1015                         case 'trash':
1016                         default:
1017                                 $status = $comment_approved;
1018                                 break;
1019                 }
1020
1021                 return $status;
1022         }
1023
1024         /**
1025          * Prepares a single comment to be inserted into the database.
1026          *
1027          * @since 4.7.0
1028          * @access protected
1029          *
1030          * @param WP_REST_Request $request Request object.
1031          * @return array|WP_Error Prepared comment, otherwise WP_Error object.
1032          */
1033         protected function prepare_item_for_database( $request ) {
1034                 $prepared_comment = array();
1035
1036                 /*
1037                  * Allow the comment_content to be set via the 'content' or
1038                  * the 'content.raw' properties of the Request object.
1039                  */
1040                 if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
1041                         $prepared_comment['comment_content'] = $request['content'];
1042                 } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
1043                         $prepared_comment['comment_content'] = $request['content']['raw'];
1044                 }
1045
1046                 if ( isset( $request['post'] ) ) {
1047                         $prepared_comment['comment_post_ID'] = (int) $request['post'];
1048                 }
1049
1050                 if ( isset( $request['parent'] ) ) {
1051                         $prepared_comment['comment_parent'] = $request['parent'];
1052                 }
1053
1054                 if ( isset( $request['author'] ) ) {
1055                         $user = new WP_User( $request['author'] );
1056
1057                         if ( $user->exists() ) {
1058                                 $prepared_comment['user_id'] = $user->ID;
1059                                 $prepared_comment['comment_author'] = $user->display_name;
1060                                 $prepared_comment['comment_author_email'] = $user->user_email;
1061                                 $prepared_comment['comment_author_url'] = $user->user_url;
1062                         } else {
1063                                 return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) );
1064                         }
1065                 }
1066
1067                 if ( isset( $request['author_name'] ) ) {
1068                         $prepared_comment['comment_author'] = $request['author_name'];
1069                 }
1070
1071                 if ( isset( $request['author_email'] ) ) {
1072                         $prepared_comment['comment_author_email'] = $request['author_email'];
1073                 }
1074
1075                 if ( isset( $request['author_url'] ) ) {
1076                         $prepared_comment['comment_author_url'] = $request['author_url'];
1077                 }
1078
1079                 if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) {
1080                         $prepared_comment['comment_author_IP'] = $request['author_ip'];
1081                 } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) {
1082                         $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1083                 } else {
1084                         $prepared_comment['comment_author_IP'] = '127.0.0.1';
1085                 }
1086
1087                 if ( ! empty( $request['author_user_agent'] ) ) {
1088                         $prepared_comment['comment_agent'] = $request['author_user_agent'];
1089                 } elseif ( $request->get_header( 'user_agent' ) ) {
1090                         $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' );
1091                 }
1092
1093                 if ( ! empty( $request['date'] ) ) {
1094                         $date_data = rest_get_date_with_gmt( $request['date'] );
1095
1096                         if ( ! empty( $date_data ) ) {
1097                                 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1098                         }
1099                 } elseif ( ! empty( $request['date_gmt'] ) ) {
1100                         $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
1101
1102                         if ( ! empty( $date_data ) ) {
1103                                 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1104                         }
1105                 }
1106
1107                 /**
1108                  * Filters a comment after it is prepared for the database.
1109                  *
1110                  * Allows modification of the comment right after it is prepared for the database.
1111                  *
1112                  * @since 4.7.0
1113                  *
1114                  * @param array           $prepared_comment The prepared comment data for `wp_insert_comment`.
1115                  * @param WP_REST_Request $request          The current request.
1116                  */
1117                 return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request );
1118         }
1119
1120         /**
1121          * Retrieves the comment's schema, conforming to JSON Schema.
1122          *
1123          * @since 4.7.0
1124          * @access public
1125          *
1126          * @return array
1127          */
1128         public function get_item_schema() {
1129                 $schema = array(
1130                         '$schema'              => 'http://json-schema.org/schema#',
1131                         'title'                => 'comment',
1132                         'type'                 => 'object',
1133                         'properties'           => array(
1134                                 'id'               => array(
1135                                         'description'  => __( 'Unique identifier for the object.' ),
1136                                         'type'         => 'integer',
1137                                         'context'      => array( 'view', 'edit', 'embed' ),
1138                                         'readonly'     => true,
1139                                 ),
1140                                 'author'           => array(
1141                                         'description'  => __( 'The ID of the user object, if author was a user.' ),
1142                                         'type'         => 'integer',
1143                                         'context'      => array( 'view', 'edit', 'embed' ),
1144                                 ),
1145                                 'author_email'     => array(
1146                                         'description'  => __( 'Email address for the object author.' ),
1147                                         'type'         => 'string',
1148                                         'format'       => 'email',
1149                                         'context'      => array( 'edit' ),
1150                                         'arg_options'  => array(
1151                                                 'sanitize_callback' => array( $this, 'check_comment_author_email' ),
1152                                                 'validate_callback' => null, // skip built-in validation of 'email'.
1153                                         ),
1154                                 ),
1155                                 'author_ip'     => array(
1156                                         'description'  => __( 'IP address for the object author.' ),
1157                                         'type'         => 'string',
1158                                         'format'       => 'ip',
1159                                         'context'      => array( 'edit' ),
1160                                 ),
1161                                 'author_name'     => array(
1162                                         'description'  => __( 'Display name for the object author.' ),
1163                                         'type'         => 'string',
1164                                         'context'      => array( 'view', 'edit', 'embed' ),
1165                                         'arg_options'  => array(
1166                                                 'sanitize_callback' => 'sanitize_text_field',
1167                                         ),
1168                                 ),
1169                                 'author_url'       => array(
1170                                         'description'  => __( 'URL for the object author.' ),
1171                                         'type'         => 'string',
1172                                         'format'       => 'uri',
1173                                         'context'      => array( 'view', 'edit', 'embed' ),
1174                                 ),
1175                                 'author_user_agent'     => array(
1176                                         'description'  => __( 'User agent for the object author.' ),
1177                                         'type'         => 'string',
1178                                         'context'      => array( 'edit' ),
1179                                         'arg_options'  => array(
1180                                                 'sanitize_callback' => 'sanitize_text_field',
1181                                         ),
1182                                 ),
1183                                 'content'          => array(
1184                                         'description'     => __( 'The content for the object.' ),
1185                                         'type'            => 'object',
1186                                         'context'         => array( 'view', 'edit', 'embed' ),
1187                                         'arg_options'     => array(
1188                                                 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1189                                         ),
1190                                         'properties'      => array(
1191                                                 'raw'         => array(
1192                                                         'description'     => __( 'Content for the object, as it exists in the database.' ),
1193                                                         'type'            => 'string',
1194                                                         'context'         => array( 'edit' ),
1195                                                 ),
1196                                                 'rendered'    => array(
1197                                                         'description'     => __( 'HTML content for the object, transformed for display.' ),
1198                                                         'type'            => 'string',
1199                                                         'context'         => array( 'view', 'edit', 'embed' ),
1200                                                         'readonly'        => true,
1201                                                 ),
1202                                         ),
1203                                 ),
1204                                 'date'             => array(
1205                                         'description'  => __( "The date the object was published, in the site's timezone." ),
1206                                         'type'         => 'string',
1207                                         'format'       => 'date-time',
1208                                         'context'      => array( 'view', 'edit', 'embed' ),
1209                                 ),
1210                                 'date_gmt'         => array(
1211                                         'description'  => __( 'The date the object was published, as GMT.' ),
1212                                         'type'         => 'string',
1213                                         'format'       => 'date-time',
1214                                         'context'      => array( 'view', 'edit' ),
1215                                 ),
1216                                 'link'             => array(
1217                                         'description'  => __( 'URL to the object.' ),
1218                                         'type'         => 'string',
1219                                         'format'       => 'uri',
1220                                         'context'      => array( 'view', 'edit', 'embed' ),
1221                                         'readonly'     => true,
1222                                 ),
1223                                 'parent'           => array(
1224                                         'description'  => __( 'The ID for the parent of the object.' ),
1225                                         'type'         => 'integer',
1226                                         'context'      => array( 'view', 'edit', 'embed' ),
1227                                         'default'      => 0,
1228                                 ),
1229                                 'post'             => array(
1230                                         'description'  => __( 'The ID of the associated post object.' ),
1231                                         'type'         => 'integer',
1232                                         'context'      => array( 'view', 'edit' ),
1233                                         'default'      => 0,
1234                                 ),
1235                                 'status'           => array(
1236                                         'description'  => __( 'State of the object.' ),
1237                                         'type'         => 'string',
1238                                         'context'      => array( 'view', 'edit' ),
1239                                         'arg_options'  => array(
1240                                                 'sanitize_callback' => 'sanitize_key',
1241                                         ),
1242                                 ),
1243                                 'type'             => array(
1244                                         'description'  => __( 'Type of Comment for the object.' ),
1245                                         'type'         => 'string',
1246                                         'context'      => array( 'view', 'edit', 'embed' ),
1247                                         'readonly'     => true,
1248                                 ),
1249                         ),
1250                 );
1251
1252                 if ( get_option( 'show_avatars' ) ) {
1253                         $avatar_properties = array();
1254
1255                         $avatar_sizes = rest_get_avatar_sizes();
1256                         foreach ( $avatar_sizes as $size ) {
1257                                 $avatar_properties[ $size ] = array(
1258                                         /* translators: %d: avatar image size in pixels */
1259                                         'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
1260                                         'type'        => 'string',
1261                                         'format'      => 'uri',
1262                                         'context'     => array( 'embed', 'view', 'edit' ),
1263                                 );
1264                         }
1265
1266                         $schema['properties']['author_avatar_urls'] = array(
1267                                 'description'   => __( 'Avatar URLs for the object author.' ),
1268                                 'type'          => 'object',
1269                                 'context'       => array( 'view', 'edit', 'embed' ),
1270                                 'readonly'      => true,
1271                                 'properties'    => $avatar_properties,
1272                         );
1273                 }
1274
1275                 $schema['properties']['meta'] = $this->meta->get_field_schema();
1276
1277                 return $this->add_additional_fields_schema( $schema );
1278         }
1279
1280         /**
1281          * Retrieves the query params for collections.
1282          *
1283          * @since 4.7.0
1284          * @access public
1285          *
1286          * @return array Comments collection parameters.
1287          */
1288         public function get_collection_params() {
1289                 $query_params = parent::get_collection_params();
1290
1291                 $query_params['context']['default'] = 'view';
1292
1293                 $query_params['after'] = array(
1294                         'description'       => __( 'Limit response to comments published after a given ISO8601 compliant date.' ),
1295                         'type'              => 'string',
1296                         'format'            => 'date-time',
1297                 );
1298
1299                 $query_params['author'] = array(
1300                         'description'       => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ),
1301                         'type'              => 'array',
1302                         'items'             => array(
1303                                 'type'          => 'integer',
1304                         ),
1305                 );
1306
1307                 $query_params['author_exclude'] = array(
1308                         'description'       => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ),
1309                         'type'              => 'array',
1310                         'items'             => array(
1311                                 'type'          => 'integer',
1312                         ),
1313                 );
1314
1315                 $query_params['author_email'] = array(
1316                         'default'           => null,
1317                         'description'       => __( 'Limit result set to that from a specific author email. Requires authorization.' ),
1318                         'format'            => 'email',
1319                         'type'              => 'string',
1320                 );
1321
1322                 $query_params['before'] = array(
1323                         'description'       => __( 'Limit response to comments published before a given ISO8601 compliant date.' ),
1324                         'type'              => 'string',
1325                         'format'            => 'date-time',
1326                 );
1327
1328                 $query_params['exclude'] = array(
1329                         'description'        => __( 'Ensure result set excludes specific IDs.' ),
1330                         'type'               => 'array',
1331                         'items'              => array(
1332                                 'type'           => 'integer',
1333                         ),
1334                         'default'            => array(),
1335                 );
1336
1337                 $query_params['include'] = array(
1338                         'description'        => __( 'Limit result set to specific IDs.' ),
1339                         'type'               => 'array',
1340                         'items'              => array(
1341                                 'type'           => 'integer',
1342                         ),
1343                         'default'            => array(),
1344                 );
1345
1346                 $query_params['offset'] = array(
1347                         'description'        => __( 'Offset the result set by a specific number of items.' ),
1348                         'type'               => 'integer',
1349                 );
1350
1351                 $query_params['order']      = array(
1352                         'description'           => __( 'Order sort attribute ascending or descending.' ),
1353                         'type'                  => 'string',
1354                         'default'               => 'desc',
1355                         'enum'                  => array(
1356                                 'asc',
1357                                 'desc',
1358                         ),
1359                 );
1360
1361                 $query_params['orderby']    = array(
1362                         'description'           => __( 'Sort collection by object attribute.' ),
1363                         'type'                  => 'string',
1364                         'default'               => 'date_gmt',
1365                         'enum'                  => array(
1366                                 'date',
1367                                 'date_gmt',
1368                                 'id',
1369                                 'include',
1370                                 'post',
1371                                 'parent',
1372                                 'type',
1373                         ),
1374                 );
1375
1376                 $query_params['parent'] = array(
1377                         'default'           => array(),
1378                         'description'       => __( 'Limit result set to comments of specific parent IDs.' ),
1379                         'type'              => 'array',
1380                         'items'             => array(
1381                                 'type'          => 'integer',
1382                         ),
1383                 );
1384
1385                 $query_params['parent_exclude'] = array(
1386                         'default'           => array(),
1387                         'description'       => __( 'Ensure result set excludes specific parent IDs.' ),
1388                         'type'              => 'array',
1389                         'items'             => array(
1390                                 'type'          => 'integer',
1391                         ),
1392                 );
1393
1394                 $query_params['post']   = array(
1395                         'default'           => array(),
1396                         'description'       => __( 'Limit result set to comments assigned to specific post IDs.' ),
1397                         'type'              => 'array',
1398                         'items'             => array(
1399                                 'type'          => 'integer',
1400                         ),
1401                 );
1402
1403                 $query_params['status'] = array(
1404                         'default'           => 'approve',
1405                         'description'       => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ),
1406                         'sanitize_callback' => 'sanitize_key',
1407                         'type'              => 'string',
1408                         'validate_callback' => 'rest_validate_request_arg',
1409                 );
1410
1411                 $query_params['type'] = array(
1412                         'default'           => 'comment',
1413                         'description'       => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ),
1414                         'sanitize_callback' => 'sanitize_key',
1415                         'type'              => 'string',
1416                         'validate_callback' => 'rest_validate_request_arg',
1417                 );
1418
1419                 $query_params['password'] = array(
1420                         'description' => __( 'The password for the post if it is password protected.' ),
1421                         'type'        => 'string',
1422                 );
1423
1424                 /**
1425                  * Filter collection parameters for the comments controller.
1426                  *
1427                  * This filter registers the collection parameter, but does not map the
1428                  * collection parameter to an internal WP_Comment_Query parameter. Use the
1429                  * `rest_comment_query` filter to set WP_Comment_Query parameters.
1430                  *
1431                  * @since 4.7.0
1432                  *
1433                  * @param $params JSON Schema-formatted collection parameters.
1434                  */
1435                 return apply_filters( 'rest_comment_collection_params', $query_params );
1436         }
1437
1438         /**
1439          * Sets the comment_status of a given comment object when creating or updating a comment.
1440          *
1441          * @since 4.7.0
1442          * @access protected
1443          *
1444          * @param string|int $new_status New comment status.
1445          * @param int        $comment_id Comment ID.
1446          * @return bool Whether the status was changed.
1447          */
1448         protected function handle_status_param( $new_status, $comment_id ) {
1449                 $old_status = wp_get_comment_status( $comment_id );
1450
1451                 if ( $new_status === $old_status ) {
1452                         return false;
1453                 }
1454
1455                 switch ( $new_status ) {
1456                         case 'approved' :
1457                         case 'approve':
1458                         case '1':
1459                                 $changed = wp_set_comment_status( $comment_id, 'approve' );
1460                                 break;
1461                         case 'hold':
1462                         case '0':
1463                                 $changed = wp_set_comment_status( $comment_id, 'hold' );
1464                                 break;
1465                         case 'spam' :
1466                                 $changed = wp_spam_comment( $comment_id );
1467                                 break;
1468                         case 'unspam' :
1469                                 $changed = wp_unspam_comment( $comment_id );
1470                                 break;
1471                         case 'trash' :
1472                                 $changed = wp_trash_comment( $comment_id );
1473                                 break;
1474                         case 'untrash' :
1475                                 $changed = wp_untrash_comment( $comment_id );
1476                                 break;
1477                         default :
1478                                 $changed = false;
1479                                 break;
1480                 }
1481
1482                 return $changed;
1483         }
1484
1485         /**
1486          * Checks if the post can be read.
1487          *
1488          * Correctly handles posts with the inherit status.
1489          *
1490          * @since 4.7.0
1491          * @access protected
1492          *
1493          * @param WP_Post         $post    Post object.
1494          * @param WP_REST_Request $request Request data to check.
1495          * @return bool Whether post can be read.
1496          */
1497         protected function check_read_post_permission( $post, $request ) {
1498                 $posts_controller = new WP_REST_Posts_Controller( $post->post_type );
1499                 $post_type = get_post_type_object( $post->post_type );
1500
1501                 $has_password_filter = false;
1502
1503                 // Only check password if a specific post was queried for or a single comment
1504                 $requested_post = ! empty( $request['post'] ) && 1 === count( $request['post'] );
1505                 $requested_comment = ! empty( $request['id'] );
1506                 if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) {
1507                         add_filter( 'post_password_required', '__return_false' );
1508
1509                         $has_password_filter = true;
1510                 }
1511
1512                 if ( post_password_required( $post ) ) {
1513                         $result = current_user_can( $post_type->cap->edit_post, $post->ID );
1514                 } else {
1515                         $result = $posts_controller->check_read_permission( $post );
1516                 }
1517
1518                 if ( $has_password_filter ) {
1519                         remove_filter( 'post_password_required', '__return_false' );
1520                 }
1521
1522                 return $result;
1523         }
1524
1525         /**
1526          * Checks if the comment can be read.
1527          *
1528          * @since 4.7.0
1529          * @access protected
1530          *
1531          * @param WP_Comment      $comment Comment object.
1532          * @param WP_REST_Request $request Request data to check.
1533          * @return bool Whether the comment can be read.
1534          */
1535         protected function check_read_permission( $comment, $request ) {
1536                 if ( ! empty( $comment->comment_post_ID ) ) {
1537                         $post = get_post( $comment->comment_post_ID );
1538                         if ( $post ) {
1539                                 if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) {
1540                                         return true;
1541                                 }
1542                         }
1543                 }
1544
1545                 if ( 0 === get_current_user_id() ) {
1546                         return false;
1547                 }
1548
1549                 if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) {
1550                         return false;
1551                 }
1552
1553                 if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) {
1554                         return true;
1555                 }
1556
1557                 return current_user_can( 'edit_comment', $comment->comment_ID );
1558         }
1559
1560         /**
1561          * Checks if a comment can be edited or deleted.
1562          *
1563          * @since 4.7.0
1564          * @access protected
1565          *
1566          * @param object $comment Comment object.
1567          * @return bool Whether the comment can be edited or deleted.
1568          */
1569         protected function check_edit_permission( $comment ) {
1570                 if ( 0 === (int) get_current_user_id() ) {
1571                         return false;
1572                 }
1573
1574                 if ( ! current_user_can( 'moderate_comments' ) ) {
1575                         return false;
1576                 }
1577
1578                 return current_user_can( 'edit_comment', $comment->comment_ID );
1579         }
1580
1581         /**
1582          * Checks a comment author email for validity.
1583          *
1584          * Accepts either a valid email address or empty string as a valid comment
1585          * author email address. Setting the comment author email to an empty
1586          * string is allowed when a comment is being updated.
1587          *
1588          * @since 4.7.0
1589          *
1590          * @param string          $value   Author email value submitted.
1591          * @param WP_REST_Request $request Full details about the request.
1592          * @param string          $param   The parameter name.
1593          * @return WP_Error|string The sanitized email address, if valid,
1594          *                         otherwise an error.
1595          */
1596         public function check_comment_author_email( $value, $request, $param ) {
1597                 $email = (string) $value;
1598                 if ( empty( $email ) ) {
1599                         return $email;
1600                 }
1601
1602                 $check_email = rest_validate_request_arg( $email, $request, $param );
1603                 if ( is_wp_error( $check_email ) ) {
1604                         return $check_email;
1605                 }
1606
1607                 return $email;
1608         }
1609 }