| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
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 * @var WP_REST_Comment_Meta_Fields 24 */ 25 protected $meta; 26 27 /** 28 * Pre-fetched reaction summaries keyed by note comment ID. 29 * 30 * Populated by get_items() to avoid N+1 queries when listing notes 31 * with their reaction summaries. Reset after each get_items() call. 32 * 33 * @since 7.2.0 34 * @var array<int, array<string, array{count: int, current_user_reaction: int}>>|null 35 */ 36 protected $reaction_summaries = null; 37 38 /** 39 * Retrieves the hex keys of the emoji a note reaction accepts. 40 * 41 * Each key is the emoji's lowercase code points, padded to four digits, 42 * matching the client's `emojiToHexKey()`. A reaction stores its key in 43 * `comment_content`. 44 * 45 * @since 7.2.0 46 * 47 * @return string[] Hex keys for thumbs up, plus, heart, celebration, smile, eyes and rocket. 48 * 49 * @phpstan-return non-empty-list<lowercase-string&non-falsy-string> 50 */ 51 private static function get_note_reaction_keys(): array { 52 return array( '1f44d', '2795', '2764', '1f389', '1f604', '1f440', '1f680' ); 53 } 54 55 /** 56 * Constructor. 57 * 58 * @since 4.7.0 59 */ 60 public function __construct() { 61 $this->namespace = 'wp/v2'; 62 $this->rest_base = 'comments'; 63 64 $this->meta = new WP_REST_Comment_Meta_Fields(); 65 } 66 67 /** 68 * Registers the routes for comments. 69 * 70 * @since 4.7.0 71 * 72 * @see register_rest_route() 73 */ 74 public function register_routes() { 75 76 register_rest_route( 77 $this->namespace, 78 '/' . $this->rest_base, 79 array( 80 array( 81 'methods' => WP_REST_Server::READABLE, 82 'callback' => array( $this, 'get_items' ), 83 'permission_callback' => array( $this, 'get_items_permissions_check' ), 84 'args' => $this->get_collection_params(), 85 ), 86 array( 87 'methods' => WP_REST_Server::CREATABLE, 88 'callback' => array( $this, 'create_item' ), 89 'permission_callback' => array( $this, 'create_item_permissions_check' ), 90 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ), 91 ), 92 'schema' => array( $this, 'get_public_item_schema' ), 93 ) 94 ); 95 96 register_rest_route( 97 $this->namespace, 98 '/' . $this->rest_base . '/(?P<id>[\d]+)', 99 array( 100 'args' => array( 101 'id' => array( 102 'description' => __( 'Unique identifier for the comment.' ), 103 'type' => 'integer', 104 ), 105 ), 106 array( 107 'methods' => WP_REST_Server::READABLE, 108 'callback' => array( $this, 'get_item' ), 109 'permission_callback' => array( $this, 'get_item_permissions_check' ), 110 'args' => array( 111 'context' => $this->get_context_param( array( 'default' => 'view' ) ), 112 'password' => array( 113 'description' => __( 'The password for the parent post of the comment (if the post is password protected).' ), 114 'type' => 'string', 115 ), 116 ), 117 ), 118 array( 119 'methods' => WP_REST_Server::EDITABLE, 120 'callback' => array( $this, 'update_item' ), 121 'permission_callback' => array( $this, 'update_item_permissions_check' ), 122 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), 123 ), 124 array( 125 'methods' => WP_REST_Server::DELETABLE, 126 'callback' => array( $this, 'delete_item' ), 127 'permission_callback' => array( $this, 'delete_item_permissions_check' ), 128 'args' => array( 129 'force' => array( 130 'type' => 'boolean', 131 'default' => false, 132 'description' => __( 'Whether to bypass Trash and force deletion.' ), 133 ), 134 'password' => array( 135 'description' => __( 'The password for the parent post of the comment (if the post is password protected).' ), 136 'type' => 'string', 137 ), 138 ), 139 ), 140 'schema' => array( $this, 'get_public_item_schema' ), 141 ) 142 ); 143 } 144 145 /** 146 * Checks if a given request has access to read comments. 147 * 148 * @since 4.7.0 149 * 150 * @param WP_REST_Request $request Full details about the request. 151 * @return true|WP_Error True if the request has read access, error object otherwise. 152 */ 153 public function get_items_permissions_check( $request ) { 154 $is_note = in_array( $request['type'], array( 'note', 'reaction' ), true ); 155 $is_edit_context = 'edit' === $request['context']; 156 $protected_params = array( 'author', 'author_exclude', 'author_email', 'type', 'status' ); 157 $forbidden_params = array(); 158 159 if ( ! empty( $request['post'] ) ) { 160 foreach ( (array) $request['post'] as $post_id ) { 161 $post = get_post( $post_id ); 162 163 if ( ! empty( $post_id ) && $post && ! $this->check_read_post_permission( $post, $request ) ) { 164 return new WP_Error( 165 'rest_cannot_read_post', 166 __( 'Sorry, you are not allowed to read the post for this comment.' ), 167 array( 'status' => rest_authorization_required_code() ) 168 ); 169 } elseif ( 0 === $post_id && ! current_user_can( 'moderate_comments' ) ) { 170 return new WP_Error( 171 'rest_cannot_read', 172 __( 'Sorry, you are not allowed to read comments without a post.' ), 173 array( 'status' => rest_authorization_required_code() ) 174 ); 175 } 176 177 if ( $post && $is_note && ! $this->check_post_type_supports_notes( $post->post_type ) ) { 178 if ( current_user_can( 'edit_post', $post->ID ) ) { 179 return new WP_Error( 180 'rest_comment_not_supported_post_type', 181 __( 'Sorry, this post type does not support notes.' ), 182 array( 'status' => 403 ) 183 ); 184 } 185 186 foreach ( $protected_params as $param ) { 187 if ( 'status' === $param ) { 188 if ( array( 'approve' ) !== $request[ $param ] ) { 189 $forbidden_params[] = $param; 190 } 191 } elseif ( 'type' === $param ) { 192 if ( 'comment' !== $request[ $param ] ) { 193 $forbidden_params[] = $param; 194 } 195 } elseif ( ! empty( $request[ $param ] ) ) { 196 $forbidden_params[] = $param; 197 } 198 } 199 return new WP_Error( 200 'rest_forbidden_param', 201 /* translators: %s: List of forbidden parameters. */ 202 sprintf( __( 'Query parameter not permitted: %s' ), implode( ', ', $forbidden_params ) ), 203 array( 'status' => rest_authorization_required_code() ) 204 ); 205 } 206 } 207 } 208 209 // Re-map edit context capabilities when requesting `note` for a post. 210 if ( $is_edit_context && $is_note && ! empty( $request['post'] ) ) { 211 foreach ( (array) $request['post'] as $post_id ) { 212 if ( ! current_user_can( 'edit_post', $post_id ) ) { 213 return new WP_Error( 214 'rest_forbidden_context', 215 __( 'Sorry, you are not allowed to edit comments.' ), 216 array( 'status' => rest_authorization_required_code() ) 217 ); 218 } 219 } 220 } elseif ( $is_edit_context && ! current_user_can( 'moderate_comments' ) ) { 221 return new WP_Error( 222 'rest_forbidden_context', 223 __( 'Sorry, you are not allowed to edit comments.' ), 224 array( 'status' => rest_authorization_required_code() ) 225 ); 226 } 227 228 if ( ! current_user_can( 'edit_posts' ) ) { 229 foreach ( $protected_params as $param ) { 230 if ( 'status' === $param ) { 231 if ( array( 'approve' ) !== $request[ $param ] ) { 232 $forbidden_params[] = $param; 233 } 234 } elseif ( 'type' === $param ) { 235 if ( 'comment' !== $request[ $param ] ) { 236 $forbidden_params[] = $param; 237 } 238 } elseif ( ! empty( $request[ $param ] ) ) { 239 $forbidden_params[] = $param; 240 } 241 } 242 243 if ( ! empty( $forbidden_params ) ) { 244 return new WP_Error( 245 'rest_forbidden_param', 246 /* translators: %s: List of forbidden parameters. */ 247 sprintf( __( 'Query parameter not permitted: %s' ), implode( ', ', $forbidden_params ) ), 248 array( 'status' => rest_authorization_required_code() ) 249 ); 250 } 251 } 252 253 return true; 254 } 255 256 /** 257 * Retrieves a list of comment items. 258 * 259 * @since 4.7.0 260 * 261 * @param WP_REST_Request $request Full details about the request. 262 * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. 263 */ 264 public function get_items( $request ) { 265 266 // Retrieve the list of registered collection query parameters. 267 $registered = $this->get_collection_params(); 268 269 /* 270 * This array defines mappings between public API query parameters whose 271 * values are accepted as-passed, and their internal WP_Query parameter 272 * name equivalents (some are the same). Only values which are also 273 * present in $registered will be set. 274 */ 275 $parameter_mappings = array( 276 'author' => 'author__in', 277 'author_email' => 'author_email', 278 'author_exclude' => 'author__not_in', 279 'exclude' => 'comment__not_in', 280 'include' => 'comment__in', 281 'offset' => 'offset', 282 'order' => 'order', 283 'parent' => 'parent__in', 284 'parent_exclude' => 'parent__not_in', 285 'per_page' => 'number', 286 'post' => 'post__in', 287 'search' => 'search', 288 'status' => 'status', 289 'type' => 'type', 290 ); 291 292 $prepared_args = array(); 293 294 /* 295 * For each known parameter which is both registered and present in the request, 296 * set the parameter's value on the query $prepared_args. 297 */ 298 foreach ( $parameter_mappings as $api_param => $wp_param ) { 299 if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) { 300 $prepared_args[ $wp_param ] = $request[ $api_param ]; 301 } 302 } 303 304 // Ensure certain parameter values default to empty strings. 305 foreach ( array( 'author_email', 'search' ) as $param ) { 306 if ( ! isset( $prepared_args[ $param ] ) ) { 307 $prepared_args[ $param ] = ''; 308 } 309 } 310 311 if ( isset( $registered['orderby'] ) ) { 312 $prepared_args['orderby'] = $this->normalize_query_param( $request['orderby'] ); 313 } 314 315 $prepared_args['no_found_rows'] = false; 316 317 $prepared_args['update_comment_post_cache'] = true; 318 319 $prepared_args['date_query'] = array(); 320 321 // Set before into date query. Date query must be specified as an array of an array. 322 if ( isset( $registered['before'], $request['before'] ) ) { 323 $prepared_args['date_query'][0]['before'] = $request['before']; 324 } 325 326 // Set after into date query. Date query must be specified as an array of an array. 327 if ( isset( $registered['after'], $request['after'] ) ) { 328 $prepared_args['date_query'][0]['after'] = $request['after']; 329 } 330 331 if ( isset( $registered['page'] ) && empty( $request['offset'] ) ) { 332 $prepared_args['offset'] = $prepared_args['number'] * ( absint( $request['page'] ) - 1 ); 333 } 334 335 $is_head_request = $request->is_method( 'HEAD' ); 336 if ( $is_head_request ) { 337 // Force the 'fields' argument. For HEAD requests, only post IDs are required to calculate pagination. 338 $prepared_args['fields'] = 'ids'; 339 // Disable priming comment meta for HEAD requests to improve performance. 340 $prepared_args['update_comment_meta_cache'] = false; 341 } 342 343 /** 344 * Filters WP_Comment_Query arguments when querying comments via the REST API. 345 * 346 * @since 4.7.0 347 * 348 * @link https://developer.wordpress.org/reference/classes/wp_comment_query/ 349 * 350 * @param array $prepared_args Array of arguments for WP_Comment_Query. 351 * @param WP_REST_Request $request The REST API request. 352 */ 353 $prepared_args = apply_filters( 'rest_comment_query', $prepared_args, $request ); 354 355 $query = new WP_Comment_Query(); 356 $query_result = $query->query( $prepared_args ); 357 $comments = array(); 358 359 if ( ! $is_head_request ) { 360 /* 361 * When listing notes that include the reaction_summary field, 362 * pre-fetch all summaries in a single aggregated query to 363 * avoid an N+1 query in prepare_item_for_response(). 364 */ 365 $fields = $this->get_fields_for_response( $request ); 366 if ( 367 ! empty( $request['type'] ) && 368 'note' === $request['type'] && 369 rest_is_field_included( 'reaction_summary', $fields ) 370 ) { 371 $note_ids = array_map( 'intval', wp_list_pluck( $query_result, 'comment_ID' ) ); 372 if ( ! empty( $note_ids ) ) { 373 $this->prefetch_reaction_summaries( $note_ids ); 374 } 375 } 376 377 foreach ( $query_result as $comment ) { 378 if ( ! $this->check_read_permission( $comment, $request ) ) { 379 continue; 380 } 381 382 $data = $this->prepare_item_for_response( $comment, $request ); 383 $comments[] = $this->prepare_response_for_collection( $data ); 384 } 385 386 $this->reaction_summaries = null; 387 } 388 389 $total_comments = (int) $query->found_comments; 390 $max_pages = (int) $query->max_num_pages; 391 392 if ( $total_comments < 1 ) { 393 // Out-of-bounds, run the query without pagination/offset to get the total count. 394 unset( $prepared_args['number'], $prepared_args['offset'] ); 395 396 $query = new WP_Comment_Query(); 397 $prepared_args['count'] = true; 398 $prepared_args['orderby'] = 'none'; 399 $prepared_args['update_comment_meta_cache'] = false; 400 401 $total_comments = $query->query( $prepared_args ); 402 $max_pages = (int) ceil( $total_comments / $request['per_page'] ); 403 } 404 405 $response = $is_head_request ? new WP_REST_Response( array() ) : rest_ensure_response( $comments ); 406 $response->header( 'X-WP-Total', (string) $total_comments ); 407 $response->header( 'X-WP-TotalPages', (string) $max_pages ); 408 409 $base = add_query_arg( urlencode_deep( $request->get_query_params() ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); 410 411 if ( $request['page'] > 1 ) { 412 $prev_page = $request['page'] - 1; 413 414 if ( $prev_page > $max_pages ) { 415 $prev_page = $max_pages; 416 } 417 418 $prev_link = add_query_arg( 'page', $prev_page, $base ); 419 $response->link_header( 'prev', $prev_link ); 420 } 421 422 if ( $max_pages > $request['page'] ) { 423 $next_page = $request['page'] + 1; 424 $next_link = add_query_arg( 'page', $next_page, $base ); 425 426 $response->link_header( 'next', $next_link ); 427 } 428 429 return $response; 430 } 431 432 /** 433 * Get the comment, if the ID is valid. 434 * 435 * @since 4.7.2 436 * 437 * @param int $id Supplied ID. 438 * @return WP_Comment|WP_Error Comment object if ID is valid, WP_Error otherwise. 439 */ 440 protected function get_comment( $id ) { 441 $error = new WP_Error( 442 'rest_comment_invalid_id', 443 __( 'Invalid comment ID.' ), 444 array( 'status' => 404 ) 445 ); 446 447 if ( (int) $id <= 0 ) { 448 return $error; 449 } 450 451 $id = (int) $id; 452 $comment = get_comment( $id ); 453 if ( empty( $comment ) ) { 454 return $error; 455 } 456 457 if ( ! empty( $comment->comment_post_ID ) ) { 458 $post = get_post( (int) $comment->comment_post_ID ); 459 460 if ( empty( $post ) ) { 461 return new WP_Error( 462 'rest_post_invalid_id', 463 __( 'Invalid post ID.' ), 464 array( 'status' => 404 ) 465 ); 466 } 467 } 468 469 return $comment; 470 } 471 472 /** 473 * Checks if a given request has access to read the comment. 474 * 475 * @since 4.7.0 476 * 477 * @param WP_REST_Request $request Full details about the request. 478 * @return true|WP_Error True if the request has read access for the item, error object otherwise. 479 */ 480 public function get_item_permissions_check( $request ) { 481 $comment = $this->get_comment( $request['id'] ); 482 if ( is_wp_error( $comment ) ) { 483 return $comment; 484 } 485 486 // Re-map edit context capabilities when requesting `note` or `reaction` type. 487 $edit_cap = in_array( $comment->comment_type, array( 'note', 'reaction' ), true ) ? array( 'edit_comment', $comment->comment_ID ) : array( 'moderate_comments' ); 488 if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( ...$edit_cap ) ) { 489 return new WP_Error( 490 'rest_forbidden_context', 491 __( 'Sorry, you are not allowed to edit comments.' ), 492 array( 'status' => rest_authorization_required_code() ) 493 ); 494 } 495 496 $post = get_post( $comment->comment_post_ID ); 497 498 if ( ! $this->check_read_permission( $comment, $request ) ) { 499 return new WP_Error( 500 'rest_cannot_read', 501 __( 'Sorry, you are not allowed to read this comment.' ), 502 array( 'status' => rest_authorization_required_code() ) 503 ); 504 } 505 506 if ( $post && ! $this->check_read_post_permission( $post, $request ) ) { 507 return new WP_Error( 508 'rest_cannot_read_post', 509 __( 'Sorry, you are not allowed to read the post for this comment.' ), 510 array( 'status' => rest_authorization_required_code() ) 511 ); 512 } 513 514 return true; 515 } 516 517 /** 518 * Retrieves a comment. 519 * 520 * @since 4.7.0 521 * 522 * @param WP_REST_Request $request Full details about the request. 523 * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. 524 */ 525 public function get_item( $request ) { 526 $comment = $this->get_comment( $request['id'] ); 527 if ( is_wp_error( $comment ) ) { 528 return $comment; 529 } 530 531 $data = $this->prepare_item_for_response( $comment, $request ); 532 $response = rest_ensure_response( $data ); 533 534 return $response; 535 } 536 537 /** 538 * Checks if a given request has access to create a comment. 539 * 540 * @since 4.7.0 541 * 542 * @param WP_REST_Request $request Full details about the request. 543 * @return true|WP_Error True if the request has access to create items, error object otherwise. 544 */ 545 public function create_item_permissions_check( $request ) { 546 $is_note = ! empty( $request['type'] ) && in_array( $request['type'], array( 'note', 'reaction' ), true ); 547 548 if ( ! is_user_logged_in() && $is_note ) { 549 return new WP_Error( 550 'rest_comment_login_required', 551 __( 'Sorry, you must be logged in to comment.' ), 552 array( 'status' => 401 ) 553 ); 554 } 555 556 if ( ! is_user_logged_in() ) { 557 if ( get_option( 'comment_registration' ) ) { 558 return new WP_Error( 559 'rest_comment_login_required', 560 __( 'Sorry, you must be logged in to comment.' ), 561 array( 'status' => 401 ) 562 ); 563 } 564 565 /** 566 * Filters whether comments can be created via the REST API without authentication. 567 * 568 * Enables creating comments for anonymous users. 569 * 570 * @since 4.7.0 571 * 572 * @param bool $allow_anonymous Whether to allow anonymous comments to 573 * be created. Default `false`. 574 * @param WP_REST_Request $request Request used to generate the 575 * response. 576 */ 577 $allow_anonymous = apply_filters( 'rest_allow_anonymous_comments', false, $request ); 578 579 if ( ! $allow_anonymous ) { 580 return new WP_Error( 581 'rest_comment_login_required', 582 __( 'Sorry, you must be logged in to comment.' ), 583 array( 'status' => 401 ) 584 ); 585 } 586 } 587 588 // Limit who can set comment `author`, `author_ip` or `status` to anything other than the default. 589 if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! $this->check_assign_author_permission( $request['author'] ) ) { 590 return new WP_Error( 591 'rest_comment_invalid_author', 592 /* translators: %s: Request parameter. */ 593 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ), 594 array( 'status' => rest_authorization_required_code() ) 595 ); 596 } 597 598 /* 599 * A reaction is always first-person. create_item() enforces one emoji per 600 * user per note against the current user, and update_item() refuses to 601 * reattribute one, so a reaction stored against somebody else would be a 602 * row the uniqueness check and the reaction summary can never see. 603 */ 604 if ( 605 ! empty( $request['type'] ) && 'reaction' === $request['type'] && 606 isset( $request['author'] ) && get_current_user_id() !== (int) $request['author'] 607 ) { 608 return new WP_Error( 609 'rest_comment_invalid_author', 610 __( 'Sorry, you are not allowed to add a reaction on behalf of another user.' ), 611 array( 'status' => rest_authorization_required_code() ) 612 ); 613 } 614 615 if ( isset( $request['author_ip'] ) && ! current_user_can( 'moderate_comments' ) ) { 616 if ( empty( $_SERVER['REMOTE_ADDR'] ) || $request['author_ip'] !== $_SERVER['REMOTE_ADDR'] ) { 617 return new WP_Error( 618 'rest_comment_invalid_author_ip', 619 /* translators: %s: Request parameter. */ 620 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author_ip' ), 621 array( 'status' => rest_authorization_required_code() ) 622 ); 623 } 624 } 625 626 if ( $is_note && ! empty( $request['post'] ) ) { 627 $target_check = $this->check_target_post_permission( (int) $request['post'], $request, true ); 628 629 if ( is_wp_error( $target_check ) ) { 630 return $target_check; 631 } 632 } 633 634 if ( empty( $request['post'] ) ) { 635 return new WP_Error( 636 'rest_comment_invalid_post_id', 637 __( 'Sorry, you are not allowed to create this comment without a post.' ), 638 array( 'status' => 403 ) 639 ); 640 } 641 642 $edit_cap = $is_note ? array( 'edit_post', (int) $request['post'] ) : array( 'moderate_comments' ); 643 if ( isset( $request['status'] ) && ! current_user_can( ...$edit_cap ) ) { 644 return new WP_Error( 645 'rest_comment_invalid_status', 646 /* translators: %s: Request parameter. */ 647 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'status' ), 648 array( 'status' => rest_authorization_required_code() ) 649 ); 650 } 651 652 /* 653 * A note's target post was fully checked by check_target_post_permission() 654 * above. Everything below applies to other comments only: a note is allowed 655 * on a draft and on a post whose discussion is closed, and the rest would 656 * repeat what that check already did. 657 */ 658 if ( $is_note ) { 659 return true; 660 } 661 662 $post = get_post( (int) $request['post'] ); 663 664 if ( ! $post ) { 665 return new WP_Error( 666 'rest_comment_invalid_post_id', 667 __( 'Sorry, you are not allowed to create this comment without a post.' ), 668 array( 'status' => 403 ) 669 ); 670 } 671 672 if ( 'draft' === $post->post_status ) { 673 return new WP_Error( 674 'rest_comment_draft_post', 675 __( 'Sorry, you are not allowed to create a comment on this post.' ), 676 array( 'status' => 403 ) 677 ); 678 } 679 680 if ( 'trash' === $post->post_status ) { 681 return new WP_Error( 682 'rest_comment_trash_post', 683 __( 'Sorry, you are not allowed to create a comment on this post.' ), 684 array( 'status' => 403 ) 685 ); 686 } 687 688 if ( ! $this->check_read_post_permission( $post, $request ) ) { 689 return new WP_Error( 690 'rest_cannot_read_post', 691 __( 'Sorry, you are not allowed to read the post for this comment.' ), 692 array( 'status' => rest_authorization_required_code() ) 693 ); 694 } 695 696 if ( ! comments_open( $post->ID ) ) { 697 return new WP_Error( 698 'rest_comment_closed', 699 __( 'Sorry, comments are closed for this item.' ), 700 array( 'status' => 403 ) 701 ); 702 } 703 704 return true; 705 } 706 707 /** 708 * Creates a comment. 709 * 710 * @since 4.7.0 711 * @since 7.2.0 Added support for the `reaction` comment type. 712 * 713 * @param WP_REST_Request $request Full details about the request. 714 * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. 715 */ 716 public function create_item( $request ) { 717 if ( ! empty( $request['id'] ) ) { 718 return new WP_Error( 719 'rest_comment_exists', 720 __( 'Cannot create existing comment.' ), 721 array( 'status' => 400 ) 722 ); 723 } 724 725 // Do not allow comments to be created with a non-core type. 726 if ( ! empty( $request['type'] ) && ! in_array( $request['type'], array( 'comment', 'note', 'reaction' ), true ) ) { 727 return new WP_Error( 728 'rest_invalid_comment_type', 729 __( 'Cannot create a comment with that type.' ), 730 array( 'status' => 400 ) 731 ); 732 } 733 734 /* 735 * The canonical reaction key, populated once validated below so the 736 * stored content matches what was validated (not the raw input). 737 */ 738 $reaction_key = null; 739 740 // Validate reaction-specific constraints. 741 if ( ! empty( $request['type'] ) && 'reaction' === $request['type'] ) { 742 // Reaction parent must be specified. 743 if ( empty( $request['parent'] ) ) { 744 return new WP_Error( 745 'rest_comment_invalid_parent', 746 __( 'A reaction must have a parent note.' ), 747 array( 'status' => 400 ) 748 ); 749 } 750 751 // Reaction parent must exist and be a note. 752 $parent_comment = get_comment( $request['parent'] ); 753 if ( ! $parent_comment || 'note' !== $parent_comment->comment_type ) { 754 return new WP_Error( 755 'rest_comment_invalid_parent', 756 __( 'A reaction must be attached to a note.' ), 757 array( 'status' => 400 ) 758 ); 759 } 760 761 /* 762 * The parent note must belong to the post the reaction targets. 763 * create_item_permissions_check() requires `post` and checks that the 764 * user can edit it, so this runs before the parent's status checks: 765 * a note on another post gets the same error whatever its status, 766 * rather than revealing whether it is trashed, spammed or resolved. 767 */ 768 if ( ! empty( $request['post'] ) && (int) $parent_comment->comment_post_ID !== (int) $request['post'] ) { 769 return new WP_Error( 770 'rest_comment_invalid_parent', 771 __( 'A reaction must be attached to a note on the same post.' ), 772 array( 'status' => 400 ) 773 ); 774 } 775 776 // A reaction under a trashed or spammed note would escape the trash cascade. 777 if ( in_array( $parent_comment->comment_approved, array( 'trash', 'spam' ), true ) ) { 778 return new WP_Error( 779 'rest_comment_invalid_parent', 780 __( 'A reaction cannot be added to a trashed or spam note.' ), 781 array( 'status' => 400 ) 782 ); 783 } 784 785 /* 786 * Resolving a thread approves its root note, and the editor disables 787 * reactions from then on. Hold requests from stale editor sessions 788 * to that too, for the root note and for every reply in its thread. 789 */ 790 if ( $this->is_thread_resolved( $parent_comment ) ) { 791 return new WP_Error( 792 'rest_comment_invalid_parent', 793 __( 'A reaction cannot be added to a resolved note.' ), 794 array( 'status' => 400 ) 795 ); 796 } 797 798 /* 799 * Validate the reaction content: the hex key of one of the curated 800 * reaction emoji, as listed by self::get_note_reaction_keys() (e.g. 801 * `2764` for the heart). Raw emoji bytes are rejected because the 802 * comments table is not guaranteed to be utf8mb4 across all WordPress 803 * installs; clients are expected to normalize before submitting. 804 * 805 * Read the content the same two ways prepare_item_for_database() 806 * does, so `content` and `content.raw` are both accepted. 807 */ 808 $raw_content = ''; 809 if ( isset( $request['content'] ) && is_string( $request['content'] ) ) { 810 $raw_content = $request['content']; 811 } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) { 812 $raw_content = $request['content']['raw']; 813 } 814 815 $emoji_key = trim( wp_strip_all_tags( $raw_content ) ); 816 817 if ( ! in_array( $emoji_key, self::get_note_reaction_keys(), true ) ) { 818 return new WP_Error( 819 'rest_comment_invalid_reaction', 820 __( 'Invalid reaction emoji.' ), 821 array( 'status' => 400 ) 822 ); 823 } 824 825 /* 826 * A reaction is always approved. The uniqueness check, the race 827 * cleanup below and the reaction summary only see approved rows, so 828 * a reaction created in any other status could never be counted, 829 * deduplicated or, since reactions cannot be updated, fixed. 830 */ 831 if ( isset( $request['status'] ) && ! in_array( $request['status'], array( 'approve', 'approved', '1' ), true ) ) { 832 return new WP_Error( 833 'rest_comment_invalid_status', 834 __( 'A reaction cannot be created with that status.' ), 835 array( 'status' => 400 ) 836 ); 837 } 838 839 /* 840 * Enforce uniqueness: one emoji per user per note. 841 * 842 * Scope to active (approved) reactions only — trashed reactions 843 * are invisible to the user and must not block re-adding the 844 * same emoji. 845 */ 846 $existing = get_comments( 847 array( 848 'parent' => $request['parent'], 849 'user_id' => get_current_user_id(), 850 'type' => 'reaction', 851 'status' => 'approve', 852 ) 853 ); 854 855 foreach ( $existing as $existing_reaction ) { 856 if ( wp_strip_all_tags( $existing_reaction->comment_content ) === $emoji_key ) { 857 return new WP_Error( 858 'rest_comment_duplicate_reaction', 859 __( 'You have already reacted with this emoji.' ), 860 array( 'status' => 409 ) 861 ); 862 } 863 } 864 865 $reaction_key = $emoji_key; 866 } 867 868 $prepared_comment = $this->prepare_item_for_database( $request ); 869 if ( is_wp_error( $prepared_comment ) ) { 870 return $prepared_comment; 871 } 872 873 $prepared_comment['comment_type'] = $request['type']; 874 875 /* 876 * Persist the validated, canonical reaction key rather than the raw 877 * request content, so stored values stay consistent for grouping and 878 * counting (e.g. "<b>2764</b>" is stored as "2764"). 879 */ 880 if ( null !== $reaction_key ) { 881 $prepared_comment['comment_content'] = $reaction_key; 882 } 883 884 if ( ! isset( $prepared_comment['comment_content'] ) ) { 885 $prepared_comment['comment_content'] = ''; 886 } 887 888 // Include note metadata into check_is_comment_content_allowed. 889 if ( isset( $request['meta']['_wp_note_status'] ) ) { 890 $prepared_comment['meta']['_wp_note_status'] = $request['meta']['_wp_note_status']; 891 } 892 893 if ( ! $this->check_is_comment_content_allowed( $prepared_comment ) ) { 894 return new WP_Error( 895 'rest_comment_content_invalid', 896 __( 'Invalid comment content.' ), 897 array( 'status' => 400 ) 898 ); 899 } 900 901 // Setting remaining values before wp_insert_comment so we can use wp_allow_comment(). 902 if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) { 903 $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true ); 904 } 905 906 // Set author data if the user's logged in. 907 $missing_author = empty( $prepared_comment['user_id'] ) 908 && empty( $prepared_comment['comment_author'] ) 909 && empty( $prepared_comment['comment_author_email'] ) 910 && empty( $prepared_comment['comment_author_url'] ); 911 912 if ( is_user_logged_in() && $missing_author ) { 913 $user = wp_get_current_user(); 914 915 $prepared_comment['user_id'] = $user->ID; 916 $prepared_comment['comment_author'] = $user->display_name; 917 $prepared_comment['comment_author_email'] = $user->user_email; 918 $prepared_comment['comment_author_url'] = $user->user_url; 919 } 920 921 /* 922 * Pin a reaction to the current user, whatever author details the request 923 * carried. Author fields alone leave `user_id` at 0, which the uniqueness 924 * check and the reaction summary both key on. 925 */ 926 if ( null !== $reaction_key ) { 927 $user = wp_get_current_user(); 928 929 $prepared_comment['user_id'] = $user->ID; 930 $prepared_comment['comment_author'] = $user->display_name; 931 $prepared_comment['comment_author_email'] = $user->user_email; 932 $prepared_comment['comment_author_url'] = $user->user_url; 933 } 934 935 // Honor the discussion setting that requires a name and email address of the comment author. 936 if ( get_option( 'require_name_email' ) ) { 937 if ( empty( $prepared_comment['comment_author'] ) || empty( $prepared_comment['comment_author_email'] ) ) { 938 return new WP_Error( 939 'rest_comment_author_data_required', 940 __( 'Creating a comment requires valid author name and email values.' ), 941 array( 'status' => 400 ) 942 ); 943 } 944 } 945 946 if ( ! isset( $prepared_comment['comment_author_email'] ) ) { 947 $prepared_comment['comment_author_email'] = ''; 948 } 949 950 if ( ! isset( $prepared_comment['comment_author_url'] ) ) { 951 $prepared_comment['comment_author_url'] = ''; 952 } 953 954 if ( ! isset( $prepared_comment['comment_agent'] ) ) { 955 $prepared_comment['comment_agent'] = ''; 956 } 957 958 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_comment ); 959 960 if ( is_wp_error( $check_comment_lengths ) ) { 961 $error_code = $check_comment_lengths->get_error_code(); 962 return new WP_Error( 963 $error_code, 964 __( 'Comment field exceeds maximum length allowed.' ), 965 array( 'status' => 400 ) 966 ); 967 } 968 969 // Don't check for duplicates or flooding for notes or reactions. 970 $prepared_comment['comment_approved'] = 971 in_array( $prepared_comment['comment_type'], array( 'note', 'reaction' ), true ) ? 972 '1' : 973 wp_allow_comment( $prepared_comment, true ); 974 975 if ( is_wp_error( $prepared_comment['comment_approved'] ) ) { 976 $error_code = $prepared_comment['comment_approved']->get_error_code(); 977 $error_message = $prepared_comment['comment_approved']->get_error_message(); 978 979 if ( 'comment_duplicate' === $error_code ) { 980 return new WP_Error( 981 $error_code, 982 $error_message, 983 array( 'status' => 409 ) 984 ); 985 } 986 987 if ( 'comment_flood' === $error_code ) { 988 return new WP_Error( 989 $error_code, 990 $error_message, 991 array( 'status' => 400 ) 992 ); 993 } 994 995 return $prepared_comment['comment_approved']; 996 } 997 998 /** 999 * Filters a comment before it is inserted via the REST API. 1000 * 1001 * Allows modification of the comment right before it is inserted via wp_insert_comment(). 1002 * Returning a WP_Error value from the filter will short-circuit insertion and allow 1003 * skipping further processing. 1004 * 1005 * @since 4.7.0 1006 * @since 4.8.0 `$prepared_comment` can now be a WP_Error to short-circuit insertion. 1007 * 1008 * @param array|WP_Error $prepared_comment The prepared comment data for wp_insert_comment(). 1009 * @param WP_REST_Request $request Request used to insert the comment. 1010 */ 1011 $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request ); 1012 if ( is_wp_error( $prepared_comment ) ) { 1013 return $prepared_comment; 1014 } 1015 1016 $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) ); 1017 1018 if ( ! $comment_id ) { 1019 return new WP_Error( 1020 'rest_comment_failed_create', 1021 __( 'Creating comment failed.' ), 1022 array( 'status' => 500 ) 1023 ); 1024 } 1025 1026 /* 1027 * The pre-insert uniqueness check is not atomic, so two concurrent 1028 * requests for the same user/note/emoji can both insert an approved 1029 * row. Converge on a single row deterministically: keep the earliest 1030 * matching reaction (lowest comment ID) and delete any later 1031 * duplicates. Every concurrent request applies the same rule, so they 1032 * all settle on the same surviving row. If this request's own row lost 1033 * the race, repoint the response to the survivor. 1034 */ 1035 if ( null !== $reaction_key ) { 1036 $matching = get_comments( 1037 array( 1038 'parent' => $request['parent'], 1039 'user_id' => get_current_user_id(), 1040 'type' => 'reaction', 1041 'status' => 'approve', 1042 'orderby' => 'comment_ID', 1043 'order' => 'ASC', 1044 ) 1045 ); 1046 $duplicates = array(); 1047 foreach ( $matching as $candidate ) { 1048 if ( wp_strip_all_tags( $candidate->comment_content ) === $reaction_key ) { 1049 $duplicates[] = (int) $candidate->comment_ID; 1050 } 1051 } 1052 1053 /* 1054 * Repoint whenever any matching row survives, not only when this 1055 * request still sees its own duplicate: a competing request may 1056 * already have deleted this request's row, leaving a single 1057 * survivor that is not `$comment_id`. 1058 */ 1059 if ( ! empty( $duplicates ) ) { 1060 $survivor_id = array_shift( $duplicates ); 1061 foreach ( $duplicates as $duplicate_id ) { 1062 wp_delete_comment( $duplicate_id, true ); 1063 } 1064 $comment_id = $survivor_id; 1065 } 1066 } 1067 1068 /* 1069 * Reactions are inserted approved and their status was validated above. 1070 * Skipping them here also keeps a request from changing the status of a 1071 * row that the race cleanup above may have handed it from another request. 1072 */ 1073 if ( isset( $request['status'] ) && null === $reaction_key ) { 1074 $this->handle_status_param( $request['status'], $comment_id ); 1075 } 1076 1077 $comment = get_comment( $comment_id ); 1078 1079 /** 1080 * Fires after a comment is created or updated via the REST API. 1081 * 1082 * @since 4.7.0 1083 * 1084 * @param WP_Comment $comment Inserted or updated comment object. 1085 * @param WP_REST_Request $request Request object. 1086 * @param bool $creating True when creating a comment, false 1087 * when updating. 1088 */ 1089 do_action( 'rest_insert_comment', $comment, $request, true ); 1090 1091 $schema = $this->get_item_schema(); 1092 1093 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { 1094 $meta_update = $this->meta->update_value( $request['meta'], $comment_id ); 1095 1096 if ( is_wp_error( $meta_update ) ) { 1097 return $meta_update; 1098 } 1099 } 1100 1101 $fields_update = $this->update_additional_fields_for_object( $comment, $request ); 1102 1103 if ( is_wp_error( $fields_update ) ) { 1104 return $fields_update; 1105 } 1106 1107 $context = current_user_can( 'moderate_comments' ) ? 'edit' : 'view'; 1108 $request->set_param( 'context', $context ); 1109 1110 /** 1111 * Fires completely after a comment is created or updated via the REST API. 1112 * 1113 * @since 5.0.0 1114 * 1115 * @param WP_Comment $comment Inserted or updated comment object. 1116 * @param WP_REST_Request $request Request object. 1117 * @param bool $creating True when creating a comment, false 1118 * when updating. 1119 */ 1120 do_action( 'rest_after_insert_comment', $comment, $request, true ); 1121 1122 $response = $this->prepare_item_for_response( $comment, $request ); 1123 $response = rest_ensure_response( $response ); 1124 1125 $response->set_status( 201 ); 1126 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment_id ) ) ); 1127 1128 return $response; 1129 } 1130 1131 /** 1132 * Checks if a given REST request has access to update a comment. 1133 * 1134 * @since 4.7.0 1135 * @since 7.1.1 Target post permissions are checked when a comment's parent post is changed. 1136 * @since 7.2.0 Reactions cannot be updated. 1137 * 1138 * @param WP_REST_Request $request Full details about the request. 1139 * @return true|WP_Error True if the request has access to update the item, error object otherwise. 1140 */ 1141 public function update_item_permissions_check( $request ) { 1142 $comment = $this->get_comment( $request['id'] ); 1143 if ( is_wp_error( $comment ) ) { 1144 return $comment; 1145 } 1146 1147 /* 1148 * Reactions are immutable. create_item() validates the author, parent 1149 * note, target post and canonical emoji hex key as a set, and none of that 1150 * is re-checked here. Allowing an update would let anyone who can edit 1151 * the note's post reattribute a reaction to another user, move it to a 1152 * note on a post they cannot edit, or store a duplicate or invalid 1153 * key. Removing a reaction is a delete. 1154 */ 1155 if ( 'reaction' === $comment->comment_type ) { 1156 return new WP_Error( 1157 'rest_comment_update_not_allowed', 1158 __( 'Reactions cannot be edited. Remove the reaction and add a new one instead.' ), 1159 array( 'status' => 403 ) 1160 ); 1161 } 1162 1163 if ( ! $this->check_edit_permission( $comment ) ) { 1164 return new WP_Error( 1165 'rest_cannot_edit', 1166 __( 'Sorry, you are not allowed to edit this comment.' ), 1167 array( 'status' => rest_authorization_required_code() ) 1168 ); 1169 } 1170 1171 /* 1172 * Reassigning a comment copies the new author's email address onto it, 1173 * which is then returned in the response. 1174 */ 1175 if ( 1176 isset( $request['author'] ) && 1177 (int) $request['author'] !== (int) $comment->user_id && 1178 get_current_user_id() !== (int) $request['author'] && 1179 ! $this->check_assign_author_permission( $request['author'] ) 1180 ) { 1181 return new WP_Error( 1182 'rest_comment_invalid_author', 1183 /* translators: %s: Request parameter. */ 1184 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ), 1185 array( 'status' => rest_authorization_required_code() ) 1186 ); 1187 } 1188 1189 /* 1190 * check_edit_permission() above only establishes that the comment may be 1191 * edited where it currently sits, because 'edit_comment' maps to 'edit_post' 1192 * on the comment's current parent. When the parent is being changed, the new 1193 * parent has to be authorized as well. Without this, a user holding 1194 * edit_comment on their own comment or note could reparent it onto any post, 1195 * including posts they can neither read nor edit. 1196 */ 1197 if ( isset( $request['post'] ) && (int) $request['post'] !== (int) $comment->comment_post_ID ) { 1198 $target_check = $this->check_target_post_permission( 1199 (int) $request['post'], 1200 $request, 1201 'note' === $comment->comment_type 1202 ); 1203 1204 if ( is_wp_error( $target_check ) ) { 1205 return $target_check; 1206 } 1207 } 1208 1209 return true; 1210 } 1211 1212 /** 1213 * Updates a comment. 1214 * 1215 * @since 4.7.0 1216 * 1217 * @param WP_REST_Request $request Full details about the request. 1218 * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. 1219 */ 1220 public function update_item( $request ) { 1221 $comment = $this->get_comment( $request['id'] ); 1222 if ( is_wp_error( $comment ) ) { 1223 return $comment; 1224 } 1225 1226 $id = $comment->comment_ID; 1227 1228 if ( isset( $request['type'] ) && get_comment_type( $id ) !== $request['type'] ) { 1229 return new WP_Error( 1230 'rest_comment_invalid_type', 1231 __( 'Sorry, you are not allowed to change the comment type.' ), 1232 array( 'status' => 404 ) 1233 ); 1234 } 1235 1236 /* 1237 * Re-sending the current author is a no-op. Otherwise the author's details 1238 * would be refreshed from their user account, exposing any change to their 1239 * email address to whoever can edit the comment. 1240 */ 1241 if ( isset( $request['author'] ) && (int) $request['author'] === (int) $comment->user_id ) { 1242 unset( $request['author'] ); 1243 } 1244 1245 $prepared_args = $this->prepare_item_for_database( $request ); 1246 1247 if ( is_wp_error( $prepared_args ) ) { 1248 return $prepared_args; 1249 } 1250 1251 if ( ! empty( $prepared_args['comment_post_ID'] ) ) { 1252 $post = get_post( $prepared_args['comment_post_ID'] ); 1253 1254 if ( empty( $post ) ) { 1255 return new WP_Error( 1256 'rest_comment_invalid_post_id', 1257 __( 'Invalid post ID.' ), 1258 array( 'status' => 403 ) 1259 ); 1260 } 1261 } 1262 1263 if ( empty( $prepared_args ) && isset( $request['status'] ) ) { 1264 // Only the comment status is being changed. 1265 $change = $this->handle_status_param( $request['status'], $id ); 1266 1267 if ( ! $change ) { 1268 return new WP_Error( 1269 'rest_comment_failed_edit', 1270 __( 'Updating comment status failed.' ), 1271 array( 'status' => 500 ) 1272 ); 1273 } 1274 } elseif ( ! empty( $prepared_args ) ) { 1275 if ( is_wp_error( $prepared_args ) ) { 1276 return $prepared_args; 1277 } 1278 if ( ! $this->check_is_comment_content_allowed( $prepared_args ) ) { 1279 return new WP_Error( 1280 'rest_comment_content_invalid', 1281 __( 'Invalid comment content.' ), 1282 array( 'status' => 400 ) 1283 ); 1284 } 1285 1286 $prepared_args['comment_ID'] = $id; 1287 1288 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args ); 1289 1290 if ( is_wp_error( $check_comment_lengths ) ) { 1291 $error_code = $check_comment_lengths->get_error_code(); 1292 return new WP_Error( 1293 $error_code, 1294 __( 'Comment field exceeds maximum length allowed.' ), 1295 array( 'status' => 400 ) 1296 ); 1297 } 1298 1299 $updated = wp_update_comment( wp_slash( (array) $prepared_args ), true ); 1300 1301 if ( is_wp_error( $updated ) ) { 1302 return new WP_Error( 1303 'rest_comment_failed_edit', 1304 __( 'Updating comment failed.' ), 1305 array( 'status' => 500 ) 1306 ); 1307 } 1308 1309 if ( isset( $request['status'] ) ) { 1310 $this->handle_status_param( $request['status'], $id ); 1311 } 1312 } 1313 1314 $comment = get_comment( $id ); 1315 1316 /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */ 1317 do_action( 'rest_insert_comment', $comment, $request, false ); 1318 1319 $schema = $this->get_item_schema(); 1320 1321 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { 1322 $meta_update = $this->meta->update_value( $request['meta'], $id ); 1323 1324 if ( is_wp_error( $meta_update ) ) { 1325 return $meta_update; 1326 } 1327 } 1328 1329 $fields_update = $this->update_additional_fields_for_object( $comment, $request ); 1330 1331 if ( is_wp_error( $fields_update ) ) { 1332 return $fields_update; 1333 } 1334 1335 $request->set_param( 'context', 'edit' ); 1336 1337 /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */ 1338 do_action( 'rest_after_insert_comment', $comment, $request, false ); 1339 1340 $response = $this->prepare_item_for_response( $comment, $request ); 1341 1342 return rest_ensure_response( $response ); 1343 } 1344 1345 /** 1346 * Checks if a given request has access to delete a comment. 1347 * 1348 * @since 4.7.0 1349 * 1350 * @param WP_REST_Request $request Full details about the request. 1351 * @return true|WP_Error True if the request has access to delete the item, error object otherwise. 1352 */ 1353 public function delete_item_permissions_check( $request ) { 1354 $comment = $this->get_comment( $request['id'] ); 1355 if ( is_wp_error( $comment ) ) { 1356 return $comment; 1357 } 1358 1359 if ( ! $this->check_edit_permission( $comment ) ) { 1360 return new WP_Error( 1361 'rest_cannot_delete', 1362 __( 'Sorry, you are not allowed to delete this comment.' ), 1363 array( 'status' => rest_authorization_required_code() ) 1364 ); 1365 } 1366 1367 if ( 'reaction' === strtolower( $comment->comment_type ) ) { 1368 // A reaction speaks for its author, so only they can remove it. 1369 if ( get_current_user_id() !== (int) $comment->user_id ) { 1370 return new WP_Error( 1371 'rest_cannot_delete', 1372 __( 'Sorry, you can only remove your own reactions.' ), 1373 array( 'status' => rest_authorization_required_code() ) 1374 ); 1375 } 1376 1377 // Reactions on a resolved thread are frozen, like adding new ones. 1378 $note = get_comment( $comment->comment_parent ); 1379 if ( $note instanceof WP_Comment && $this->is_thread_resolved( $note ) ) { 1380 return new WP_Error( 1381 'rest_cannot_delete', 1382 __( 'A reaction cannot be removed from a resolved note.' ), 1383 array( 'status' => 403 ) 1384 ); 1385 } 1386 } 1387 1388 return true; 1389 } 1390 1391 /** 1392 * Deletes a comment. 1393 * 1394 * @since 4.7.0 1395 * 1396 * @param WP_REST_Request $request Full details about the request. 1397 * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. 1398 */ 1399 public function delete_item( $request ) { 1400 $comment = $this->get_comment( $request['id'] ); 1401 if ( is_wp_error( $comment ) ) { 1402 return $comment; 1403 } 1404 1405 $force = isset( $request['force'] ) ? (bool) $request['force'] : false; 1406 1407 /** 1408 * Filters whether a comment can be trashed via the REST API. 1409 * 1410 * Return false to disable trash support for the comment. 1411 * 1412 * @since 4.7.0 1413 * 1414 * @param bool $supports_trash Whether the comment supports trashing. 1415 * @param WP_Comment $comment The comment object being considered for trashing support. 1416 */ 1417 $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment ); 1418 1419 $request->set_param( 'context', 'edit' ); 1420 1421 if ( $force ) { 1422 $previous = $this->prepare_item_for_response( $comment, $request ); 1423 $result = wp_delete_comment( $comment->comment_ID, true ); 1424 $response = new WP_REST_Response(); 1425 $response->set_data( 1426 array( 1427 'deleted' => true, 1428 'previous' => $previous->get_data(), 1429 ) 1430 ); 1431 } else { 1432 // If this type doesn't support trashing, error out. 1433 if ( ! $supports_trash ) { 1434 return new WP_Error( 1435 'rest_trash_not_supported', 1436 /* translators: %s: force=true */ 1437 sprintf( __( "The comment does not support trashing. Set '%s' to delete." ), 'force=true' ), 1438 array( 'status' => 501 ) 1439 ); 1440 } 1441 1442 if ( 'trash' === $comment->comment_approved ) { 1443 return new WP_Error( 1444 'rest_already_trashed', 1445 __( 'The comment has already been trashed.' ), 1446 array( 'status' => 410 ) 1447 ); 1448 } 1449 1450 $result = wp_trash_comment( $comment->comment_ID ); 1451 $comment = get_comment( $comment->comment_ID ); 1452 $response = $this->prepare_item_for_response( $comment, $request ); 1453 } 1454 1455 if ( ! $result ) { 1456 return new WP_Error( 1457 'rest_cannot_delete', 1458 __( 'The comment cannot be deleted.' ), 1459 array( 'status' => 500 ) 1460 ); 1461 } 1462 1463 /** 1464 * Fires after a comment is deleted via the REST API. 1465 * 1466 * @since 4.7.0 1467 * 1468 * @param WP_Comment $comment The deleted comment data. 1469 * @param WP_REST_Response $response The response returned from the API. 1470 * @param WP_REST_Request $request The request sent to the API. 1471 */ 1472 do_action( 'rest_delete_comment', $comment, $response, $request ); 1473 1474 return $response; 1475 } 1476 1477 /** 1478 * Prepares a single comment output for response. 1479 * 1480 * @since 4.7.0 1481 * @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support. 1482 * 1483 * @param WP_Comment $item Comment object. 1484 * @param WP_REST_Request $request Request object. 1485 * @return WP_REST_Response Response object. 1486 */ 1487 public function prepare_item_for_response( $item, $request ) { 1488 // Restores the more descriptive, specific name for use within this method. 1489 $comment = $item; 1490 1491 // Don't prepare the response body for HEAD requests. 1492 if ( $request->is_method( 'HEAD' ) ) { 1493 /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */ 1494 return apply_filters( 'rest_prepare_comment', new WP_REST_Response( array() ), $comment, $request ); 1495 } 1496 1497 $fields = $this->get_fields_for_response( $request ); 1498 $data = array(); 1499 1500 if ( in_array( 'id', $fields, true ) ) { 1501 $data['id'] = (int) $comment->comment_ID; 1502 } 1503 1504 if ( in_array( 'post', $fields, true ) ) { 1505 $data['post'] = (int) $comment->comment_post_ID; 1506 } 1507 1508 if ( in_array( 'parent', $fields, true ) ) { 1509 $data['parent'] = (int) $comment->comment_parent; 1510 } 1511 1512 if ( in_array( 'author', $fields, true ) ) { 1513 $data['author'] = (int) $comment->user_id; 1514 } 1515 1516 if ( in_array( 'author_name', $fields, true ) ) { 1517 $data['author_name'] = $comment->comment_author; 1518 } 1519 1520 if ( in_array( 'author_email', $fields, true ) ) { 1521 $data['author_email'] = $comment->comment_author_email; 1522 } 1523 1524 if ( in_array( 'author_url', $fields, true ) ) { 1525 $data['author_url'] = $comment->comment_author_url; 1526 } 1527 1528 if ( in_array( 'author_ip', $fields, true ) ) { 1529 $data['author_ip'] = $comment->comment_author_IP; 1530 } 1531 1532 if ( in_array( 'author_user_agent', $fields, true ) ) { 1533 $data['author_user_agent'] = $comment->comment_agent; 1534 } 1535 1536 if ( in_array( 'date', $fields, true ) ) { 1537 $data['date'] = mysql_to_rfc3339( $comment->comment_date ); 1538 } 1539 1540 if ( in_array( 'date_gmt', $fields, true ) ) { 1541 $data['date_gmt'] = mysql_to_rfc3339( $comment->comment_date_gmt ); 1542 } 1543 1544 if ( in_array( 'content', $fields, true ) ) { 1545 $data['content'] = array( 1546 /** This filter is documented in wp-includes/comment-template.php */ 1547 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment, array() ), 1548 'raw' => $comment->comment_content, 1549 ); 1550 } 1551 1552 if ( in_array( 'link', $fields, true ) ) { 1553 $data['link'] = get_comment_link( $comment ); 1554 } 1555 1556 if ( in_array( 'status', $fields, true ) ) { 1557 $data['status'] = $this->prepare_status_response( $comment->comment_approved ); 1558 } 1559 1560 if ( in_array( 'type', $fields, true ) ) { 1561 $data['type'] = get_comment_type( $comment->comment_ID ); 1562 } 1563 1564 if ( in_array( 'author_avatar_urls', $fields, true ) ) { 1565 $data['author_avatar_urls'] = rest_get_avatar_urls( $comment ); 1566 } 1567 1568 if ( in_array( 'meta', $fields, true ) ) { 1569 $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request ); 1570 } 1571 1572 if ( in_array( 'reaction_summary', $fields, true ) && 'note' === $comment->comment_type ) { 1573 $note_id = (int) $comment->comment_ID; 1574 1575 if ( null !== $this->reaction_summaries && isset( $this->reaction_summaries[ $note_id ] ) ) { 1576 $data['reaction_summary'] = $this->reaction_summaries[ $note_id ]; 1577 } else { 1578 // Single-item path (get_item or single create/update): query individually. 1579 $this->prefetch_reaction_summaries( array( $note_id ) ); 1580 $data['reaction_summary'] = $this->reaction_summaries[ $note_id ] ?? array(); 1581 // Reset so subsequent unrelated calls do not see this entry. 1582 $this->reaction_summaries = null; 1583 } 1584 } 1585 1586 $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; 1587 $data = $this->add_additional_fields_to_object( $data, $request ); 1588 $data = $this->filter_response_by_context( $data, $context ); 1589 1590 // Wrap the data in a response object. 1591 $response = rest_ensure_response( $data ); 1592 1593 if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { 1594 $links = $this->prepare_links( $comment ); 1595 $response->add_links( $links ); 1596 1597 if ( ! empty( $links['self']['href'] ) ) { 1598 $actions = $this->get_available_actions( $comment, $request ); 1599 1600 $self = $links['self']['href']; 1601 1602 foreach ( $actions as $rel ) { 1603 $response->add_link( $rel, $self ); 1604 } 1605 } 1606 } 1607 1608 /** 1609 * Filters a comment returned from the REST API. 1610 * 1611 * Allows modification of the comment right before it is returned. 1612 * 1613 * @since 4.7.0 1614 * 1615 * @param WP_REST_Response $response The response object. 1616 * @param WP_Comment $comment The original comment object. 1617 * @param WP_REST_Request $request Request used to generate the response. 1618 */ 1619 return apply_filters( 'rest_prepare_comment', $response, $comment, $request ); 1620 } 1621 1622 /** 1623 * Prepares links for the request. 1624 * 1625 * @since 4.7.0 1626 * 1627 * @param WP_Comment $comment Comment object. 1628 * @return array Links for the given comment. 1629 */ 1630 protected function prepare_links( $comment ) { 1631 $links = array( 1632 'self' => array( 1633 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ), 1634 ), 1635 'collection' => array( 1636 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), 1637 ), 1638 ); 1639 1640 if ( 0 !== (int) $comment->user_id ) { 1641 $links['author'] = array( 1642 'href' => rest_url( 'wp/v2/users/' . $comment->user_id ), 1643 'embeddable' => true, 1644 ); 1645 } 1646 1647 if ( 0 !== (int) $comment->comment_post_ID ) { 1648 $post = get_post( $comment->comment_post_ID ); 1649 $post_route = rest_get_route_for_post( $post ); 1650 1651 if ( ! empty( $post->ID ) && $post_route ) { 1652 $links['up'] = array( 1653 'href' => rest_url( $post_route ), 1654 'embeddable' => true, 1655 'post_type' => $post->post_type, 1656 ); 1657 } 1658 } 1659 1660 if ( 0 !== (int) $comment->comment_parent ) { 1661 $links['in-reply-to'] = array( 1662 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ), 1663 'embeddable' => true, 1664 ); 1665 } 1666 1667 /* 1668 * Only grab one comment to verify the comment has children. Reactions are 1669 * left out: they are summarized in `reaction_summary`, and counting them 1670 * would advertise a `children` link on a note that has no replies. 1671 */ 1672 $comment_children = $comment->get_children( 1673 array( 1674 'count' => true, 1675 'orderby' => 'none', 1676 'type' => 'all', 1677 'type__not_in' => array( 'reaction' ), 1678 ) 1679 ); 1680 1681 if ( ! empty( $comment_children ) ) { 1682 $args = array( 1683 'parent' => $comment->comment_ID, 1684 ); 1685 1686 $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) ); 1687 1688 $links['children'] = array( 1689 'href' => $rest_url, 1690 'embeddable' => true, 1691 ); 1692 } 1693 1694 // Embedding children for notes requires `type` and `status` inheritance. 1695 if ( isset( $links['children'] ) && 'note' === $comment->comment_type ) { 1696 $args = array( 1697 'parent' => $comment->comment_ID, 1698 'type' => $comment->comment_type, 1699 'status' => 'all', 1700 ); 1701 1702 $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) ); 1703 1704 $links['children'] = array( 1705 'href' => $rest_url, 1706 'embeddable' => true, 1707 ); 1708 } 1709 1710 return $links; 1711 } 1712 1713 /** 1714 * Gets the link relations available for the comment and current user. 1715 * 1716 * @since 7.2.0 1717 * 1718 * @param WP_Comment $comment Comment object. 1719 * @param WP_REST_Request $request Request object. 1720 * @return string[] List of link relations. 1721 * 1722 * @phpstan-return array<non-falsy-string> 1723 */ 1724 protected function get_available_actions( $comment, $request ) { 1725 if ( 'edit' !== $request['context'] ) { 1726 return array(); 1727 } 1728 1729 $rels = array(); 1730 1731 if ( 'trash' !== $comment->comment_approved && $this->check_edit_permission( $comment ) ) { 1732 /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */ 1733 if ( apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment ) ) { 1734 $rels[] = 'https://api.w.org/action-trash'; 1735 } 1736 } 1737 1738 return $rels; 1739 } 1740 1741 /** 1742 * Prepends internal property prefix to query parameters to match our response fields. 1743 * 1744 * @since 4.7.0 1745 * 1746 * @param string $query_param Query parameter. 1747 * @return string The normalized query parameter. 1748 */ 1749 protected function normalize_query_param( $query_param ) { 1750 $prefix = 'comment_'; 1751 1752 switch ( $query_param ) { 1753 case 'id': 1754 $normalized = $prefix . 'ID'; 1755 break; 1756 case 'post': 1757 $normalized = $prefix . 'post_ID'; 1758 break; 1759 case 'parent': 1760 $normalized = $prefix . 'parent'; 1761 break; 1762 case 'include': 1763 $normalized = 'comment__in'; 1764 break; 1765 default: 1766 $normalized = $prefix . $query_param; 1767 break; 1768 } 1769 1770 return $normalized; 1771 } 1772 1773 /** 1774 * Checks comment_approved to set comment status for single comment output. 1775 * 1776 * @since 4.7.0 1777 * 1778 * @param string $comment_approved Comment status. 1779 * @return string Comment status. 1780 */ 1781 protected function prepare_status_response( $comment_approved ) { 1782 1783 switch ( $comment_approved ) { 1784 case 'hold': 1785 case '0': 1786 $status = 'hold'; 1787 break; 1788 1789 case 'approve': 1790 case '1': 1791 $status = 'approved'; 1792 break; 1793 1794 case 'spam': 1795 case 'trash': 1796 default: 1797 $status = $comment_approved; 1798 break; 1799 } 1800 1801 return $status; 1802 } 1803 1804 /** 1805 * Prepares a single comment to be inserted into the database. 1806 * 1807 * @since 4.7.0 1808 * 1809 * @param WP_REST_Request $request Request object. 1810 * @return array|WP_Error Prepared comment, otherwise WP_Error object. 1811 */ 1812 protected function prepare_item_for_database( $request ) { 1813 $prepared_comment = array(); 1814 1815 /* 1816 * Allow the comment_content to be set via the 'content' or 1817 * the 'content.raw' properties of the Request object. 1818 */ 1819 if ( isset( $request['content'] ) && is_string( $request['content'] ) ) { 1820 $prepared_comment['comment_content'] = trim( $request['content'] ); 1821 } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) { 1822 $prepared_comment['comment_content'] = trim( $request['content']['raw'] ); 1823 } 1824 1825 if ( isset( $request['post'] ) ) { 1826 $prepared_comment['comment_post_ID'] = (int) $request['post']; 1827 } 1828 1829 if ( isset( $request['parent'] ) ) { 1830 $prepared_comment['comment_parent'] = $request['parent']; 1831 } 1832 1833 if ( isset( $request['author'] ) ) { 1834 $user = new WP_User( $request['author'] ); 1835 1836 if ( $user->exists() ) { 1837 $prepared_comment['user_id'] = $user->ID; 1838 $prepared_comment['comment_author'] = $user->display_name; 1839 $prepared_comment['comment_author_email'] = $user->user_email; 1840 $prepared_comment['comment_author_url'] = $user->user_url; 1841 } else { 1842 return new WP_Error( 1843 'rest_comment_author_invalid', 1844 __( 'Invalid comment author ID.' ), 1845 array( 'status' => 400 ) 1846 ); 1847 } 1848 } 1849 1850 if ( isset( $request['author_name'] ) ) { 1851 $prepared_comment['comment_author'] = $request['author_name']; 1852 } 1853 1854 if ( isset( $request['author_email'] ) ) { 1855 $prepared_comment['comment_author_email'] = $request['author_email']; 1856 } 1857 1858 if ( isset( $request['author_url'] ) ) { 1859 $prepared_comment['comment_author_url'] = $request['author_url']; 1860 } 1861 1862 if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) { 1863 $prepared_comment['comment_author_IP'] = $request['author_ip']; 1864 } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) { 1865 $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR']; 1866 } else { 1867 $prepared_comment['comment_author_IP'] = '127.0.0.1'; 1868 } 1869 1870 if ( ! empty( $request['author_user_agent'] ) ) { 1871 $prepared_comment['comment_agent'] = $request['author_user_agent']; 1872 } elseif ( $request->get_header( 'user_agent' ) ) { 1873 $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' ); 1874 } 1875 1876 if ( ! empty( $request['date'] ) ) { 1877 $date_data = rest_get_date_with_gmt( $request['date'] ); 1878 1879 if ( ! empty( $date_data ) ) { 1880 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data; 1881 } 1882 } elseif ( ! empty( $request['date_gmt'] ) ) { 1883 $date_data = rest_get_date_with_gmt( $request['date_gmt'], true ); 1884 1885 if ( ! empty( $date_data ) ) { 1886 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data; 1887 } 1888 } 1889 1890 /** 1891 * Filters a comment added via the REST API after it is prepared for insertion into the database. 1892 * 1893 * Allows modification of the comment right after it is prepared for the database. 1894 * 1895 * @since 4.7.0 1896 * 1897 * @param array $prepared_comment The prepared comment data for `wp_insert_comment`. 1898 * @param WP_REST_Request $request The current request. 1899 */ 1900 return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request ); 1901 } 1902 1903 /** 1904 * Retrieves the comment's schema, conforming to JSON Schema. 1905 * 1906 * @since 4.7.0 1907 * 1908 * @return array 1909 */ 1910 public function get_item_schema() { 1911 if ( $this->schema ) { 1912 return $this->add_additional_fields_schema( $this->schema ); 1913 } 1914 1915 $schema = array( 1916 '$schema' => 'http://json-schema.org/draft-04/schema#', 1917 'title' => 'comment', 1918 'type' => 'object', 1919 'properties' => array( 1920 'id' => array( 1921 'description' => __( 'Unique identifier for the comment.' ), 1922 'type' => 'integer', 1923 'context' => array( 'view', 'edit', 'embed' ), 1924 'readonly' => true, 1925 ), 1926 'author' => array( 1927 'description' => __( 'The ID of the user object, if author was a user.' ), 1928 'type' => 'integer', 1929 'context' => array( 'view', 'edit', 'embed' ), 1930 ), 1931 'author_email' => array( 1932 'description' => __( 'Email address for the comment author.' ), 1933 'type' => 'string', 1934 'format' => 'email', 1935 'context' => array( 'edit' ), 1936 'arg_options' => array( 1937 'sanitize_callback' => array( $this, 'check_comment_author_email' ), 1938 'validate_callback' => null, // Skip built-in validation of 'email'. 1939 ), 1940 ), 1941 'author_ip' => array( 1942 'description' => __( 'IP address for the comment author.' ), 1943 'type' => 'string', 1944 'format' => 'ip', 1945 'context' => array( 'edit' ), 1946 ), 1947 'author_name' => array( 1948 'description' => __( 'Display name for the comment author.' ), 1949 'type' => 'string', 1950 'context' => array( 'view', 'edit', 'embed' ), 1951 'arg_options' => array( 1952 'sanitize_callback' => 'sanitize_text_field', 1953 ), 1954 ), 1955 'author_url' => array( 1956 'description' => __( 'URL for the comment author.' ), 1957 'type' => 'string', 1958 'format' => 'uri', 1959 'context' => array( 'view', 'edit', 'embed' ), 1960 ), 1961 'author_user_agent' => array( 1962 'description' => __( 'User agent for the comment author.' ), 1963 'type' => 'string', 1964 'context' => array( 'edit' ), 1965 'arg_options' => array( 1966 'sanitize_callback' => 'sanitize_text_field', 1967 ), 1968 ), 1969 'content' => array( 1970 'description' => __( 'The content for the comment.' ), 1971 'type' => 'object', 1972 'context' => array( 'view', 'edit', 'embed' ), 1973 'arg_options' => array( 1974 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 1975 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). 1976 ), 1977 'properties' => array( 1978 'raw' => array( 1979 'description' => __( 'Content for the comment, as it exists in the database.' ), 1980 'type' => 'string', 1981 'context' => array( 'edit' ), 1982 ), 1983 'rendered' => array( 1984 'description' => __( 'HTML content for the comment, transformed for display.' ), 1985 'type' => 'string', 1986 'context' => array( 'view', 'edit', 'embed' ), 1987 'readonly' => true, 1988 ), 1989 ), 1990 ), 1991 'date' => array( 1992 'description' => __( "The date the comment was published, in the site's timezone." ), 1993 'type' => 'string', 1994 'format' => 'date-time', 1995 'context' => array( 'view', 'edit', 'embed' ), 1996 ), 1997 'date_gmt' => array( 1998 'description' => __( 'The date the comment was published, as GMT.' ), 1999 'type' => 'string', 2000 'format' => 'date-time', 2001 'context' => array( 'view', 'edit' ), 2002 ), 2003 'link' => array( 2004 'description' => __( 'URL to the comment.' ), 2005 'type' => 'string', 2006 'format' => 'uri', 2007 'context' => array( 'view', 'edit', 'embed' ), 2008 'readonly' => true, 2009 ), 2010 'parent' => array( 2011 'description' => __( 'The ID for the parent of the comment.' ), 2012 'type' => 'integer', 2013 'context' => array( 'view', 'edit', 'embed' ), 2014 'default' => 0, 2015 ), 2016 'post' => array( 2017 'description' => __( 'The ID of the associated post object.' ), 2018 'type' => 'integer', 2019 'context' => array( 'view', 'edit' ), 2020 'default' => 0, 2021 ), 2022 'status' => array( 2023 'description' => __( 'State of the comment.' ), 2024 'type' => 'string', 2025 'context' => array( 'view', 'edit' ), 2026 'arg_options' => array( 2027 'sanitize_callback' => 'sanitize_key', 2028 ), 2029 ), 2030 'type' => array( 2031 'description' => __( 'Type of the comment.' ), 2032 'type' => 'string', 2033 'context' => array( 'view', 'edit', 'embed' ), 2034 'readonly' => true, 2035 'default' => 'comment', 2036 ), 2037 'reaction_summary' => array( 2038 'description' => __( 'Aggregated reaction counts for this note, keyed by emoji hex key.' ), 2039 'type' => 'object', 2040 'context' => array( 'view', 'edit' ), 2041 'readonly' => true, 2042 'additionalProperties' => array( 2043 'type' => 'object', 2044 'properties' => array( 2045 'count' => array( 2046 'description' => __( 'Total number of reactions with this emoji.' ), 2047 'type' => 'integer', 2048 'minimum' => 0, 2049 ), 2050 'current_user_reaction' => array( 2051 'description' => __( "The current user's reaction comment ID for this emoji, or 0 if they have not reacted." ), 2052 'type' => 'integer', 2053 'minimum' => 0, 2054 ), 2055 ), 2056 ), 2057 ), 2058 ), 2059 ); 2060 2061 if ( get_option( 'show_avatars' ) ) { 2062 $avatar_properties = array(); 2063 2064 $avatar_sizes = rest_get_avatar_sizes(); 2065 2066 foreach ( $avatar_sizes as $size ) { 2067 $avatar_properties[ $size ] = array( 2068 /* translators: %d: Avatar image size in pixels. */ 2069 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ), 2070 'type' => 'string', 2071 'format' => 'uri', 2072 'context' => array( 'embed', 'view', 'edit' ), 2073 ); 2074 } 2075 2076 $schema['properties']['author_avatar_urls'] = array( 2077 'description' => __( 'Avatar URLs for the comment author.' ), 2078 'type' => 'object', 2079 'context' => array( 'view', 'edit', 'embed' ), 2080 'readonly' => true, 2081 'properties' => $avatar_properties, 2082 ); 2083 } 2084 2085 $schema['properties']['meta'] = $this->meta->get_field_schema(); 2086 2087 $this->schema = $schema; 2088 2089 return $this->add_additional_fields_schema( $this->schema ); 2090 } 2091 2092 /** 2093 * Retrieves the query params for collections. 2094 * 2095 * @since 4.7.0 2096 * 2097 * @return array Comments collection parameters. 2098 */ 2099 public function get_collection_params() { 2100 $query_params = parent::get_collection_params(); 2101 2102 $query_params['context']['default'] = 'view'; 2103 2104 $query_params['after'] = array( 2105 'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ), 2106 'type' => 'string', 2107 'format' => 'date-time', 2108 ); 2109 2110 $query_params['author'] = array( 2111 'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ), 2112 'type' => 'array', 2113 'items' => array( 2114 'type' => 'integer', 2115 ), 2116 ); 2117 2118 $query_params['author_exclude'] = array( 2119 'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ), 2120 'type' => 'array', 2121 'items' => array( 2122 'type' => 'integer', 2123 ), 2124 ); 2125 2126 $query_params['author_email'] = array( 2127 'default' => null, 2128 'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ), 2129 'format' => 'email', 2130 'type' => 'string', 2131 ); 2132 2133 $query_params['before'] = array( 2134 'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ), 2135 'type' => 'string', 2136 'format' => 'date-time', 2137 ); 2138 2139 $query_params['exclude'] = array( 2140 'description' => __( 'Ensure result set excludes specific IDs.' ), 2141 'type' => 'array', 2142 'items' => array( 2143 'type' => 'integer', 2144 ), 2145 'default' => array(), 2146 ); 2147 2148 $query_params['include'] = array( 2149 'description' => __( 'Limit result set to specific IDs.' ), 2150 'type' => 'array', 2151 'items' => array( 2152 'type' => 'integer', 2153 ), 2154 'default' => array(), 2155 ); 2156 2157 $query_params['offset'] = array( 2158 'description' => __( 'Offset the result set by a specific number of items.' ), 2159 'type' => 'integer', 2160 ); 2161 2162 $query_params['order'] = array( 2163 'description' => __( 'Order sort attribute ascending or descending.' ), 2164 'type' => 'string', 2165 'default' => 'desc', 2166 'enum' => array( 2167 'asc', 2168 'desc', 2169 ), 2170 ); 2171 2172 $query_params['orderby'] = array( 2173 'description' => __( 'Sort collection by comment attribute.' ), 2174 'type' => 'string', 2175 'default' => 'date_gmt', 2176 'enum' => array( 2177 'date', 2178 'date_gmt', 2179 'id', 2180 'include', 2181 'post', 2182 'parent', 2183 'type', 2184 ), 2185 ); 2186 2187 $query_params['parent'] = array( 2188 'default' => array(), 2189 'description' => __( 'Limit result set to comments of specific parent IDs.' ), 2190 'type' => 'array', 2191 'items' => array( 2192 'type' => 'integer', 2193 ), 2194 ); 2195 2196 $query_params['parent_exclude'] = array( 2197 'default' => array(), 2198 'description' => __( 'Ensure result set excludes specific parent IDs.' ), 2199 'type' => 'array', 2200 'items' => array( 2201 'type' => 'integer', 2202 ), 2203 ); 2204 2205 $query_params['post'] = array( 2206 'default' => array(), 2207 'description' => __( 'Limit result set to comments assigned to specific post IDs.' ), 2208 'type' => 'array', 2209 'items' => array( 2210 'type' => 'integer', 2211 ), 2212 ); 2213 2214 $query_params['status'] = array( 2215 'default' => array( 'approve' ), 2216 'description' => __( 'Limit result set to comments assigned one or more statuses. Requires authorization.' ), 2217 'type' => 'array', 2218 'items' => array( 2219 'type' => 'string', 2220 ), 2221 'sanitize_callback' => array( $this, 'sanitize_comment_statuses' ), 2222 'validate_callback' => 'rest_validate_request_arg', 2223 ); 2224 2225 $query_params['type'] = array( 2226 'default' => 'comment', 2227 'description' => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ), 2228 'sanitize_callback' => 'sanitize_key', 2229 'type' => 'string', 2230 'validate_callback' => 'rest_validate_request_arg', 2231 ); 2232 2233 $query_params['password'] = array( 2234 'description' => __( 'The password for the post if it is password protected.' ), 2235 'type' => 'string', 2236 ); 2237 2238 /** 2239 * Filters REST API collection parameters for the comments controller. 2240 * 2241 * This filter registers the collection parameter, but does not map the 2242 * collection parameter to an internal WP_Comment_Query parameter. Use the 2243 * `rest_comment_query` filter to set WP_Comment_Query parameters. 2244 * 2245 * @since 4.7.0 2246 * 2247 * @param array $query_params JSON Schema-formatted collection parameters. 2248 */ 2249 return apply_filters( 'rest_comment_collection_params', $query_params ); 2250 } 2251 2252 /** 2253 * Sets the comment_status of a given comment object when creating or updating a comment. 2254 * 2255 * @since 4.7.0 2256 * 2257 * @param string|int $new_status New comment status. 2258 * @param int $comment_id Comment ID. 2259 * @return bool Whether the status was changed. 2260 */ 2261 protected function handle_status_param( $new_status, $comment_id ) { 2262 $old_status = wp_get_comment_status( $comment_id ); 2263 2264 if ( $new_status === $old_status ) { 2265 return false; 2266 } 2267 2268 switch ( $new_status ) { 2269 case 'approved': 2270 case 'approve': 2271 case '1': 2272 $changed = wp_set_comment_status( $comment_id, 'approve' ); 2273 break; 2274 case 'hold': 2275 case '0': 2276 $changed = wp_set_comment_status( $comment_id, 'hold' ); 2277 break; 2278 case 'spam': 2279 $changed = wp_spam_comment( $comment_id ); 2280 break; 2281 case 'unspam': 2282 $changed = wp_unspam_comment( $comment_id ); 2283 break; 2284 case 'trash': 2285 $changed = wp_trash_comment( $comment_id ); 2286 break; 2287 case 'untrash': 2288 $changed = wp_untrash_comment( $comment_id ); 2289 break; 2290 default: 2291 $changed = false; 2292 break; 2293 } 2294 2295 return $changed; 2296 } 2297 2298 /** 2299 * Checks if the post can be read. 2300 * 2301 * Correctly handles posts with the inherit status. 2302 * 2303 * @since 4.7.0 2304 * 2305 * @param WP_Post $post Post object. 2306 * @param WP_REST_Request $request Request data to check. 2307 * @return bool Whether post can be read. 2308 */ 2309 protected function check_read_post_permission( $post, $request ) { 2310 $post_type = get_post_type_object( $post->post_type ); 2311 2312 // Return false if custom post type doesn't exist 2313 if ( ! $post_type ) { 2314 return false; 2315 } 2316 2317 $posts_controller = $post_type->get_rest_controller(); 2318 2319 /* 2320 * Ensure the posts controller is specifically a WP_REST_Posts_Controller instance 2321 * before using methods specific to that controller. 2322 */ 2323 if ( ! $posts_controller instanceof WP_REST_Posts_Controller ) { 2324 $posts_controller = new WP_REST_Posts_Controller( $post->post_type ); 2325 } 2326 2327 $has_password_filter = false; 2328 2329 // Only check password if a specific post was queried for or a single comment 2330 $requested_post = ! empty( $request['post'] ) && ( ! is_array( $request['post'] ) || 1 === count( $request['post'] ) ); 2331 $requested_comment = ! empty( $request['id'] ); 2332 if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) { 2333 add_filter( 'post_password_required', '__return_false' ); 2334 2335 $has_password_filter = true; 2336 } 2337 2338 if ( post_password_required( $post ) ) { 2339 $result = current_user_can( 'edit_post', $post->ID ); 2340 } else { 2341 $result = $posts_controller->check_read_permission( $post ); 2342 } 2343 2344 if ( $has_password_filter ) { 2345 remove_filter( 'post_password_required', '__return_false' ); 2346 } 2347 2348 return $result; 2349 } 2350 2351 /** 2352 * Pre-fetches reaction summaries for a set of note IDs. 2353 * 2354 * Runs two aggregated queries (one for the per-emoji counts, one for the 2355 * current user's own reactions) and stores the result in 2356 * $this->reaction_summaries, keyed by note comment ID. This lets a 2357 * batched note listing return reaction_summary for many notes without 2358 * issuing a per-note query. 2359 * 2360 * @since 7.2.0 2361 * 2362 * @global wpdb $wpdb WordPress database abstraction object. 2363 * 2364 * @param int[] $note_ids Array of note comment IDs. 2365 */ 2366 protected function prefetch_reaction_summaries( $note_ids ) { 2367 global $wpdb; 2368 2369 $this->reaction_summaries = array(); 2370 2371 if ( empty( $note_ids ) ) { 2372 return; 2373 } 2374 2375 $current_user_id = get_current_user_id(); 2376 2377 $parent_in = $wpdb->prepare( 2378 'comment_parent IN (' . implode( ',', array_fill( 0, count( $note_ids ), '%d' ) ) . ')', 2379 ...$note_ids 2380 ); 2381 2382 // Query 1: Get aggregated counts per emoji per note. 2383 $query = "SELECT comment_parent, comment_content, COUNT(*) AS reaction_count FROM $wpdb->comments WHERE comment_type = 'reaction' AND comment_approved = '1' AND "; 2384 $query .= $parent_in; 2385 $query .= ' GROUP BY comment_parent, comment_content'; 2386 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 2387 $counts = $wpdb->get_results( $query ); 2388 2389 // Query 2: Get the current user's own reaction IDs (if logged in). 2390 $my_reactions = array(); 2391 if ( $current_user_id ) { 2392 $query = "SELECT comment_ID, comment_parent, comment_content FROM $wpdb->comments WHERE comment_type = 'reaction' AND comment_approved = '1' AND "; 2393 $query .= $parent_in; 2394 $query .= $wpdb->prepare( ' AND user_id = %d', $current_user_id ); 2395 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 2396 $user_rows = $wpdb->get_results( $query ); 2397 2398 if ( $user_rows ) { 2399 foreach ( $user_rows as $row ) { 2400 $key = (int) $row->comment_parent . ':' . wp_strip_all_tags( $row->comment_content ); 2401 $my_reactions[ $key ] = (int) $row->comment_ID; 2402 } 2403 } 2404 } 2405 2406 // Initialize empty summaries for every requested note ID. 2407 foreach ( $note_ids as $note_id ) { 2408 $this->reaction_summaries[ $note_id ] = array(); 2409 } 2410 2411 if ( ! $counts ) { 2412 return; 2413 } 2414 2415 foreach ( $counts as $row ) { 2416 $note_id = (int) $row->comment_parent; 2417 $emoji_key = wp_strip_all_tags( $row->comment_content ); 2418 $key = $note_id . ':' . $emoji_key; 2419 2420 $this->reaction_summaries[ $note_id ][ $emoji_key ] = array( 2421 'count' => (int) $row->reaction_count, 2422 'current_user_reaction' => $my_reactions[ $key ] ?? 0, 2423 ); 2424 } 2425 } 2426 2427 /** 2428 * Checks if the comment can be read. 2429 * 2430 * @since 4.7.0 2431 * 2432 * @param WP_Comment $comment Comment object. 2433 * @param WP_REST_Request $request Request data to check. 2434 * @return bool Whether the comment can be read. 2435 */ 2436 protected function check_read_permission( $comment, $request ) { 2437 if ( ! in_array( $comment->comment_type, array( 'note', 'reaction' ), true ) && ! empty( $comment->comment_post_ID ) ) { 2438 $post = get_post( $comment->comment_post_ID ); 2439 if ( $post ) { 2440 if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) { 2441 return true; 2442 } 2443 } 2444 } 2445 2446 if ( 0 === get_current_user_id() ) { 2447 return false; 2448 } 2449 2450 if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) { 2451 return false; 2452 } 2453 2454 if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) { 2455 return true; 2456 } 2457 2458 return current_user_can( 'edit_comment', $comment->comment_ID ); 2459 } 2460 2461 /** 2462 * Checks if a comment can be edited or deleted. 2463 * 2464 * @since 4.7.0 2465 * 2466 * @param WP_Comment $comment Comment object. 2467 * @return bool Whether the comment can be edited or deleted. 2468 */ 2469 protected function check_edit_permission( $comment ) { 2470 if ( 0 === (int) get_current_user_id() ) { 2471 return false; 2472 } 2473 2474 /* 2475 * Notes and their reactions are editorial content, so require edit access 2476 * to the note's post rather than the moderate_comments capability. 2477 */ 2478 if ( in_array( strtolower( $comment->comment_type ), array( 'note', 'reaction' ), true ) ) { 2479 return current_user_can( 'edit_comment', $comment->comment_ID ); 2480 } 2481 2482 if ( current_user_can( 'moderate_comments' ) ) { 2483 return true; 2484 } 2485 2486 return current_user_can( 'edit_comment', $comment->comment_ID ); 2487 } 2488 2489 /** 2490 * Checks whether the current user can attribute a comment to another user. 2491 * 2492 * @since 7.1.5 2493 * 2494 * @param int $author_id ID of the user the comment is being attributed to. 2495 * @return bool Whether the comment can be attributed to the user. 2496 */ 2497 protected function check_assign_author_permission( $author_id ) { 2498 return current_user_can( 'moderate_comments' ) && is_user_member_of_blog( $author_id ); 2499 } 2500 2501 /** 2502 * Checks a comment author email for validity. 2503 * 2504 * Accepts either a valid email address or empty string as a valid comment 2505 * author email address. Setting the comment author email to an empty 2506 * string is allowed when a comment is being updated. 2507 * 2508 * @since 4.7.0 2509 * 2510 * @param string $value Author email value submitted. 2511 * @param WP_REST_Request $request Full details about the request. 2512 * @param string $param The parameter name. 2513 * @return string|WP_Error The sanitized email address, if valid, 2514 * otherwise an error. 2515 */ 2516 public function check_comment_author_email( $value, $request, $param ) { 2517 $email = (string) $value; 2518 if ( empty( $email ) ) { 2519 return $email; 2520 } 2521 2522 $check_email = rest_validate_request_arg( $email, $request, $param ); 2523 if ( is_wp_error( $check_email ) ) { 2524 return $check_email; 2525 } 2526 2527 return $email; 2528 } 2529 2530 /** 2531 * If empty comments are not allowed, checks if the provided comment content is not empty. 2532 * 2533 * @since 5.6.0 2534 * 2535 * @param array $prepared_comment The prepared comment data. 2536 * @return bool True if the content is allowed, false otherwise. 2537 */ 2538 protected function check_is_comment_content_allowed( $prepared_comment ) { 2539 if ( ! isset( $prepared_comment['comment_content'] ) ) { 2540 return true; 2541 } 2542 2543 $check = wp_parse_args( 2544 $prepared_comment, 2545 array( 2546 'comment_post_ID' => 0, 2547 'comment_author' => null, 2548 'comment_author_email' => null, 2549 'comment_author_url' => null, 2550 'comment_parent' => 0, 2551 'user_id' => 0, 2552 ) 2553 ); 2554 2555 /** This filter is documented in wp-includes/comment.php */ 2556 $allow_empty = apply_filters( 'allow_empty_comment', false, $check ); 2557 2558 if ( $allow_empty ) { 2559 return true; 2560 } 2561 2562 // Allow empty notes only when resolution metadata is valid. 2563 if ( 2564 isset( $check['comment_type'] ) && 2565 'note' === $check['comment_type'] && 2566 isset( $check['meta']['_wp_note_status'] ) && 2567 in_array( $check['meta']['_wp_note_status'], array( 'resolved', 'reopen' ), true ) 2568 ) { 2569 return true; 2570 } 2571 2572 /* 2573 * Do not allow a comment to be created with missing or empty 2574 * comment_content. See wp_handle_comment_submission(). 2575 */ 2576 return '' !== $check['comment_content']; 2577 } 2578 2579 /** 2580 * Sanitizes a single comment status or a list of comment statuses. 2581 * 2582 * @since 7.2.0 2583 * 2584 * @param string[]|string $statuses Comment status or array of comment statuses. 2585 * @return string[] Sanitized array of comment statuses. 2586 * @phpstan-return list<non-empty-lowercase-string> 2587 */ 2588 public function sanitize_comment_statuses( $statuses ): array { 2589 $statuses = array_unique( array_map( 'sanitize_key', wp_parse_list( $statuses ) ) ); 2590 2591 // Only drop empty values. A literal '0' is a queryable status, as comments are held with `comment_approved` of '0'. 2592 $statuses = array_filter( 2593 $statuses, 2594 static function ( $status ) { 2595 return '' !== $status; 2596 } 2597 ); 2598 2599 return array_values( $statuses ); 2600 } 2601 2602 /** 2603 * Checks that a post can receive a comment or a note from the current user. 2604 * 2605 * Used when creating a note and when changing the parent post of an existing 2606 * comment or note, so that attaching content to a post is authorized the same 2607 * way whichever path it arrives by. 2608 * 2609 * @since 7.1.1 2610 * 2611 * @param int $post_id Target post ID. 2612 * @param WP_REST_Request $request Full details about the request. 2613 * @param bool $is_note Optional. Whether the comment is a note. Default false. 2614 * @return true|WP_Error True if the post can receive the comment, error object otherwise. 2615 */ 2616 protected function check_target_post_permission( int $post_id, WP_REST_Request $request, bool $is_note = false ) { 2617 if ( ! $post_id ) { 2618 return new WP_Error( 2619 'rest_comment_invalid_post_id', 2620 __( 'Sorry, you are not allowed to create this comment without a post.' ), 2621 array( 'status' => 403 ) 2622 ); 2623 } 2624 2625 /* 2626 * Notes are editorial content, so they may only be attached to a post the 2627 * user can edit. Any other comment needs either comment moderation rights 2628 * or edit access to the post, which is what check_edit_permission() grants 2629 * on the post a comment is moving away from. Requiring the same at the 2630 * destination means both ends of a move are authorized alike. 2631 */ 2632 if ( $is_note ) { 2633 $can_target_post = current_user_can( 'edit_post', $post_id ); 2634 } else { 2635 $can_target_post = current_user_can( 'moderate_comments' ) || current_user_can( 'edit_post', $post_id ); 2636 } 2637 2638 if ( ! $can_target_post ) { 2639 if ( $is_note ) { 2640 return new WP_Error( 2641 'rest_cannot_create_note', 2642 __( 'Sorry, you are not allowed to create notes for this post.' ), 2643 array( 'status' => rest_authorization_required_code() ) 2644 ); 2645 } 2646 2647 return new WP_Error( 2648 'rest_cannot_edit', 2649 __( 'Sorry, you are not allowed to edit this comment.' ), 2650 array( 'status' => rest_authorization_required_code() ) 2651 ); 2652 } 2653 2654 $post = get_post( $post_id ); 2655 2656 if ( ! $post ) { 2657 return new WP_Error( 2658 'rest_comment_invalid_post_id', 2659 __( 'Sorry, you are not allowed to create this comment without a post.' ), 2660 array( 'status' => 403 ) 2661 ); 2662 } 2663 2664 /* 2665 * The remaining rules mirror the create-time checks for notes only. They are 2666 * deliberately not applied to other comments, because moderators move comments 2667 * onto posts whose discussion has closed and onto drafts today. Enforcing the 2668 * create-time rules there would break that without blocking anything the 2669 * capability check above already permits. 2670 */ 2671 if ( ! $is_note ) { 2672 return true; 2673 } 2674 2675 if ( ! $this->check_post_type_supports_notes( $post->post_type ) ) { 2676 return new WP_Error( 2677 'rest_comment_not_supported_post_type', 2678 __( 'Sorry, this post type does not support notes.' ), 2679 array( 'status' => 403 ) 2680 ); 2681 } 2682 2683 if ( 'trash' === $post->post_status ) { 2684 return new WP_Error( 2685 'rest_comment_trash_post', 2686 __( 'Sorry, you are not allowed to create a comment on this post.' ), 2687 array( 'status' => 403 ) 2688 ); 2689 } 2690 2691 if ( ! $this->check_read_post_permission( $post, $request ) ) { 2692 return new WP_Error( 2693 'rest_cannot_read_post', 2694 __( 'Sorry, you are not allowed to read the post for this comment.' ), 2695 array( 'status' => rest_authorization_required_code() ) 2696 ); 2697 } 2698 2699 return true; 2700 } 2701 2702 /** 2703 * Checks whether a note belongs to a resolved thread. 2704 * 2705 * Resolving a thread approves its root note. 2706 * 2707 * @since 7.2.0 2708 * 2709 * @param WP_Comment $note A root note or a reply. 2710 * @return bool True if the note's thread is resolved. 2711 */ 2712 private function is_thread_resolved( WP_Comment $note ): bool { 2713 $thread_root = $note; 2714 $visited = array( (int) $thread_root->comment_ID => true ); 2715 while ( $thread_root->comment_parent ) { 2716 $ancestor = get_comment( $thread_root->comment_parent ); 2717 2718 // Stop at a missing ancestor or a corrupt, cyclic chain. 2719 if ( ! $ancestor || isset( $visited[ (int) $ancestor->comment_ID ] ) ) { 2720 break; 2721 } 2722 2723 $visited[ (int) $ancestor->comment_ID ] = true; 2724 $thread_root = $ancestor; 2725 } 2726 2727 return '1' === $thread_root->comment_approved; 2728 } 2729 2730 /** 2731 * Check if post type supports notes. 2732 * 2733 * @since 6.9.0 2734 * 2735 * @param string $post_type Post type name. 2736 * @return bool True if post type supports notes, false otherwise. 2737 */ 2738 private function check_post_type_supports_notes( $post_type ) { 2739 $supports = get_all_post_type_supports( $post_type ); 2740 2741 if ( ! isset( $supports['editor'] ) ) { 2742 return false; 2743 } 2744 2745 if ( ! is_array( $supports['editor'] ) ) { 2746 return false; 2747 } 2748 2749 return array_any( $supports['editor'], fn( $item ) => ! empty( $item['notes'] ) ); 2750 } 2751 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Sat Nov 21 08:20:02 2026 | Cross-referenced by PHPXref |