REST API: On comment create, return an error if the `post` parameter does not relate to a valid WP_Post object.

Return a `WP_Error` object for attempts to create a comment without an empty or invalid `post` ID.

Props dd32, jnylen0, rachelbaker.
Fixes #38816.

git-svn-id: https://develop.svn.wordpress.org/trunk@39288 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Rachel Baker 2016-11-18 16:55:03 +00:00
parent cceb9a6053
commit ff38fc46e4
2 changed files with 20 additions and 16 deletions

View File

@ -385,11 +385,15 @@ class WP_REST_Comments_Controller extends WP_REST_Controller {
return new WP_Error( 'rest_comment_invalid_status', __( 'Sorry, you are not allowed to set status for comments.' ), array( 'status' => rest_authorization_required_code() ) );
}
if ( empty( $request['post'] ) && ! current_user_can( 'moderate_comments' ) ) {
return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => rest_authorization_required_code() ) );
if ( empty( $request['post'] ) ) {
return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
}
$post = get_post( (int) $request['post'] );
if ( ! $post ) {
return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
}
if ( ! empty( $request['post'] ) && $post = get_post( (int) $request['post'] ) ) {
if ( 'draft' === $post->post_status ) {
return new WP_Error( 'rest_comment_draft_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
}
@ -405,7 +409,6 @@ class WP_REST_Comments_Controller extends WP_REST_Controller {
if ( ! comments_open( $post->ID ) ) {
return new WP_Error( 'rest_comment_closed', __( 'Sorry, comments are closed on this post.' ), array( 'status' => 403 ) );
}
}
return true;
}

View File

@ -1306,7 +1306,8 @@ class WP_Test_REST_Comments_Controller extends WP_Test_REST_Controller_Testcase
$request->set_body( wp_json_encode( $params ) );
$response = $this->server->dispatch( $request );
$this->assertEquals( 201, $response->get_status() );
$this->assertErrorResponse( 'rest_comment_invalid_post_id', $response, 403 );
}
public function test_create_comment_no_post_id_no_permission() {