| 1 |
<?php |
| 2 |
|
| 3 |
// phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure. |
| 4 |
namespace Yoast\WP\SEO\Abilities\Infrastructure; |
| 5 |
|
| 6 |
use WP_Error; |
| 7 |
use Yoast\WP\SEO\Models\Indexable; |
| 8 |
|
| 9 |
/** |
| 10 |
* Checks whether the current user may edit the posts behind indexables. |
| 11 |
* |
| 12 |
* The abilities are gated site-wide by a capability check, but that capability |
| 13 |
* must not grant access to posts the user could not otherwise edit. This |
| 14 |
* checker applies the exact per-post WordPress check, current_user_can( 'edit_post', $id ), |
| 15 |
* mirroring the bulk editor's access rules. |
| 16 |
*/ |
| 17 |
class Post_Access_Checker { |
| 18 |
|
| 19 |
/** |
| 20 |
* Ensures the current user may edit the given post. |
| 21 |
* |
| 22 |
* @param int $post_id The post ID. |
| 23 |
* |
| 24 |
* @return true|WP_Error True when the post is editable, or a 403 error. |
| 25 |
*/ |
| 26 |
public function ensure_can_edit( int $post_id ) { |
| 27 |
if ( \current_user_can( 'edit_post', $post_id ) ) { |
| 28 |
return true; |
| 29 |
} |
| 30 |
|
| 31 |
return $this->forbidden_error(); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Builds the 403 error for posts the current user may not edit. |
| 36 |
* |
| 37 |
* Mirrors WP core's rest_cannot_edit wording. |
| 38 |
* |
| 39 |
* @return WP_Error The forbidden error. |
| 40 |
*/ |
| 41 |
public function forbidden_error(): WP_Error { |
| 42 |
return new WP_Error( |
| 43 |
'yoast_seo_cannot_edit_post', |
| 44 |
\__( 'Sorry, you are not allowed to edit this post.', 'wordpress-seo' ), |
| 45 |
[ 'status' => 403 ], |
| 46 |
); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Filters a list of post indexables down to the ones the current user may edit. |
| 51 |
* |
| 52 |
* @param Indexable[] $indexables The post indexables. |
| 53 |
* |
| 54 |
* @return Indexable[] The editable indexables, reindexed. |
| 55 |
*/ |
| 56 |
public function filter_editable( array $indexables ): array { |
| 57 |
$editable = \array_filter( |
| 58 |
$indexables, |
| 59 |
static function ( $indexable ) { |
| 60 |
return \current_user_can( 'edit_post', (int) $indexable->object_id ); |
| 61 |
}, |
| 62 |
); |
| 63 |
|
| 64 |
return \array_values( $editable ); |
| 65 |
} |
| 66 |
} |
| 67 |
|