[ Index ]

PHP Cross Reference of WordPress

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


Generated: Mon Jul 15 01:00:03 2019 Cross-referenced by PHPXref 0.7.1