REST API: Confirm the parent post object of an attachment exists in `WP_REST_Posts_Controller::check_read_permission()`.

Avoid a PHP Error when attempting to embed the parent post of an attachment, when the parent post ID is invalid. Instead check if the parent post 
object exists before checking the read permission for the parent post.

Props GhostToast.
Fixes #39881. 

Merges [40306] to the 4.7 branch.


git-svn-id: https://develop.svn.wordpress.org/branches/4.7@40337 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Pascal Birchler 2017-03-27 09:23:05 +00:00
parent 8e68bdace3
commit 3f200a7c35
2 changed files with 28 additions and 1 deletions

View File

@ -1288,7 +1288,9 @@ class WP_REST_Posts_Controller extends WP_REST_Controller {
// Can we read the parent if we're inheriting?
if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
$parent = get_post( $post->post_parent );
return $this->check_read_permission( $parent );
if ( $parent ) {
return $this->check_read_permission( $parent );
}
}
/*

View File

@ -480,6 +480,31 @@ class WP_Test_REST_Attachments_Controller extends WP_Test_REST_Post_Type_Control
$this->assertEquals( 403, $response->get_status() );
}
public function test_get_item_inherit_status_with_invalid_parent() {
$attachment_id = $this->factory->attachment->create_object( $this->test_file, REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, array(
'post_mime_type' => 'image/jpeg',
'post_excerpt' => 'A sample caption',
) );
$request = new WP_REST_Request( 'GET', sprintf( '/wp/v2/media/%d', $attachment_id ) );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 200, $response->get_status() );
$this->assertEquals( $attachment_id, $data['id'] );
}
public function test_get_item_auto_status_with_invalid_parent_returns_error() {
$attachment_id = $this->factory->attachment->create_object( $this->test_file, REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, array(
'post_mime_type' => 'image/jpeg',
'post_excerpt' => 'A sample caption',
'post_status' => 'auto-draft',
) );
$request = new WP_REST_Request( 'GET', sprintf( '/wp/v2/media/%d', $attachment_id ) );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_forbidden', $response, 403 );
}
public function test_create_item() {
wp_set_current_user( self::$author_id );