[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/rest-api/endpoints/ -> class-wp-rest-comments-controller.php (source)

   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          if ( 'note' === $request['type'] && $request['parent'] ) {
 735              $parent_check = $this->check_note_parent( absint( $request['parent'] ), absint( $request['post'] ) );
 736  
 737              if ( is_wp_error( $parent_check ) ) {
 738                  return $parent_check;
 739              }
 740          }
 741  
 742          /*
 743           * The canonical reaction key, populated once validated below so the
 744           * stored content matches what was validated (not the raw input).
 745           */
 746          $reaction_key = null;
 747  
 748          // Validate reaction-specific constraints.
 749          if ( ! empty( $request['type'] ) && 'reaction' === $request['type'] ) {
 750              // Reaction parent must be specified.
 751              if ( empty( $request['parent'] ) ) {
 752                  return new WP_Error(
 753                      'rest_comment_invalid_parent',
 754                      __( 'A reaction must have a parent note.' ),
 755                      array( 'status' => 400 )
 756                  );
 757              }
 758  
 759              // Reaction parent must exist and be a note.
 760              $parent_comment = get_comment( $request['parent'] );
 761              if ( ! $parent_comment || 'note' !== $parent_comment->comment_type ) {
 762                  return new WP_Error(
 763                      'rest_comment_invalid_parent',
 764                      __( 'A reaction must be attached to a note.' ),
 765                      array( 'status' => 400 )
 766                  );
 767              }
 768  
 769              /*
 770               * The parent note must belong to the post the reaction targets.
 771               * create_item_permissions_check() requires `post` and checks that the
 772               * user can edit it, so this runs before the parent's status checks:
 773               * a note on another post gets the same error whatever its status,
 774               * rather than revealing whether it is trashed, spammed or resolved.
 775               */
 776              if ( ! empty( $request['post'] ) && (int) $parent_comment->comment_post_ID !== (int) $request['post'] ) {
 777                  return new WP_Error(
 778                      'rest_comment_invalid_parent',
 779                      __( 'A reaction must be attached to a note on the same post.' ),
 780                      array( 'status' => 400 )
 781                  );
 782              }
 783  
 784              // A reaction under a trashed or spammed note would escape the trash cascade.
 785              if ( in_array( $parent_comment->comment_approved, array( 'trash', 'spam' ), true ) ) {
 786                  return new WP_Error(
 787                      'rest_comment_invalid_parent',
 788                      __( 'A reaction cannot be added to a trashed or spam note.' ),
 789                      array( 'status' => 400 )
 790                  );
 791              }
 792  
 793              /*
 794               * Resolving a thread approves its root note, and the editor disables
 795               * reactions from then on. Hold requests from stale editor sessions
 796               * to that too, for the root note and for every reply in its thread.
 797               */
 798              if ( $this->is_thread_resolved( $parent_comment ) ) {
 799                  return new WP_Error(
 800                      'rest_comment_invalid_parent',
 801                      __( 'A reaction cannot be added to a resolved note.' ),
 802                      array( 'status' => 400 )
 803                  );
 804              }
 805  
 806              /*
 807               * Validate the reaction content: the hex key of one of the curated
 808               * reaction emoji, as listed by self::get_note_reaction_keys() (e.g.
 809               * `2764` for the heart). Raw emoji bytes are rejected because the
 810               * comments table is not guaranteed to be utf8mb4 across all WordPress
 811               * installs; clients are expected to normalize before submitting.
 812               *
 813               * Read the content the same two ways prepare_item_for_database()
 814               * does, so `content` and `content.raw` are both accepted.
 815               */
 816              $raw_content = '';
 817              if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
 818                  $raw_content = $request['content'];
 819              } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
 820                  $raw_content = $request['content']['raw'];
 821              }
 822  
 823              $emoji_key = trim( wp_strip_all_tags( $raw_content ) );
 824  
 825              if ( ! in_array( $emoji_key, self::get_note_reaction_keys(), true ) ) {
 826                  return new WP_Error(
 827                      'rest_comment_invalid_reaction',
 828                      __( 'Invalid reaction emoji.' ),
 829                      array( 'status' => 400 )
 830                  );
 831              }
 832  
 833              /*
 834               * A reaction is always approved. The uniqueness check, the race
 835               * cleanup below and the reaction summary only see approved rows, so
 836               * a reaction created in any other status could never be counted,
 837               * deduplicated or, since reactions cannot be updated, fixed.
 838               */
 839              if ( isset( $request['status'] ) && ! in_array( $request['status'], array( 'approve', 'approved', '1' ), true ) ) {
 840                  return new WP_Error(
 841                      'rest_comment_invalid_status',
 842                      __( 'A reaction cannot be created with that status.' ),
 843                      array( 'status' => 400 )
 844                  );
 845              }
 846  
 847              /*
 848               * Enforce uniqueness: one emoji per user per note.
 849               *
 850               * Scope to active (approved) reactions only — trashed reactions
 851               * are invisible to the user and must not block re-adding the
 852               * same emoji. The same goes for a reaction stored on another
 853               * post, which the reaction summary leaves out.
 854               */
 855              $existing = get_comments(
 856                  array(
 857                      'post_id' => absint( $request['post'] ),
 858                      'parent'  => $request['parent'],
 859                      'user_id' => get_current_user_id(),
 860                      'type'    => 'reaction',
 861                      'status'  => 'approve',
 862                  )
 863              );
 864  
 865              foreach ( $existing as $existing_reaction ) {
 866                  if ( wp_strip_all_tags( $existing_reaction->comment_content ) === $emoji_key ) {
 867                      return new WP_Error(
 868                          'rest_comment_duplicate_reaction',
 869                          __( 'You have already reacted with this emoji.' ),
 870                          array( 'status' => 409 )
 871                      );
 872                  }
 873              }
 874  
 875              $reaction_key = $emoji_key;
 876          }
 877  
 878          $prepared_comment = $this->prepare_item_for_database( $request );
 879          if ( is_wp_error( $prepared_comment ) ) {
 880              return $prepared_comment;
 881          }
 882  
 883          $prepared_comment['comment_type'] = $request['type'];
 884  
 885          /*
 886           * Persist the validated, canonical reaction key rather than the raw
 887           * request content, so stored values stay consistent for grouping and
 888           * counting (e.g. "<b>2764</b>" is stored as "2764").
 889           */
 890          if ( null !== $reaction_key ) {
 891              $prepared_comment['comment_content'] = $reaction_key;
 892          }
 893  
 894          if ( ! isset( $prepared_comment['comment_content'] ) ) {
 895              $prepared_comment['comment_content'] = '';
 896          }
 897  
 898          // Include note metadata into check_is_comment_content_allowed.
 899          if ( isset( $request['meta']['_wp_note_status'] ) ) {
 900              $prepared_comment['meta']['_wp_note_status'] = $request['meta']['_wp_note_status'];
 901          }
 902  
 903          if ( ! $this->check_is_comment_content_allowed( $prepared_comment ) ) {
 904              return new WP_Error(
 905                  'rest_comment_content_invalid',
 906                  __( 'Invalid comment content.' ),
 907                  array( 'status' => 400 )
 908              );
 909          }
 910  
 911          // Setting remaining values before wp_insert_comment so we can use wp_allow_comment().
 912          if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) {
 913              $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true );
 914          }
 915  
 916          // Set author data if the user's logged in.
 917          $missing_author = empty( $prepared_comment['user_id'] )
 918              && empty( $prepared_comment['comment_author'] )
 919              && empty( $prepared_comment['comment_author_email'] )
 920              && empty( $prepared_comment['comment_author_url'] );
 921  
 922          if ( is_user_logged_in() && $missing_author ) {
 923              $user = wp_get_current_user();
 924  
 925              $prepared_comment['user_id']              = $user->ID;
 926              $prepared_comment['comment_author']       = $user->display_name;
 927              $prepared_comment['comment_author_email'] = $user->user_email;
 928              $prepared_comment['comment_author_url']   = $user->user_url;
 929          }
 930  
 931          /*
 932           * Pin a reaction to the current user, whatever author details the request
 933           * carried. Author fields alone leave `user_id` at 0, which the uniqueness
 934           * check and the reaction summary both key on.
 935           */
 936          if ( null !== $reaction_key ) {
 937              $user = wp_get_current_user();
 938  
 939              $prepared_comment['user_id']              = $user->ID;
 940              $prepared_comment['comment_author']       = $user->display_name;
 941              $prepared_comment['comment_author_email'] = $user->user_email;
 942              $prepared_comment['comment_author_url']   = $user->user_url;
 943          }
 944  
 945          // Honor the discussion setting that requires a name and email address of the comment author.
 946          if ( get_option( 'require_name_email' ) ) {
 947              if ( empty( $prepared_comment['comment_author'] ) || empty( $prepared_comment['comment_author_email'] ) ) {
 948                  return new WP_Error(
 949                      'rest_comment_author_data_required',
 950                      __( 'Creating a comment requires valid author name and email values.' ),
 951                      array( 'status' => 400 )
 952                  );
 953              }
 954          }
 955  
 956          if ( ! isset( $prepared_comment['comment_author_email'] ) ) {
 957              $prepared_comment['comment_author_email'] = '';
 958          }
 959  
 960          if ( ! isset( $prepared_comment['comment_author_url'] ) ) {
 961              $prepared_comment['comment_author_url'] = '';
 962          }
 963  
 964          if ( ! isset( $prepared_comment['comment_agent'] ) ) {
 965              $prepared_comment['comment_agent'] = '';
 966          }
 967  
 968          $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_comment );
 969  
 970          if ( is_wp_error( $check_comment_lengths ) ) {
 971              $error_code = $check_comment_lengths->get_error_code();
 972              return new WP_Error(
 973                  $error_code,
 974                  __( 'Comment field exceeds maximum length allowed.' ),
 975                  array( 'status' => 400 )
 976              );
 977          }
 978  
 979          // Don't check for duplicates or flooding for notes or reactions.
 980          $prepared_comment['comment_approved'] =
 981              in_array( $prepared_comment['comment_type'], array( 'note', 'reaction' ), true ) ?
 982              '1' :
 983              wp_allow_comment( $prepared_comment, true );
 984  
 985          if ( is_wp_error( $prepared_comment['comment_approved'] ) ) {
 986              $error_code    = $prepared_comment['comment_approved']->get_error_code();
 987              $error_message = $prepared_comment['comment_approved']->get_error_message();
 988  
 989              if ( 'comment_duplicate' === $error_code ) {
 990                  return new WP_Error(
 991                      $error_code,
 992                      $error_message,
 993                      array( 'status' => 409 )
 994                  );
 995              }
 996  
 997              if ( 'comment_flood' === $error_code ) {
 998                  return new WP_Error(
 999                      $error_code,
1000                      $error_message,
1001                      array( 'status' => 400 )
1002                  );
1003              }
1004  
1005              return $prepared_comment['comment_approved'];
1006          }
1007  
1008          /**
1009           * Filters a comment before it is inserted via the REST API.
1010           *
1011           * Allows modification of the comment right before it is inserted via wp_insert_comment().
1012           * Returning a WP_Error value from the filter will short-circuit insertion and allow
1013           * skipping further processing.
1014           *
1015           * @since 4.7.0
1016           * @since 4.8.0 `$prepared_comment` can now be a WP_Error to short-circuit insertion.
1017           *
1018           * @param array|WP_Error  $prepared_comment The prepared comment data for wp_insert_comment().
1019           * @param WP_REST_Request $request          Request used to insert the comment.
1020           */
1021          $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request );
1022          if ( is_wp_error( $prepared_comment ) ) {
1023              return $prepared_comment;
1024          }
1025  
1026          $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) );
1027  
1028          if ( ! $comment_id ) {
1029              return new WP_Error(
1030                  'rest_comment_failed_create',
1031                  __( 'Creating comment failed.' ),
1032                  array( 'status' => 500 )
1033              );
1034          }
1035  
1036          /*
1037           * The pre-insert uniqueness check is not atomic, so two concurrent
1038           * requests for the same user/note/emoji can both insert an approved
1039           * row. Converge on a single row deterministically: keep the earliest
1040           * matching reaction (lowest comment ID) and delete any later
1041           * duplicates. Every concurrent request applies the same rule, so they
1042           * all settle on the same surviving row. If this request's own row lost
1043           * the race, repoint the response to the survivor.
1044           */
1045          if ( null !== $reaction_key ) {
1046              $matching   = get_comments(
1047                  array(
1048                      'post_id' => absint( $request['post'] ),
1049                      'parent'  => $request['parent'],
1050                      'user_id' => get_current_user_id(),
1051                      'type'    => 'reaction',
1052                      'status'  => 'approve',
1053                      'orderby' => 'comment_ID',
1054                      'order'   => 'ASC',
1055                  )
1056              );
1057              $duplicates = array();
1058              foreach ( $matching as $candidate ) {
1059                  if ( wp_strip_all_tags( $candidate->comment_content ) === $reaction_key ) {
1060                      $duplicates[] = (int) $candidate->comment_ID;
1061                  }
1062              }
1063  
1064              /*
1065               * Repoint whenever any matching row survives, not only when this
1066               * request still sees its own duplicate: a competing request may
1067               * already have deleted this request's row, leaving a single
1068               * survivor that is not `$comment_id`.
1069               */
1070              if ( ! empty( $duplicates ) ) {
1071                  $survivor_id = array_shift( $duplicates );
1072                  foreach ( $duplicates as $duplicate_id ) {
1073                      wp_delete_comment( $duplicate_id, true );
1074                  }
1075                  $comment_id = $survivor_id;
1076              }
1077          }
1078  
1079          /*
1080           * Reactions are inserted approved and their status was validated above.
1081           * Skipping them here also keeps a request from changing the status of a
1082           * row that the race cleanup above may have handed it from another request.
1083           */
1084          if ( isset( $request['status'] ) && null === $reaction_key ) {
1085              $this->handle_status_param( $request['status'], $comment_id );
1086          }
1087  
1088          $comment = get_comment( $comment_id );
1089  
1090          /**
1091           * Fires after a comment is created or updated via the REST API.
1092           *
1093           * @since 4.7.0
1094           *
1095           * @param WP_Comment      $comment  Inserted or updated comment object.
1096           * @param WP_REST_Request $request  Request object.
1097           * @param bool            $creating True when creating a comment, false
1098           *                                  when updating.
1099           */
1100          do_action( 'rest_insert_comment', $comment, $request, true );
1101  
1102          $schema = $this->get_item_schema();
1103  
1104          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
1105              $meta_update = $this->meta->update_value( $request['meta'], $comment_id );
1106  
1107              if ( is_wp_error( $meta_update ) ) {
1108                  return $meta_update;
1109              }
1110          }
1111  
1112          $fields_update = $this->update_additional_fields_for_object( $comment, $request );
1113  
1114          if ( is_wp_error( $fields_update ) ) {
1115              return $fields_update;
1116          }
1117  
1118          $context = current_user_can( 'moderate_comments' ) ? 'edit' : 'view';
1119          $request->set_param( 'context', $context );
1120  
1121          /**
1122           * Fires completely after a comment is created or updated via the REST API.
1123           *
1124           * @since 5.0.0
1125           *
1126           * @param WP_Comment      $comment  Inserted or updated comment object.
1127           * @param WP_REST_Request $request  Request object.
1128           * @param bool            $creating True when creating a comment, false
1129           *                                  when updating.
1130           */
1131          do_action( 'rest_after_insert_comment', $comment, $request, true );
1132  
1133          $response = $this->prepare_item_for_response( $comment, $request );
1134          $response = rest_ensure_response( $response );
1135  
1136          $response->set_status( 201 );
1137          $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment_id ) ) );
1138  
1139          return $response;
1140      }
1141  
1142      /**
1143       * Checks if a given REST request has access to update a comment.
1144       *
1145       * @since 4.7.0
1146       * @since 7.1.1 Target post permissions are checked when a comment's parent post is changed.
1147       * @since 7.2.0 Reactions cannot be updated.
1148       *
1149       * @param WP_REST_Request $request Full details about the request.
1150       * @return true|WP_Error True if the request has access to update the item, error object otherwise.
1151       */
1152  	public function update_item_permissions_check( $request ) {
1153          $comment = $this->get_comment( $request['id'] );
1154          if ( is_wp_error( $comment ) ) {
1155              return $comment;
1156          }
1157  
1158          /*
1159           * Reactions are immutable. create_item() validates the author, parent
1160           * note, target post and canonical emoji hex key as a set, and none of that
1161           * is re-checked here. Allowing an update would let anyone who can edit
1162           * the note's post reattribute a reaction to another user, move it to a
1163           * note on a post they cannot edit, or store a duplicate or invalid
1164           * key. Removing a reaction is a delete.
1165           */
1166          if ( 'reaction' === $comment->comment_type ) {
1167              return new WP_Error(
1168                  'rest_comment_update_not_allowed',
1169                  __( 'Reactions cannot be edited. Remove the reaction and add a new one instead.' ),
1170                  array( 'status' => 403 )
1171              );
1172          }
1173  
1174          if ( ! $this->check_edit_permission( $comment ) ) {
1175              return new WP_Error(
1176                  'rest_cannot_edit',
1177                  __( 'Sorry, you are not allowed to edit this comment.' ),
1178                  array( 'status' => rest_authorization_required_code() )
1179              );
1180          }
1181  
1182          /*
1183           * Reassigning a comment copies the new author's email address onto it,
1184           * which is then returned in the response.
1185           */
1186          if (
1187              isset( $request['author'] ) &&
1188              (int) $request['author'] !== (int) $comment->user_id &&
1189              get_current_user_id() !== (int) $request['author'] &&
1190              ! $this->check_assign_author_permission( $request['author'] )
1191          ) {
1192              return new WP_Error(
1193                  'rest_comment_invalid_author',
1194                  /* translators: %s: Request parameter. */
1195                  sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ),
1196                  array( 'status' => rest_authorization_required_code() )
1197              );
1198          }
1199  
1200          /*
1201           * check_edit_permission() above only establishes that the comment may be
1202           * edited where it currently sits, because 'edit_comment' maps to 'edit_post'
1203           * on the comment's current parent. When the parent is being changed, the new
1204           * parent has to be authorized as well. Without this, a user holding
1205           * edit_comment on their own comment or note could reparent it onto any post,
1206           * including posts they can neither read nor edit.
1207           */
1208          if ( isset( $request['post'] ) && (int) $request['post'] !== (int) $comment->comment_post_ID ) {
1209              $target_check = $this->check_target_post_permission(
1210                  (int) $request['post'],
1211                  $request,
1212                  'note' === $comment->comment_type
1213              );
1214  
1215              if ( is_wp_error( $target_check ) ) {
1216                  return $target_check;
1217              }
1218          }
1219  
1220          return true;
1221      }
1222  
1223      /**
1224       * Updates a comment.
1225       *
1226       * @since 4.7.0
1227       *
1228       * @param WP_REST_Request $request Full details about the request.
1229       * @return WP_REST_Response|WP_Error Response object on success, or error object on failure.
1230       */
1231  	public function update_item( $request ) {
1232          $comment = $this->get_comment( $request['id'] );
1233          if ( is_wp_error( $comment ) ) {
1234              return $comment;
1235          }
1236  
1237          $id = $comment->comment_ID;
1238  
1239          if ( isset( $request['type'] ) && get_comment_type( $id ) !== $request['type'] ) {
1240              return new WP_Error(
1241                  'rest_comment_invalid_type',
1242                  __( 'Sorry, you are not allowed to change the comment type.' ),
1243                  array( 'status' => 404 )
1244              );
1245          }
1246  
1247          if ( 'note' === $comment->comment_type ) {
1248              $post_id   = isset( $request['post'] ) ? absint( $request['post'] ) : (int) $comment->comment_post_ID;
1249              $parent_id = isset( $request['parent'] ) ? absint( $request['parent'] ) : (int) $comment->comment_parent;
1250              $is_moving = $post_id !== (int) $comment->comment_post_ID;
1251  
1252              if ( $parent_id && ( $is_moving || $parent_id !== (int) $comment->comment_parent ) ) {
1253                  $parent_check = $this->check_note_parent( $parent_id, $post_id );
1254  
1255                  if ( is_wp_error( $parent_check ) ) {
1256                      return $parent_check;
1257                  }
1258              }
1259  
1260              // Replies and reactions stay on the note's post, so a move would separate them.
1261              if ( $is_moving ) {
1262                  $children = get_comments(
1263                      array(
1264                          'parent' => $id,
1265                          'type'   => array( 'note', 'reaction' ),
1266                          'status' => 'any',
1267                          'count'  => true,
1268                      )
1269                  );
1270  
1271                  if ( $children ) {
1272                      return new WP_Error(
1273                          'rest_comment_has_children',
1274                          __( 'A note with replies or reactions cannot be moved to another post.' ),
1275                          array( 'status' => 400 )
1276                      );
1277                  }
1278              }
1279          }
1280  
1281          /*
1282           * Re-sending the current author is a no-op. Otherwise the author's details
1283           * would be refreshed from their user account, exposing any change to their
1284           * email address to whoever can edit the comment.
1285           */
1286          if ( isset( $request['author'] ) && (int) $request['author'] === (int) $comment->user_id ) {
1287              unset( $request['author'] );
1288          }
1289  
1290          $prepared_args = $this->prepare_item_for_database( $request );
1291  
1292          if ( is_wp_error( $prepared_args ) ) {
1293              return $prepared_args;
1294          }
1295  
1296          if ( ! empty( $prepared_args['comment_post_ID'] ) ) {
1297              $post = get_post( $prepared_args['comment_post_ID'] );
1298  
1299              if ( empty( $post ) ) {
1300                  return new WP_Error(
1301                      'rest_comment_invalid_post_id',
1302                      __( 'Invalid post ID.' ),
1303                      array( 'status' => 403 )
1304                  );
1305              }
1306          }
1307  
1308          if ( empty( $prepared_args ) && isset( $request['status'] ) ) {
1309              // Only the comment status is being changed.
1310              $change = $this->handle_status_param( $request['status'], $id );
1311  
1312              if ( ! $change ) {
1313                  return new WP_Error(
1314                      'rest_comment_failed_edit',
1315                      __( 'Updating comment status failed.' ),
1316                      array( 'status' => 500 )
1317                  );
1318              }
1319          } elseif ( ! empty( $prepared_args ) ) {
1320              if ( is_wp_error( $prepared_args ) ) {
1321                  return $prepared_args;
1322              }
1323              if ( ! $this->check_is_comment_content_allowed( $prepared_args ) ) {
1324                  return new WP_Error(
1325                      'rest_comment_content_invalid',
1326                      __( 'Invalid comment content.' ),
1327                      array( 'status' => 400 )
1328                  );
1329              }
1330  
1331              $prepared_args['comment_ID'] = $id;
1332  
1333              $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args );
1334  
1335              if ( is_wp_error( $check_comment_lengths ) ) {
1336                  $error_code = $check_comment_lengths->get_error_code();
1337                  return new WP_Error(
1338                      $error_code,
1339                      __( 'Comment field exceeds maximum length allowed.' ),
1340                      array( 'status' => 400 )
1341                  );
1342              }
1343  
1344              $updated = wp_update_comment( wp_slash( (array) $prepared_args ), true );
1345  
1346              if ( is_wp_error( $updated ) ) {
1347                  return new WP_Error(
1348                      'rest_comment_failed_edit',
1349                      __( 'Updating comment failed.' ),
1350                      array( 'status' => 500 )
1351                  );
1352              }
1353  
1354              if ( isset( $request['status'] ) ) {
1355                  $this->handle_status_param( $request['status'], $id );
1356              }
1357          }
1358  
1359          $comment = get_comment( $id );
1360  
1361          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */
1362          do_action( 'rest_insert_comment', $comment, $request, false );
1363  
1364          $schema = $this->get_item_schema();
1365  
1366          if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
1367              $meta_update = $this->meta->update_value( $request['meta'], $id );
1368  
1369              if ( is_wp_error( $meta_update ) ) {
1370                  return $meta_update;
1371              }
1372          }
1373  
1374          $fields_update = $this->update_additional_fields_for_object( $comment, $request );
1375  
1376          if ( is_wp_error( $fields_update ) ) {
1377              return $fields_update;
1378          }
1379  
1380          $request->set_param( 'context', 'edit' );
1381  
1382          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */
1383          do_action( 'rest_after_insert_comment', $comment, $request, false );
1384  
1385          $response = $this->prepare_item_for_response( $comment, $request );
1386  
1387          return rest_ensure_response( $response );
1388      }
1389  
1390      /**
1391       * Checks if a given request has access to delete a comment.
1392       *
1393       * @since 4.7.0
1394       *
1395       * @param WP_REST_Request $request Full details about the request.
1396       * @return true|WP_Error True if the request has access to delete the item, error object otherwise.
1397       */
1398  	public function delete_item_permissions_check( $request ) {
1399          $comment = $this->get_comment( $request['id'] );
1400          if ( is_wp_error( $comment ) ) {
1401              return $comment;
1402          }
1403  
1404          if ( ! $this->check_edit_permission( $comment ) ) {
1405              return new WP_Error(
1406                  'rest_cannot_delete',
1407                  __( 'Sorry, you are not allowed to delete this comment.' ),
1408                  array( 'status' => rest_authorization_required_code() )
1409              );
1410          }
1411  
1412          if ( 'reaction' === strtolower( $comment->comment_type ) ) {
1413              // A reaction speaks for its author, so only they can remove it.
1414              if ( get_current_user_id() !== (int) $comment->user_id ) {
1415                  return new WP_Error(
1416                      'rest_cannot_delete',
1417                      __( 'Sorry, you can only remove your own reactions.' ),
1418                      array( 'status' => rest_authorization_required_code() )
1419                  );
1420              }
1421  
1422              // Reactions on a resolved thread are frozen, like adding new ones.
1423              $note = get_comment( $comment->comment_parent );
1424              if ( $note instanceof WP_Comment && $this->is_thread_resolved( $note ) ) {
1425                  return new WP_Error(
1426                      'rest_cannot_delete',
1427                      __( 'A reaction cannot be removed from a resolved note.' ),
1428                      array( 'status' => 403 )
1429                  );
1430              }
1431          }
1432  
1433          return true;
1434      }
1435  
1436      /**
1437       * Deletes a comment.
1438       *
1439       * @since 4.7.0
1440       *
1441       * @param WP_REST_Request $request Full details about the request.
1442       * @return WP_REST_Response|WP_Error Response object on success, or error object on failure.
1443       */
1444  	public function delete_item( $request ) {
1445          $comment = $this->get_comment( $request['id'] );
1446          if ( is_wp_error( $comment ) ) {
1447              return $comment;
1448          }
1449  
1450          $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
1451  
1452          /**
1453           * Filters whether a comment can be trashed via the REST API.
1454           *
1455           * Return false to disable trash support for the comment.
1456           *
1457           * @since 4.7.0
1458           *
1459           * @param bool       $supports_trash Whether the comment supports trashing.
1460           * @param WP_Comment $comment        The comment object being considered for trashing support.
1461           */
1462          $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );
1463  
1464          $request->set_param( 'context', 'edit' );
1465  
1466          if ( $force ) {
1467              $previous = $this->prepare_item_for_response( $comment, $request );
1468              $result   = wp_delete_comment( $comment->comment_ID, true );
1469              $response = new WP_REST_Response();
1470              $response->set_data(
1471                  array(
1472                      'deleted'  => true,
1473                      'previous' => $previous->get_data(),
1474                  )
1475              );
1476          } else {
1477              // If this type doesn't support trashing, error out.
1478              if ( ! $supports_trash ) {
1479                  return new WP_Error(
1480                      'rest_trash_not_supported',
1481                      /* translators: %s: force=true */
1482                      sprintf( __( "The comment does not support trashing. Set '%s' to delete." ), 'force=true' ),
1483                      array( 'status' => 501 )
1484                  );
1485              }
1486  
1487              if ( 'trash' === $comment->comment_approved ) {
1488                  return new WP_Error(
1489                      'rest_already_trashed',
1490                      __( 'The comment has already been trashed.' ),
1491                      array( 'status' => 410 )
1492                  );
1493              }
1494  
1495              $result   = wp_trash_comment( $comment->comment_ID );
1496              $comment  = get_comment( $comment->comment_ID );
1497              $response = $this->prepare_item_for_response( $comment, $request );
1498          }
1499  
1500          if ( ! $result ) {
1501              return new WP_Error(
1502                  'rest_cannot_delete',
1503                  __( 'The comment cannot be deleted.' ),
1504                  array( 'status' => 500 )
1505              );
1506          }
1507  
1508          /**
1509           * Fires after a comment is deleted via the REST API.
1510           *
1511           * @since 4.7.0
1512           *
1513           * @param WP_Comment       $comment  The deleted comment data.
1514           * @param WP_REST_Response $response The response returned from the API.
1515           * @param WP_REST_Request  $request  The request sent to the API.
1516           */
1517          do_action( 'rest_delete_comment', $comment, $response, $request );
1518  
1519          return $response;
1520      }
1521  
1522      /**
1523       * Prepares a single comment output for response.
1524       *
1525       * @since 4.7.0
1526       * @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support.
1527       *
1528       * @param WP_Comment      $item    Comment object.
1529       * @param WP_REST_Request $request Request object.
1530       * @return WP_REST_Response Response object.
1531       */
1532  	public function prepare_item_for_response( $item, $request ) {
1533          // Restores the more descriptive, specific name for use within this method.
1534          $comment = $item;
1535  
1536          // Don't prepare the response body for HEAD requests.
1537          if ( $request->is_method( 'HEAD' ) ) {
1538              /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */
1539              return apply_filters( 'rest_prepare_comment', new WP_REST_Response( array() ), $comment, $request );
1540          }
1541  
1542          $fields = $this->get_fields_for_response( $request );
1543          $data   = array();
1544  
1545          if ( in_array( 'id', $fields, true ) ) {
1546              $data['id'] = (int) $comment->comment_ID;
1547          }
1548  
1549          if ( in_array( 'post', $fields, true ) ) {
1550              $data['post'] = (int) $comment->comment_post_ID;
1551          }
1552  
1553          if ( in_array( 'parent', $fields, true ) ) {
1554              $data['parent'] = (int) $comment->comment_parent;
1555          }
1556  
1557          if ( in_array( 'author', $fields, true ) ) {
1558              $data['author'] = (int) $comment->user_id;
1559          }
1560  
1561          if ( in_array( 'author_name', $fields, true ) ) {
1562              $data['author_name'] = $comment->comment_author;
1563          }
1564  
1565          if ( in_array( 'author_email', $fields, true ) ) {
1566              $data['author_email'] = $comment->comment_author_email;
1567          }
1568  
1569          if ( in_array( 'author_url', $fields, true ) ) {
1570              $data['author_url'] = $comment->comment_author_url;
1571          }
1572  
1573          if ( in_array( 'author_ip', $fields, true ) ) {
1574              $data['author_ip'] = $comment->comment_author_IP;
1575          }
1576  
1577          if ( in_array( 'author_user_agent', $fields, true ) ) {
1578              $data['author_user_agent'] = $comment->comment_agent;
1579          }
1580  
1581          if ( in_array( 'date', $fields, true ) ) {
1582              $data['date'] = mysql_to_rfc3339( $comment->comment_date );
1583          }
1584  
1585          if ( in_array( 'date_gmt', $fields, true ) ) {
1586              $data['date_gmt'] = mysql_to_rfc3339( $comment->comment_date_gmt );
1587          }
1588  
1589          if ( in_array( 'content', $fields, true ) ) {
1590              $data['content'] = array(
1591                  /** This filter is documented in wp-includes/comment-template.php */
1592                  'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment, array() ),
1593                  'raw'      => $comment->comment_content,
1594              );
1595          }
1596  
1597          if ( in_array( 'link', $fields, true ) ) {
1598              $data['link'] = get_comment_link( $comment );
1599          }
1600  
1601          if ( in_array( 'status', $fields, true ) ) {
1602              $data['status'] = $this->prepare_status_response( $comment->comment_approved );
1603          }
1604  
1605          if ( in_array( 'type', $fields, true ) ) {
1606              $data['type'] = get_comment_type( $comment->comment_ID );
1607          }
1608  
1609          if ( in_array( 'author_avatar_urls', $fields, true ) ) {
1610              $data['author_avatar_urls'] = rest_get_avatar_urls( $comment );
1611          }
1612  
1613          if ( in_array( 'meta', $fields, true ) ) {
1614              $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
1615          }
1616  
1617          if ( in_array( 'reaction_summary', $fields, true ) && 'note' === $comment->comment_type ) {
1618              $note_id = (int) $comment->comment_ID;
1619  
1620              if ( null !== $this->reaction_summaries && isset( $this->reaction_summaries[ $note_id ] ) ) {
1621                  $data['reaction_summary'] = $this->reaction_summaries[ $note_id ];
1622              } else {
1623                  // Single-item path (get_item or single create/update): query individually.
1624                  $this->prefetch_reaction_summaries( array( $note_id ) );
1625                  $data['reaction_summary'] = $this->reaction_summaries[ $note_id ] ?? array();
1626                  // Reset so subsequent unrelated calls do not see this entry.
1627                  $this->reaction_summaries = null;
1628              }
1629          }
1630  
1631          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1632          $data    = $this->add_additional_fields_to_object( $data, $request );
1633          $data    = $this->filter_response_by_context( $data, $context );
1634  
1635          // Wrap the data in a response object.
1636          $response = rest_ensure_response( $data );
1637  
1638          if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
1639              $links = $this->prepare_links( $comment );
1640              $response->add_links( $links );
1641  
1642              if ( ! empty( $links['self']['href'] ) ) {
1643                  $actions = $this->get_available_actions( $comment, $request );
1644  
1645                  $self = $links['self']['href'];
1646  
1647                  foreach ( $actions as $rel ) {
1648                      $response->add_link( $rel, $self );
1649                  }
1650              }
1651          }
1652  
1653          /**
1654           * Filters a comment returned from the REST API.
1655           *
1656           * Allows modification of the comment right before it is returned.
1657           *
1658           * @since 4.7.0
1659           *
1660           * @param WP_REST_Response  $response The response object.
1661           * @param WP_Comment        $comment  The original comment object.
1662           * @param WP_REST_Request   $request  Request used to generate the response.
1663           */
1664          return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
1665      }
1666  
1667      /**
1668       * Prepares links for the request.
1669       *
1670       * @since 4.7.0
1671       *
1672       * @param WP_Comment $comment Comment object.
1673       * @return array Links for the given comment.
1674       */
1675  	protected function prepare_links( $comment ) {
1676          $links = array(
1677              'self'       => array(
1678                  'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ),
1679              ),
1680              'collection' => array(
1681                  'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
1682              ),
1683          );
1684  
1685          if ( 0 !== (int) $comment->user_id ) {
1686              $links['author'] = array(
1687                  'href'       => rest_url( 'wp/v2/users/' . $comment->user_id ),
1688                  'embeddable' => true,
1689              );
1690          }
1691  
1692          if ( 0 !== (int) $comment->comment_post_ID ) {
1693              $post       = get_post( $comment->comment_post_ID );
1694              $post_route = rest_get_route_for_post( $post );
1695  
1696              if ( ! empty( $post->ID ) && $post_route ) {
1697                  $links['up'] = array(
1698                      'href'       => rest_url( $post_route ),
1699                      'embeddable' => true,
1700                      'post_type'  => $post->post_type,
1701                  );
1702              }
1703          }
1704  
1705          if ( 0 !== (int) $comment->comment_parent ) {
1706              $links['in-reply-to'] = array(
1707                  'href'       => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ),
1708                  'embeddable' => true,
1709              );
1710          }
1711  
1712          /*
1713           * Only grab one comment to verify the comment has children. Reactions are
1714           * left out: they are summarized in `reaction_summary`, and counting them
1715           * would advertise a `children` link on a note that has no replies.
1716           */
1717          $comment_children = $comment->get_children(
1718              array(
1719                  'count'        => true,
1720                  'orderby'      => 'none',
1721                  'type'         => 'all',
1722                  'type__not_in' => array( 'reaction' ),
1723              )
1724          );
1725  
1726          if ( ! empty( $comment_children ) ) {
1727              $args = array(
1728                  'parent' => $comment->comment_ID,
1729              );
1730  
1731              $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
1732  
1733              $links['children'] = array(
1734                  'href'       => $rest_url,
1735                  'embeddable' => true,
1736              );
1737          }
1738  
1739          // Embedding children for notes requires `type` and `status` inheritance.
1740          if ( isset( $links['children'] ) && 'note' === $comment->comment_type ) {
1741              $args = array(
1742                  'parent' => $comment->comment_ID,
1743                  'type'   => $comment->comment_type,
1744                  'status' => 'all',
1745              );
1746  
1747              $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
1748  
1749              $links['children'] = array(
1750                  'href'       => $rest_url,
1751                  'embeddable' => true,
1752              );
1753          }
1754  
1755          return $links;
1756      }
1757  
1758      /**
1759       * Gets the link relations available for the comment and current user.
1760       *
1761       * @since 7.2.0
1762       *
1763       * @param WP_Comment      $comment Comment object.
1764       * @param WP_REST_Request $request Request object.
1765       * @return string[] List of link relations.
1766       *
1767       * @phpstan-return array<non-falsy-string>
1768       */
1769  	protected function get_available_actions( $comment, $request ) {
1770          if ( 'edit' !== $request['context'] ) {
1771              return array();
1772          }
1773  
1774          $rels = array();
1775  
1776          if ( 'trash' !== $comment->comment_approved && $this->check_edit_permission( $comment ) ) {
1777              /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */
1778              if ( apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment ) ) {
1779                  $rels[] = 'https://api.w.org/action-trash';
1780              }
1781          }
1782  
1783          return $rels;
1784      }
1785  
1786      /**
1787       * Prepends internal property prefix to query parameters to match our response fields.
1788       *
1789       * @since 4.7.0
1790       *
1791       * @param string $query_param Query parameter.
1792       * @return string The normalized query parameter.
1793       */
1794  	protected function normalize_query_param( $query_param ) {
1795          $prefix = 'comment_';
1796  
1797          switch ( $query_param ) {
1798              case 'id':
1799                  $normalized = $prefix . 'ID';
1800                  break;
1801              case 'post':
1802                  $normalized = $prefix . 'post_ID';
1803                  break;
1804              case 'parent':
1805                  $normalized = $prefix . 'parent';
1806                  break;
1807              case 'include':
1808                  $normalized = 'comment__in';
1809                  break;
1810              default:
1811                  $normalized = $prefix . $query_param;
1812                  break;
1813          }
1814  
1815          return $normalized;
1816      }
1817  
1818      /**
1819       * Checks comment_approved to set comment status for single comment output.
1820       *
1821       * @since 4.7.0
1822       *
1823       * @param string $comment_approved Comment status.
1824       * @return string Comment status.
1825       */
1826  	protected function prepare_status_response( $comment_approved ) {
1827  
1828          switch ( $comment_approved ) {
1829              case 'hold':
1830              case '0':
1831                  $status = 'hold';
1832                  break;
1833  
1834              case 'approve':
1835              case '1':
1836                  $status = 'approved';
1837                  break;
1838  
1839              case 'spam':
1840              case 'trash':
1841              default:
1842                  $status = $comment_approved;
1843                  break;
1844          }
1845  
1846          return $status;
1847      }
1848  
1849      /**
1850       * Prepares a single comment to be inserted into the database.
1851       *
1852       * @since 4.7.0
1853       *
1854       * @param WP_REST_Request $request Request object.
1855       * @return array|WP_Error Prepared comment, otherwise WP_Error object.
1856       */
1857  	protected function prepare_item_for_database( $request ) {
1858          $prepared_comment = array();
1859  
1860          /*
1861           * Allow the comment_content to be set via the 'content' or
1862           * the 'content.raw' properties of the Request object.
1863           */
1864          if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
1865              $prepared_comment['comment_content'] = trim( $request['content'] );
1866          } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
1867              $prepared_comment['comment_content'] = trim( $request['content']['raw'] );
1868          }
1869  
1870          if ( isset( $request['post'] ) ) {
1871              $prepared_comment['comment_post_ID'] = (int) $request['post'];
1872          }
1873  
1874          if ( isset( $request['parent'] ) ) {
1875              $prepared_comment['comment_parent'] = $request['parent'];
1876          }
1877  
1878          if ( isset( $request['author'] ) ) {
1879              $user = new WP_User( $request['author'] );
1880  
1881              if ( $user->exists() ) {
1882                  $prepared_comment['user_id']              = $user->ID;
1883                  $prepared_comment['comment_author']       = $user->display_name;
1884                  $prepared_comment['comment_author_email'] = $user->user_email;
1885                  $prepared_comment['comment_author_url']   = $user->user_url;
1886              } else {
1887                  return new WP_Error(
1888                      'rest_comment_author_invalid',
1889                      __( 'Invalid comment author ID.' ),
1890                      array( 'status' => 400 )
1891                  );
1892              }
1893          }
1894  
1895          if ( isset( $request['author_name'] ) ) {
1896              $prepared_comment['comment_author'] = $request['author_name'];
1897          }
1898  
1899          if ( isset( $request['author_email'] ) ) {
1900              $prepared_comment['comment_author_email'] = $request['author_email'];
1901          }
1902  
1903          if ( isset( $request['author_url'] ) ) {
1904              $prepared_comment['comment_author_url'] = $request['author_url'];
1905          }
1906  
1907          if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) {
1908              $prepared_comment['comment_author_IP'] = $request['author_ip'];
1909          } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) {
1910              $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1911          } else {
1912              $prepared_comment['comment_author_IP'] = '127.0.0.1';
1913          }
1914  
1915          if ( ! empty( $request['author_user_agent'] ) ) {
1916              $prepared_comment['comment_agent'] = $request['author_user_agent'];
1917          } elseif ( $request->get_header( 'user_agent' ) ) {
1918              $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' );
1919          }
1920  
1921          if ( ! empty( $request['date'] ) ) {
1922              $date_data = rest_get_date_with_gmt( $request['date'] );
1923  
1924              if ( ! empty( $date_data ) ) {
1925                  list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1926              }
1927          } elseif ( ! empty( $request['date_gmt'] ) ) {
1928              $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
1929  
1930              if ( ! empty( $date_data ) ) {
1931                  list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1932              }
1933          }
1934  
1935          /**
1936           * Filters a comment added via the REST API after it is prepared for insertion into the database.
1937           *
1938           * Allows modification of the comment right after it is prepared for the database.
1939           *
1940           * @since 4.7.0
1941           *
1942           * @param array           $prepared_comment The prepared comment data for `wp_insert_comment`.
1943           * @param WP_REST_Request $request          The current request.
1944           */
1945          return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request );
1946      }
1947  
1948      /**
1949       * Retrieves the comment's schema, conforming to JSON Schema.
1950       *
1951       * @since 4.7.0
1952       *
1953       * @return array
1954       */
1955  	public function get_item_schema() {
1956          if ( $this->schema ) {
1957              return $this->add_additional_fields_schema( $this->schema );
1958          }
1959  
1960          $schema = array(
1961              '$schema'    => 'http://json-schema.org/draft-04/schema#',
1962              'title'      => 'comment',
1963              'type'       => 'object',
1964              'properties' => array(
1965                  'id'                => array(
1966                      'description' => __( 'Unique identifier for the comment.' ),
1967                      'type'        => 'integer',
1968                      'context'     => array( 'view', 'edit', 'embed' ),
1969                      'readonly'    => true,
1970                  ),
1971                  'author'            => array(
1972                      'description' => __( 'The ID of the user object, if author was a user.' ),
1973                      'type'        => 'integer',
1974                      'context'     => array( 'view', 'edit', 'embed' ),
1975                  ),
1976                  'author_email'      => array(
1977                      'description' => __( 'Email address for the comment author.' ),
1978                      'type'        => 'string',
1979                      'format'      => 'email',
1980                      'context'     => array( 'edit' ),
1981                      'arg_options' => array(
1982                          'sanitize_callback' => array( $this, 'check_comment_author_email' ),
1983                          'validate_callback' => null, // Skip built-in validation of 'email'.
1984                      ),
1985                  ),
1986                  'author_ip'         => array(
1987                      'description' => __( 'IP address for the comment author.' ),
1988                      'type'        => 'string',
1989                      'format'      => 'ip',
1990                      'context'     => array( 'edit' ),
1991                  ),
1992                  'author_name'       => array(
1993                      'description' => __( 'Display name for the comment author.' ),
1994                      'type'        => 'string',
1995                      'context'     => array( 'view', 'edit', 'embed' ),
1996                      'arg_options' => array(
1997                          'sanitize_callback' => 'sanitize_text_field',
1998                      ),
1999                  ),
2000                  'author_url'        => array(
2001                      'description' => __( 'URL for the comment author.' ),
2002                      'type'        => 'string',
2003                      'format'      => 'uri',
2004                      'context'     => array( 'view', 'edit', 'embed' ),
2005                  ),
2006                  'author_user_agent' => array(
2007                      'description' => __( 'User agent for the comment author.' ),
2008                      'type'        => 'string',
2009                      'context'     => array( 'edit' ),
2010                      'arg_options' => array(
2011                          'sanitize_callback' => 'sanitize_text_field',
2012                      ),
2013                  ),
2014                  'content'           => array(
2015                      'description' => __( 'The content for the comment.' ),
2016                      'type'        => 'object',
2017                      'context'     => array( 'view', 'edit', 'embed' ),
2018                      'arg_options' => array(
2019                          'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database().
2020                          'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database().
2021                      ),
2022                      'properties'  => array(
2023                          'raw'      => array(
2024                              'description' => __( 'Content for the comment, as it exists in the database.' ),
2025                              'type'        => 'string',
2026                              'context'     => array( 'edit' ),
2027                          ),
2028                          'rendered' => array(
2029                              'description' => __( 'HTML content for the comment, transformed for display.' ),
2030                              'type'        => 'string',
2031                              'context'     => array( 'view', 'edit', 'embed' ),
2032                              'readonly'    => true,
2033                          ),
2034                      ),
2035                  ),
2036                  'date'              => array(
2037                      'description' => __( "The date the comment was published, in the site's timezone." ),
2038                      'type'        => 'string',
2039                      'format'      => 'date-time',
2040                      'context'     => array( 'view', 'edit', 'embed' ),
2041                  ),
2042                  'date_gmt'          => array(
2043                      'description' => __( 'The date the comment was published, as GMT.' ),
2044                      'type'        => 'string',
2045                      'format'      => 'date-time',
2046                      'context'     => array( 'view', 'edit' ),
2047                  ),
2048                  'link'              => array(
2049                      'description' => __( 'URL to the comment.' ),
2050                      'type'        => 'string',
2051                      'format'      => 'uri',
2052                      'context'     => array( 'view', 'edit', 'embed' ),
2053                      'readonly'    => true,
2054                  ),
2055                  'parent'            => array(
2056                      'description' => __( 'The ID for the parent of the comment.' ),
2057                      'type'        => 'integer',
2058                      'minimum'     => 0,
2059                      'context'     => array( 'view', 'edit', 'embed' ),
2060                      'default'     => 0,
2061                  ),
2062                  'post'              => array(
2063                      'description' => __( 'The ID of the associated post object.' ),
2064                      'type'        => 'integer',
2065                      'minimum'     => 0,
2066                      'context'     => array( 'view', 'edit' ),
2067                      'default'     => 0,
2068                  ),
2069                  'status'            => array(
2070                      'description' => __( 'State of the comment.' ),
2071                      'type'        => 'string',
2072                      'context'     => array( 'view', 'edit' ),
2073                      'arg_options' => array(
2074                          'sanitize_callback' => 'sanitize_key',
2075                      ),
2076                  ),
2077                  'type'              => array(
2078                      'description' => __( 'Type of the comment.' ),
2079                      'type'        => 'string',
2080                      'context'     => array( 'view', 'edit', 'embed' ),
2081                      'readonly'    => true,
2082                      'default'     => 'comment',
2083                  ),
2084                  'reaction_summary'  => array(
2085                      'description'          => __( 'Aggregated reaction counts for this note, keyed by emoji hex key.' ),
2086                      'type'                 => 'object',
2087                      'context'              => array( 'view', 'edit' ),
2088                      'readonly'             => true,
2089                      'additionalProperties' => array(
2090                          'type'       => 'object',
2091                          'properties' => array(
2092                              'count'                 => array(
2093                                  'description' => __( 'Total number of reactions with this emoji.' ),
2094                                  'type'        => 'integer',
2095                                  'minimum'     => 0,
2096                              ),
2097                              'current_user_reaction' => array(
2098                                  'description' => __( "The current user's reaction comment ID for this emoji, or 0 if they have not reacted." ),
2099                                  'type'        => 'integer',
2100                                  'minimum'     => 0,
2101                              ),
2102                          ),
2103                      ),
2104                  ),
2105              ),
2106          );
2107  
2108          if ( get_option( 'show_avatars' ) ) {
2109              $avatar_properties = array();
2110  
2111              $avatar_sizes = rest_get_avatar_sizes();
2112  
2113              foreach ( $avatar_sizes as $size ) {
2114                  $avatar_properties[ $size ] = array(
2115                      /* translators: %d: Avatar image size in pixels. */
2116                      'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
2117                      'type'        => 'string',
2118                      'format'      => 'uri',
2119                      'context'     => array( 'embed', 'view', 'edit' ),
2120                  );
2121              }
2122  
2123              $schema['properties']['author_avatar_urls'] = array(
2124                  'description' => __( 'Avatar URLs for the comment author.' ),
2125                  'type'        => 'object',
2126                  'context'     => array( 'view', 'edit', 'embed' ),
2127                  'readonly'    => true,
2128                  'properties'  => $avatar_properties,
2129              );
2130          }
2131  
2132          $schema['properties']['meta'] = $this->meta->get_field_schema();
2133  
2134          $this->schema = $schema;
2135  
2136          return $this->add_additional_fields_schema( $this->schema );
2137      }
2138  
2139      /**
2140       * Retrieves the query params for collections.
2141       *
2142       * @since 4.7.0
2143       *
2144       * @return array Comments collection parameters.
2145       */
2146  	public function get_collection_params() {
2147          $query_params = parent::get_collection_params();
2148  
2149          $query_params['context']['default'] = 'view';
2150  
2151          $query_params['after'] = array(
2152              'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ),
2153              'type'        => 'string',
2154              'format'      => 'date-time',
2155          );
2156  
2157          $query_params['author'] = array(
2158              'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ),
2159              'type'        => 'array',
2160              'items'       => array(
2161                  'type' => 'integer',
2162              ),
2163          );
2164  
2165          $query_params['author_exclude'] = array(
2166              'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ),
2167              'type'        => 'array',
2168              'items'       => array(
2169                  'type' => 'integer',
2170              ),
2171          );
2172  
2173          $query_params['author_email'] = array(
2174              'default'     => null,
2175              'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ),
2176              'format'      => 'email',
2177              'type'        => 'string',
2178          );
2179  
2180          $query_params['before'] = array(
2181              'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ),
2182              'type'        => 'string',
2183              'format'      => 'date-time',
2184          );
2185  
2186          $query_params['exclude'] = array(
2187              'description' => __( 'Ensure result set excludes specific IDs.' ),
2188              'type'        => 'array',
2189              'items'       => array(
2190                  'type' => 'integer',
2191              ),
2192              'default'     => array(),
2193          );
2194  
2195          $query_params['include'] = array(
2196              'description' => __( 'Limit result set to specific IDs.' ),
2197              'type'        => 'array',
2198              'items'       => array(
2199                  'type' => 'integer',
2200              ),
2201              'default'     => array(),
2202          );
2203  
2204          $query_params['offset'] = array(
2205              'description' => __( 'Offset the result set by a specific number of items.' ),
2206              'type'        => 'integer',
2207          );
2208  
2209          $query_params['order'] = array(
2210              'description' => __( 'Order sort attribute ascending or descending.' ),
2211              'type'        => 'string',
2212              'default'     => 'desc',
2213              'enum'        => array(
2214                  'asc',
2215                  'desc',
2216              ),
2217          );
2218  
2219          $query_params['orderby'] = array(
2220              'description' => __( 'Sort collection by comment attribute.' ),
2221              'type'        => 'string',
2222              'default'     => 'date_gmt',
2223              'enum'        => array(
2224                  'date',
2225                  'date_gmt',
2226                  'id',
2227                  'include',
2228                  'post',
2229                  'parent',
2230                  'type',
2231              ),
2232          );
2233  
2234          $query_params['parent'] = array(
2235              'default'     => array(),
2236              'description' => __( 'Limit result set to comments of specific parent IDs.' ),
2237              'type'        => 'array',
2238              'items'       => array(
2239                  'type'    => 'integer',
2240                  'minimum' => 0,
2241              ),
2242          );
2243  
2244          $query_params['parent_exclude'] = array(
2245              'default'     => array(),
2246              'description' => __( 'Ensure result set excludes specific parent IDs.' ),
2247              'type'        => 'array',
2248              'items'       => array(
2249                  'type' => 'integer',
2250              ),
2251          );
2252  
2253          $query_params['post'] = array(
2254              'default'     => array(),
2255              'description' => __( 'Limit result set to comments assigned to specific post IDs.' ),
2256              'type'        => 'array',
2257              'items'       => array(
2258                  'type' => 'integer',
2259              ),
2260          );
2261  
2262          $query_params['status'] = array(
2263              'default'           => array( 'approve' ),
2264              'description'       => __( 'Limit result set to comments assigned one or more statuses. Requires authorization.' ),
2265              'type'              => 'array',
2266              'items'             => array(
2267                  'type' => 'string',
2268              ),
2269              'sanitize_callback' => array( $this, 'sanitize_comment_statuses' ),
2270              'validate_callback' => 'rest_validate_request_arg',
2271          );
2272  
2273          $query_params['type'] = array(
2274              'default'           => 'comment',
2275              'description'       => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ),
2276              'sanitize_callback' => 'sanitize_key',
2277              'type'              => 'string',
2278              'validate_callback' => 'rest_validate_request_arg',
2279          );
2280  
2281          $query_params['password'] = array(
2282              'description' => __( 'The password for the post if it is password protected.' ),
2283              'type'        => 'string',
2284          );
2285  
2286          /**
2287           * Filters REST API collection parameters for the comments controller.
2288           *
2289           * This filter registers the collection parameter, but does not map the
2290           * collection parameter to an internal WP_Comment_Query parameter. Use the
2291           * `rest_comment_query` filter to set WP_Comment_Query parameters.
2292           *
2293           * @since 4.7.0
2294           *
2295           * @param array $query_params JSON Schema-formatted collection parameters.
2296           */
2297          return apply_filters( 'rest_comment_collection_params', $query_params );
2298      }
2299  
2300      /**
2301       * Sets the comment_status of a given comment object when creating or updating a comment.
2302       *
2303       * @since 4.7.0
2304       *
2305       * @param string|int $new_status New comment status.
2306       * @param int        $comment_id Comment ID.
2307       * @return bool Whether the status was changed.
2308       */
2309  	protected function handle_status_param( $new_status, $comment_id ) {
2310          $old_status = wp_get_comment_status( $comment_id );
2311  
2312          if ( $new_status === $old_status ) {
2313              return false;
2314          }
2315  
2316          switch ( $new_status ) {
2317              case 'approved':
2318              case 'approve':
2319              case '1':
2320                  $changed = wp_set_comment_status( $comment_id, 'approve' );
2321                  break;
2322              case 'hold':
2323              case '0':
2324                  $changed = wp_set_comment_status( $comment_id, 'hold' );
2325                  break;
2326              case 'spam':
2327                  $changed = wp_spam_comment( $comment_id );
2328                  break;
2329              case 'unspam':
2330                  $changed = wp_unspam_comment( $comment_id );
2331                  break;
2332              case 'trash':
2333                  $changed = wp_trash_comment( $comment_id );
2334                  break;
2335              case 'untrash':
2336                  $changed = wp_untrash_comment( $comment_id );
2337                  break;
2338              default:
2339                  $changed = false;
2340                  break;
2341          }
2342  
2343          return $changed;
2344      }
2345  
2346      /**
2347       * Checks if the post can be read.
2348       *
2349       * Correctly handles posts with the inherit status.
2350       *
2351       * @since 4.7.0
2352       *
2353       * @param WP_Post         $post    Post object.
2354       * @param WP_REST_Request $request Request data to check.
2355       * @return bool Whether post can be read.
2356       */
2357  	protected function check_read_post_permission( $post, $request ) {
2358          $post_type = get_post_type_object( $post->post_type );
2359  
2360          // Return false if custom post type doesn't exist
2361          if ( ! $post_type ) {
2362              return false;
2363          }
2364  
2365          $posts_controller = $post_type->get_rest_controller();
2366  
2367          /*
2368           * Ensure the posts controller is specifically a WP_REST_Posts_Controller instance
2369           * before using methods specific to that controller.
2370           */
2371          if ( ! $posts_controller instanceof WP_REST_Posts_Controller ) {
2372              $posts_controller = new WP_REST_Posts_Controller( $post->post_type );
2373          }
2374  
2375          $has_password_filter = false;
2376  
2377          // Only check password if a specific post was queried for or a single comment
2378          $requested_post    = ! empty( $request['post'] ) && ( ! is_array( $request['post'] ) || 1 === count( $request['post'] ) );
2379          $requested_comment = ! empty( $request['id'] );
2380          if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) {
2381              add_filter( 'post_password_required', '__return_false' );
2382  
2383              $has_password_filter = true;
2384          }
2385  
2386          if ( post_password_required( $post ) ) {
2387              $result = current_user_can( 'edit_post', $post->ID );
2388          } else {
2389              $result = $posts_controller->check_read_permission( $post );
2390          }
2391  
2392          if ( $has_password_filter ) {
2393              remove_filter( 'post_password_required', '__return_false' );
2394          }
2395  
2396          return $result;
2397      }
2398  
2399      /**
2400       * Pre-fetches reaction summaries for a set of note IDs.
2401       *
2402       * Runs two aggregated queries (one for the per-emoji counts, one for the
2403       * current user's own reactions) and stores the result in
2404       * $this->reaction_summaries, keyed by note comment ID. This lets a
2405       * batched note listing return reaction_summary for many notes without
2406       * issuing a per-note query.
2407       *
2408       * @since 7.2.0
2409       *
2410       * @global wpdb $wpdb WordPress database abstraction object.
2411       *
2412       * @param int[] $note_ids Array of note comment IDs.
2413       */
2414  	protected function prefetch_reaction_summaries( $note_ids ) {
2415          global $wpdb;
2416  
2417          $this->reaction_summaries = array();
2418  
2419          if ( empty( $note_ids ) ) {
2420              return;
2421          }
2422  
2423          $current_user_id = get_current_user_id();
2424  
2425          // Only reactions stored on their note's post count, which is what create_item() writes.
2426          $from   = "FROM $wpdb->comments AS r INNER JOIN $wpdb->comments AS n";
2427          $from  .= " ON n.comment_ID = r.comment_parent AND n.comment_post_ID = r.comment_post_ID AND n.comment_type = 'note'";
2428          $where  = "WHERE r.comment_type = 'reaction' AND r.comment_approved = '1' AND ";
2429          $where .= $wpdb->prepare(
2430              'r.comment_parent IN (' . implode( ',', array_fill( 0, count( $note_ids ), '%d' ) ) . ')',
2431              ...$note_ids
2432          );
2433  
2434          // Query 1: Get aggregated counts per emoji per note.
2435          $query = "SELECT r.comment_parent, r.comment_content, COUNT(*) AS reaction_count $from $where GROUP BY r.comment_parent, r.comment_content";
2436          /** @var list<object{ comment_parent: decimal-int-string, comment_content: string, reaction_count: decimal-int-string }&stdClass>|null $counts */
2437          $counts = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above.
2438  
2439          // Query 2: Get the current user's own reaction IDs (if logged in).
2440          $my_reactions = array();
2441          if ( $current_user_id ) {
2442              $query  = "SELECT r.comment_ID, r.comment_parent, r.comment_content $from $where";
2443              $query .= $wpdb->prepare( ' AND r.user_id = %d', $current_user_id );
2444              /** @var list<object{ comment_ID: decimal-int-string, comment_parent: decimal-int-string, comment_content: string }&stdClass>|null $user_rows */
2445              $user_rows = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- It is prepared above.
2446  
2447              if ( $user_rows ) {
2448                  foreach ( $user_rows as $row ) {
2449                      $key                  = (int) $row->comment_parent . ':' . wp_strip_all_tags( $row->comment_content );
2450                      $my_reactions[ $key ] = (int) $row->comment_ID;
2451                  }
2452              }
2453          }
2454  
2455          // Initialize empty summaries for every requested note ID.
2456          foreach ( $note_ids as $note_id ) {
2457              $this->reaction_summaries[ $note_id ] = array();
2458          }
2459  
2460          if ( ! $counts ) {
2461              return;
2462          }
2463  
2464          $allowed_keys = self::get_note_reaction_keys();
2465  
2466          foreach ( $counts as $row ) {
2467              $note_id   = (int) $row->comment_parent;
2468              $emoji_key = wp_strip_all_tags( $row->comment_content );
2469              $key       = $note_id . ':' . $emoji_key;
2470  
2471              // Only curated emoji keys are summarized.
2472              if ( ! in_array( $emoji_key, $allowed_keys, true ) ) {
2473                  continue;
2474              }
2475  
2476              // Rows are grouped on the raw content, so several groups can strip to one key.
2477              if ( ! isset( $this->reaction_summaries[ $note_id ][ $emoji_key ] ) ) {
2478                  $this->reaction_summaries[ $note_id ][ $emoji_key ] = array(
2479                      'count'                 => 0,
2480                      'current_user_reaction' => $my_reactions[ $key ] ?? 0,
2481                  );
2482              }
2483  
2484              $this->reaction_summaries[ $note_id ][ $emoji_key ]['count'] += (int) $row->reaction_count;
2485          }
2486      }
2487  
2488      /**
2489       * Checks if the comment can be read.
2490       *
2491       * @since 4.7.0
2492       *
2493       * @param WP_Comment      $comment Comment object.
2494       * @param WP_REST_Request $request Request data to check.
2495       * @return bool Whether the comment can be read.
2496       */
2497  	protected function check_read_permission( $comment, $request ) {
2498          if ( ! in_array( $comment->comment_type, array( 'note', 'reaction' ), true ) && ! empty( $comment->comment_post_ID ) ) {
2499              $post = get_post( $comment->comment_post_ID );
2500              if ( $post ) {
2501                  if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) {
2502                      return true;
2503                  }
2504              }
2505          }
2506  
2507          if ( 0 === get_current_user_id() ) {
2508              return false;
2509          }
2510  
2511          if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) {
2512              return false;
2513          }
2514  
2515          if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) {
2516              return true;
2517          }
2518  
2519          return current_user_can( 'edit_comment', $comment->comment_ID );
2520      }
2521  
2522      /**
2523       * Checks if a comment can be edited or deleted.
2524       *
2525       * @since 4.7.0
2526       *
2527       * @param WP_Comment $comment Comment object.
2528       * @return bool Whether the comment can be edited or deleted.
2529       */
2530  	protected function check_edit_permission( $comment ) {
2531          if ( 0 === (int) get_current_user_id() ) {
2532              return false;
2533          }
2534  
2535          /*
2536           * Notes and their reactions are editorial content, so require edit access
2537           * to the note's post rather than the moderate_comments capability.
2538           */
2539          if ( in_array( strtolower( $comment->comment_type ), array( 'note', 'reaction' ), true ) ) {
2540              return current_user_can( 'edit_comment', $comment->comment_ID );
2541          }
2542  
2543          if ( current_user_can( 'moderate_comments' ) ) {
2544              return true;
2545          }
2546  
2547          return current_user_can( 'edit_comment', $comment->comment_ID );
2548      }
2549  
2550      /**
2551       * Checks whether the current user can attribute a comment to another user.
2552       *
2553       * @since 7.1.5
2554       *
2555       * @param int $author_id ID of the user the comment is being attributed to.
2556       * @return bool Whether the comment can be attributed to the user.
2557       */
2558  	protected function check_assign_author_permission( $author_id ) {
2559          return current_user_can( 'moderate_comments' ) && is_user_member_of_blog( $author_id );
2560      }
2561  
2562      /**
2563       * Checks a comment author email for validity.
2564       *
2565       * Accepts either a valid email address or empty string as a valid comment
2566       * author email address. Setting the comment author email to an empty
2567       * string is allowed when a comment is being updated.
2568       *
2569       * @since 4.7.0
2570       *
2571       * @param string          $value   Author email value submitted.
2572       * @param WP_REST_Request $request Full details about the request.
2573       * @param string          $param   The parameter name.
2574       * @return string|WP_Error The sanitized email address, if valid,
2575       *                         otherwise an error.
2576       */
2577  	public function check_comment_author_email( $value, $request, $param ) {
2578          $email = (string) $value;
2579          if ( empty( $email ) ) {
2580              return $email;
2581          }
2582  
2583          $check_email = rest_validate_request_arg( $email, $request, $param );
2584          if ( is_wp_error( $check_email ) ) {
2585              return $check_email;
2586          }
2587  
2588          return $email;
2589      }
2590  
2591      /**
2592       * If empty comments are not allowed, checks if the provided comment content is not empty.
2593       *
2594       * @since 5.6.0
2595       *
2596       * @param array $prepared_comment The prepared comment data.
2597       * @return bool True if the content is allowed, false otherwise.
2598       */
2599  	protected function check_is_comment_content_allowed( $prepared_comment ) {
2600          if ( ! isset( $prepared_comment['comment_content'] ) ) {
2601              return true;
2602          }
2603  
2604          $check = wp_parse_args(
2605              $prepared_comment,
2606              array(
2607                  'comment_post_ID'      => 0,
2608                  'comment_author'       => null,
2609                  'comment_author_email' => null,
2610                  'comment_author_url'   => null,
2611                  'comment_parent'       => 0,
2612                  'user_id'              => 0,
2613              )
2614          );
2615  
2616          /** This filter is documented in wp-includes/comment.php */
2617          $allow_empty = apply_filters( 'allow_empty_comment', false, $check );
2618  
2619          if ( $allow_empty ) {
2620              return true;
2621          }
2622  
2623          // Allow empty notes only when resolution metadata is valid.
2624          if (
2625              isset( $check['comment_type'] ) &&
2626              'note' === $check['comment_type'] &&
2627              isset( $check['meta']['_wp_note_status'] ) &&
2628              in_array( $check['meta']['_wp_note_status'], array( 'resolved', 'reopen' ), true )
2629          ) {
2630              return true;
2631          }
2632  
2633          /*
2634           * Do not allow a comment to be created with missing or empty
2635           * comment_content. See wp_handle_comment_submission().
2636           */
2637          return '' !== $check['comment_content'];
2638      }
2639  
2640      /**
2641       * Sanitizes a single comment status or a list of comment statuses.
2642       *
2643       * @since 7.2.0
2644       *
2645       * @param string[]|string $statuses Comment status or array of comment statuses.
2646       * @return string[] Sanitized array of comment statuses.
2647       * @phpstan-return list<non-empty-lowercase-string>
2648       */
2649  	public function sanitize_comment_statuses( $statuses ): array {
2650          $statuses = array_unique( array_map( 'sanitize_key', wp_parse_list( $statuses ) ) );
2651  
2652          // Only drop empty values. A literal '0' is a queryable status, as comments are held with `comment_approved` of '0'.
2653          $statuses = array_filter(
2654              $statuses,
2655              static function ( $status ) {
2656                  return '' !== $status;
2657              }
2658          );
2659  
2660          return array_values( $statuses );
2661      }
2662  
2663      /**
2664       * Checks that a post can receive a comment or a note from the current user.
2665       *
2666       * Used when creating a note and when changing the parent post of an existing
2667       * comment or note, so that attaching content to a post is authorized the same
2668       * way whichever path it arrives by.
2669       *
2670       * @since 7.1.1
2671       *
2672       * @param int             $post_id Target post ID.
2673       * @param WP_REST_Request $request Full details about the request.
2674       * @param bool            $is_note Optional. Whether the comment is a note. Default false.
2675       * @return true|WP_Error True if the post can receive the comment, error object otherwise.
2676       */
2677  	protected function check_target_post_permission( int $post_id, WP_REST_Request $request, bool $is_note = false ) {
2678          if ( ! $post_id ) {
2679              return new WP_Error(
2680                  'rest_comment_invalid_post_id',
2681                  __( 'Sorry, you are not allowed to create this comment without a post.' ),
2682                  array( 'status' => 403 )
2683              );
2684          }
2685  
2686          /*
2687           * Notes are editorial content, so they may only be attached to a post the
2688           * user can edit. Any other comment needs either comment moderation rights
2689           * or edit access to the post, which is what check_edit_permission() grants
2690           * on the post a comment is moving away from. Requiring the same at the
2691           * destination means both ends of a move are authorized alike.
2692           */
2693          if ( $is_note ) {
2694              $can_target_post = current_user_can( 'edit_post', $post_id );
2695          } else {
2696              $can_target_post = current_user_can( 'moderate_comments' ) || current_user_can( 'edit_post', $post_id );
2697          }
2698  
2699          if ( ! $can_target_post ) {
2700              if ( $is_note ) {
2701                  return new WP_Error(
2702                      'rest_cannot_create_note',
2703                      __( 'Sorry, you are not allowed to create notes for this post.' ),
2704                      array( 'status' => rest_authorization_required_code() )
2705                  );
2706              }
2707  
2708              return new WP_Error(
2709                  'rest_cannot_edit',
2710                  __( 'Sorry, you are not allowed to edit this comment.' ),
2711                  array( 'status' => rest_authorization_required_code() )
2712              );
2713          }
2714  
2715          $post = get_post( $post_id );
2716  
2717          if ( ! $post ) {
2718              return new WP_Error(
2719                  'rest_comment_invalid_post_id',
2720                  __( 'Sorry, you are not allowed to create this comment without a post.' ),
2721                  array( 'status' => 403 )
2722              );
2723          }
2724  
2725          /*
2726           * The remaining rules mirror the create-time checks for notes only. They are
2727           * deliberately not applied to other comments, because moderators move comments
2728           * onto posts whose discussion has closed and onto drafts today. Enforcing the
2729           * create-time rules there would break that without blocking anything the
2730           * capability check above already permits.
2731           */
2732          if ( ! $is_note ) {
2733              return true;
2734          }
2735  
2736          if ( ! $this->check_post_type_supports_notes( $post->post_type ) ) {
2737              return new WP_Error(
2738                  'rest_comment_not_supported_post_type',
2739                  __( 'Sorry, this post type does not support notes.' ),
2740                  array( 'status' => 403 )
2741              );
2742          }
2743  
2744          if ( 'trash' === $post->post_status ) {
2745              return new WP_Error(
2746                  'rest_comment_trash_post',
2747                  __( 'Sorry, you are not allowed to create a comment on this post.' ),
2748                  array( 'status' => 403 )
2749              );
2750          }
2751  
2752          if ( ! $this->check_read_post_permission( $post, $request ) ) {
2753              return new WP_Error(
2754                  'rest_cannot_read_post',
2755                  __( 'Sorry, you are not allowed to read the post for this comment.' ),
2756                  array( 'status' => rest_authorization_required_code() )
2757              );
2758          }
2759  
2760          return true;
2761      }
2762  
2763      /**
2764       * Checks that a note's parent is a note on the same post.
2765       *
2766       * @since 7.2.0
2767       *
2768       * @param int $parent_id ID of the parent comment.
2769       * @param int $post_id   ID of the post the note is, or will be, on.
2770       * @return true|WP_Error True if the parent is valid, error object otherwise.
2771       */
2772  	private function check_note_parent( int $parent_id, int $post_id ) {
2773          $parent = get_comment( $parent_id );
2774  
2775          if (
2776              ! $parent ||
2777              'note' !== $parent->comment_type ||
2778              ( $post_id && $post_id !== (int) $parent->comment_post_ID )
2779          ) {
2780              return new WP_Error(
2781                  'rest_comment_invalid_parent',
2782                  __( 'A note reply must be attached to a note on the same post.' ),
2783                  array( 'status' => 400 )
2784              );
2785          }
2786  
2787          return true;
2788      }
2789  
2790      /**
2791       * Checks whether a note belongs to a resolved thread.
2792       *
2793       * Resolving a thread approves its root note.
2794       *
2795       * @since 7.2.0
2796       *
2797       * @param WP_Comment $note A root note or a reply.
2798       * @return bool True if the note's thread is resolved.
2799       */
2800  	private function is_thread_resolved( WP_Comment $note ): bool {
2801          $thread_root = $note;
2802          $visited     = array( (int) $thread_root->comment_ID => true );
2803          while ( $thread_root->comment_parent ) {
2804              $ancestor = get_comment( $thread_root->comment_parent );
2805  
2806              // Stop at a missing ancestor or a corrupt, cyclic chain.
2807              if ( ! $ancestor || isset( $visited[ (int) $ancestor->comment_ID ] ) ) {
2808                  break;
2809              }
2810  
2811              $visited[ (int) $ancestor->comment_ID ] = true;
2812              $thread_root                            = $ancestor;
2813          }
2814  
2815          return '1' === $thread_root->comment_approved;
2816      }
2817  
2818      /**
2819       * Check if post type supports notes.
2820       *
2821       * @since 6.9.0
2822       *
2823       * @param string $post_type Post type name.
2824       * @return bool True if post type supports notes, false otherwise.
2825       */
2826  	private function check_post_type_supports_notes( $post_type ) {
2827          $supports = get_all_post_type_supports( $post_type );
2828  
2829          if ( ! isset( $supports['editor'] ) ) {
2830              return false;
2831          }
2832  
2833          if ( ! is_array( $supports['editor'] ) ) {
2834              return false;
2835          }
2836  
2837          return array_any( $supports['editor'], fn( $item ) => ! empty( $item['notes'] ) );
2838      }
2839  }


Generated : Tue Dec 1 08:20:01 2026 Cross-referenced by PHPXref