diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php
index 835c19e04f949..b67387be617bd 100644
--- a/src/wp-includes/abilities.php
+++ b/src/wp-includes/abilities.php
@@ -50,6 +50,7 @@ function wp_register_core_ability_categories(): void {
*
* @since 6.9.0
* @since 7.2.0 Added the `core/content-query`, `core/settings-get`, and `core/users-query` abilities.
+ * @since 7.3.0 Added the `core/content-create`, `core/content-update`, and `core/content-delete` abilities.
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
@@ -377,6 +378,6 @@ function wp_register_core_abilities(): void {
// Register the user abilities (currently the read-only `core/users-query`).
( new WP_Abilities_Users() )->register();
- // Register the content abilities (currently the read-only `core/content-query`).
+ // Register the content abilities (query, create, update, and delete).
( new WP_Abilities_Content() )->register();
}
diff --git a/src/wp-includes/abilities/class-wp-abilities-content.php b/src/wp-includes/abilities/class-wp-abilities-content.php
index 17e1a81ac30df..c0855bb02ef99 100644
--- a/src/wp-includes/abilities/class-wp-abilities-content.php
+++ b/src/wp-includes/abilities/class-wp-abilities-content.php
@@ -17,12 +17,15 @@
* status, author, and parent. Raw fields are only returned for posts the current user can
* edit, and the author's name and slug only for authors the current user may see.
*
+ * Also registers `core/content-create`, `core/content-update`, and `core/content-delete`,
+ * which create, update, and trash or delete one post of such a post type, and return the
+ * written post in the same shape as a `core/content-query` item.
+ *
* Unlike the core abilities registered directly in wp_register_core_abilities() as
- * self-contained closures, the content ability lives in a dedicated class because
- * its callbacks and schemas share helpers: the permission and execute callbacks read the
+ * self-contained closures, the content abilities live in a dedicated class because
+ * their callbacks and schemas share helpers: the permission and execute callbacks read the
* post type and the filters through the same code, and the input schema, output schema,
- * and field projection are built from the same field definitions. Future write-oriented
- * content abilities can reuse them as well.
+ * and field projection are built from the same field definitions.
*
* Only register() is public. The ability callbacks are closures that call private
* methods, so callers go through the Abilities API, such as
@@ -93,7 +96,17 @@ final class WP_Abilities_Content {
private const LOOP_GLOBALS = array( 'post', 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' );
/**
- * Whether each author seen in the current query has posts the current user may read.
+ * The `data` attributes the create and update abilities can write.
+ *
+ * Only these reach the save, each mapped to one post field. Other keys are never written.
+ *
+ * @since 7.3.0
+ * @var list
+ */
+ private const WRITE_ATTRIBUTES = array( 'title', 'content', 'excerpt', 'status', 'slug', 'date', 'author', 'parent' );
+
+ /**
+ * Whether each author seen in the current call has posts the current user may read.
*
* @since 7.2.0
* @var array
@@ -106,38 +119,44 @@ final class WP_Abilities_Content {
* Must run on the `wp_abilities_api_init` hook.
*
* @since 7.2.0
+ * @since 7.3.0 Registers the `core/content-create`, `core/content-update`, and `core/content-delete` abilities.
*/
public function register(): void {
- $this->register_content_query();
-
/*
- * Future write-oriented content abilities can be registered here, reusing the
- * shared helpers below (get_exposed_post_type(), format_post(), check_permission()).
+ * Post types must be registered with `show_in_abilities` before the abilities are
+ * registered so they are included in the input schemas. Without one, no content
+ * ability is registered.
*/
+ $post_types = array_values( get_post_types( array( 'show_in_abilities' => true ) ) );
+ if ( empty( $post_types ) ) {
+ return;
+ }
+
+ // The statuses that can be set: the ones the query accepts, other than `trash`.
+ $statuses = array_values( array_diff( $this->get_queryable_statuses(), array( 'trash' ) ) );
+
+ $this->register_content_query( $post_types );
+ $this->register_content_create( $post_types, $statuses );
+ $this->register_content_update( $post_types, $statuses );
+ $this->register_content_delete( $post_types );
}
/**
* Registers the read-only `core/content-query` ability.
*
* @since 7.2.0
+ * @since 7.3.0 Added the `$post_types` parameter.
+ *
+ * @param list $post_types Exposed post type names.
*/
- private function register_content_query(): void {
+ private function register_content_query( array $post_types ): void {
/*
- * Post types must be registered with `show_in_abilities` before the ability is
- * registered so they are included in its input schema.
+ * Internal statuses (e.g. `inherit`) are excluded here, other than `trash`, and from
+ * the statuses a query covers by default, so the posts of post types that rely on them
+ * (attachments) cannot be queried, not even by ID. Revisit if such a post type is ever
+ * exposed via `show_in_abilities`.
*/
- $post_types = array_values( get_post_types( array( 'show_in_abilities' => true ) ) );
- if ( empty( $post_types ) ) {
- return;
- }
-
- /*
- * Internal statuses (e.g. `inherit`) are excluded here and from the statuses a query
- * covers by default, so the posts of post types that rely on them (attachments)
- * cannot be queried, not even by ID. Revisit if such a post type is ever exposed via
- * `show_in_abilities`.
- */
- $statuses = array_values( get_post_stati( array( 'internal' => false ) ) );
+ $statuses = $this->get_queryable_statuses();
wp_register_ability(
'core/content-query',
@@ -151,7 +170,7 @@ private function register_content_query(): void {
return $this->execute_content_query( $input );
},
'permission_callback' => function ( $input = array() ): bool {
- return $this->check_permission( $input );
+ return $this->check_query_permission( $input );
},
'meta' => array(
'annotations' => array(
@@ -165,6 +184,110 @@ private function register_content_query(): void {
);
}
+ /**
+ * Registers the `core/content-create` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $post_types Exposed post type names.
+ * @param list $statuses Post status slugs that can be set.
+ */
+ private function register_content_create( array $post_types, array $statuses ): void {
+ wp_register_ability(
+ 'core/content-create',
+ array(
+ 'label' => __( 'Create Content' ),
+ 'description' => __( 'Creates a post of a post type exposed to abilities and returns it. Requires an authenticated user who can create posts of that type. The post is saved as a draft unless another status is given.' ),
+ 'category' => self::CATEGORY,
+ 'input_schema' => $this->get_content_create_input_schema( $post_types, $statuses ),
+ 'output_schema' => $this->get_content_output_schema(),
+ 'execute_callback' => function ( $input = array() ) {
+ return $this->execute_content_create( $input );
+ },
+ 'permission_callback' => function ( $input = array() ): bool {
+ return $this->check_create_permission( $input );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => false,
+ 'destructive' => false,
+ 'idempotent' => false,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+ }
+
+ /**
+ * Registers the `core/content-update` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $post_types Exposed post type names.
+ * @param list $statuses Post status slugs that can be set.
+ */
+ private function register_content_update( array $post_types, array $statuses ): void {
+ wp_register_ability(
+ 'core/content-update',
+ array(
+ 'label' => __( 'Update Content' ),
+ 'description' => __( 'Updates the given attributes of a post of a post type exposed to abilities and returns it. Attributes that are left out keep their stored values. Requires an authenticated user who can edit the post.' ),
+ 'category' => self::CATEGORY,
+ 'input_schema' => $this->get_content_update_input_schema( $post_types, $statuses ),
+ 'output_schema' => $this->get_content_output_schema(),
+ 'execute_callback' => function ( $input = array() ) {
+ return $this->execute_content_update( $input );
+ },
+ 'permission_callback' => function ( $input = array() ): bool {
+ return $this->check_post_permission( $input, 'edit_post' );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => false,
+ 'destructive' => false,
+ 'idempotent' => true,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+ }
+
+ /**
+ * Registers the `core/content-delete` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $post_types Exposed post type names.
+ */
+ private function register_content_delete( array $post_types ): void {
+ wp_register_ability(
+ 'core/content-delete',
+ array(
+ 'label' => __( 'Delete Content' ),
+ 'description' => __( 'Moves a post of a post type exposed to abilities to the Trash, or deletes it permanently when `permanent` is true. Requires an authenticated user who can delete the post.' ),
+ 'category' => self::CATEGORY,
+ 'input_schema' => $this->get_content_delete_input_schema( $post_types ),
+ 'output_schema' => $this->get_content_delete_output_schema(),
+ 'execute_callback' => function ( $input = array() ) {
+ return $this->execute_content_delete( $input );
+ },
+ 'permission_callback' => function ( $input = array() ): bool {
+ return $this->check_post_permission( $input, 'delete_post' );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => false,
+ 'destructive' => true,
+ 'idempotent' => true,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+ }
+
/**
* Permission callback for the `core/content-query` ability.
*
@@ -178,7 +301,7 @@ private function register_content_query(): void {
* @param mixed $input Optional. The ability input. Default empty array.
* @return bool True if the request may proceed, false otherwise.
*/
- private function check_permission( $input = array() ): bool {
+ private function check_query_permission( $input = array() ): bool {
$input = rest_sanitize_object( $input );
if ( ! is_user_logged_in() ) {
@@ -203,13 +326,67 @@ private function check_permission( $input = array() ): bool {
return $this->can_query_statuses( $where, $post_type_object );
}
+ /**
+ * Permission callback for the `core/content-create` ability.
+ *
+ * A coarse gate: a logged-in user, a `data.type` that is exposed to abilities, and the
+ * capability to create posts of that type. {@see self::execute_content_create()} checks
+ * the capability again and makes every other decision.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input Optional. The ability input. Default empty array.
+ * @return bool True if the request may proceed, false otherwise.
+ */
+ private function check_create_permission( $input = array() ): bool {
+ if ( ! is_user_logged_in() ) {
+ return false;
+ }
+
+ // The input is read defensively: WP_Ability::check_permissions() does not prepare it.
+ $data = $this->get_input_object( rest_sanitize_object( $input ), 'data' ) ?? array();
+ $post_type_object = $this->get_exposed_post_type( $data['type'] ?? null );
+
+ return null !== $post_type_object && current_user_can( $post_type_object->cap->create_posts );
+ }
+
+ /**
+ * Permission callback for the `core/content-update` and `core/content-delete` abilities.
+ *
+ * Requires a logged-in user, a `where.type` that is exposed to abilities, and the given
+ * capability on the post that `where` names. A post that does not exist is let through,
+ * so that the execute callback can report it as not found. The execute callbacks check
+ * the capability again and make every other decision.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input.
+ * @param string $capability The capability required on the post: `edit_post` or `delete_post`.
+ * @return bool True if the request may proceed, false otherwise.
+ */
+ private function check_post_permission( $input, string $capability ): bool {
+ if ( ! is_user_logged_in() ) {
+ return false;
+ }
+
+ // The input is read defensively: WP_Ability::check_permissions() does not prepare it.
+ $where = $this->get_input_object( rest_sanitize_object( $input ), 'where' ) ?? array();
+ if ( ! $this->get_exposed_post_type( $where['type'] ?? null ) ) {
+ return false;
+ }
+
+ $post = $this->get_requested_post( array( 'where' => $where ) );
+
+ return ! $post || current_user_can( $capability, $post->ID );
+ }
+
/**
* Parses a raw input value into an integer of at least a minimum, or null when invalid.
*
* Accepts the whole numbers that the integer schema accepts: native integers, floats such
* as the 2.0 that JSON encoders produce, and integer strings such as "2", "2.0", or "+2".
- * Only the REST run controller converts input to the schema types, so other callers, such
- * as the MCP adapter or a direct WP_Ability::execute() call, pass them on unconverted.
+ * WP_Ability::execute() converts input to the schema types, but
+ * WP_Ability::check_permissions() does not, so a permission callback can receive any of them.
* Anything else, such as a fraction, is rejected rather than coerced: a malformed ID would
* otherwise resolve to another post, and a malformed `parent` filter would be read as 0,
* which asks for top-level posts.
@@ -310,7 +487,7 @@ private function can_query_status( string $status, WP_Post_Type $post_type_objec
* Checks if a post can be read by the current user.
*
* Mirrors the REST posts controller's read permission, while keeping this ability
- * authenticated-only via {@see self::check_permission()}.
+ * authenticated-only via {@see self::check_query_permission()}.
*
* @since 7.2.0
*
@@ -372,9 +549,10 @@ private function check_read_permission( WP_Post $post, array $checked_post_ids =
/*
* Mirror the REST posts controller's inherited-parent behavior, but keep the
* ability fail-closed for missing parents or parent loops. No input can request
- * `inherit`, since internal statuses are left out of the input schema and of the
- * statuses a query covers by default, but a query filter such as a `pre_get_posts`
- * callback can still add it, so such posts keep their parent's read check.
+ * `inherit`, since internal statuses other than `trash` are left out of the input
+ * schema, and all of them of the statuses a query covers by default, but a query
+ * filter such as a `pre_get_posts` callback can still add it, so such posts keep
+ * their parent's read check.
*/
if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
$parent = get_post( $post->post_parent );
@@ -389,7 +567,7 @@ private function check_read_permission( WP_Post $post, array $checked_post_ids =
/**
* Executes the `core/content-query` ability.
*
- * {@see WP_Ability::execute()} always runs {@see self::check_permission()} first, which
+ * {@see WP_Ability::execute()} always runs {@see self::check_query_permission()} first, which
* gates the request as a whole. The query still filters every row by read permission,
* because the gate cannot know the rows before the query runs.
*
@@ -419,19 +597,15 @@ private function execute_content_query( $input = array() ) {
$page = $this->parse_filter_int( $pagination['page'] ?? 1, 1 ) ?? 1;
/*
- * Unreachable through gated transports, which run check_permission() first and deny a
- * request without a post type exposed to abilities. A direct call to the execute
+ * Unreachable through gated transports, which run check_query_permission() first and deny
+ * a request without a post type exposed to abilities. A direct call to the execute
* callback still fails closed here, but it bypasses the checks of the request as a
* whole that the permission callback performed, such as the status capabilities, so
* only invoke the callback through WP_Ability::execute().
*/
$post_type_object = $this->get_exposed_post_type( $where['type'] ?? null );
if ( ! $post_type_object ) {
- return new WP_Error(
- 'content_not_found',
- __( 'The requested content was not found.' ),
- array( 'status' => 404 )
- );
+ return $this->not_found_error();
}
$post_type = $post_type_object->name;
@@ -577,9 +751,9 @@ private function execute_content_query( $input = array() ) {
* The input schema lists the statuses registered when the ability was, so check them
* again: WP_Query ignores a status that is not registered, and drops the status clause
* when none is left, which would cover every status, including internal ones such as
- * `trash`.
+ * `trash`. Of the internal statuses, only `trash` can be requested, by name.
*/
- if ( ! empty( array_diff( $statuses, get_post_stati( array( 'internal' => false ) ) ) ) ) {
+ if ( ! empty( array_diff( $statuses, $this->get_queryable_statuses() ) ) ) {
return $this->invalid_filter_error(
'where[status]',
/* translators: %s: Parameter. */
@@ -616,93 +790,713 @@ private function execute_content_query( $input = array() ) {
$query_args['post__in'] = $ids;
}
- if ( null !== $slugs ) {
- $query_args['post_name__in'] = $slugs;
+ if ( null !== $slugs ) {
+ $query_args['post_name__in'] = $slugs;
+ }
+
+ if ( is_int( $author_id ) ) {
+ $query_args['author'] = $author_id;
+ }
+
+ if ( null !== $parent ) {
+ $query_args['post_parent'] = $parent;
+ }
+
+ /*
+ * A slug that names no user or a user the current user may not see, or an ID and a slug
+ * that name different users, match no post, like IDs and slugs that name no post, rather
+ * than failing the query. An `id` is not looked up: the query matches the stored author
+ * ID, so the posts of a deleted user still match it.
+ */
+ if ( false === $author_id ) {
+ return $this->prepare_output( array(), 0, 0 );
+ }
+
+ $query = new WP_Query( $query_args );
+ $total = $this->get_query_total( $query, $query_args, $page );
+
+ /*
+ * Count the pages with the page size the query ran with, as the REST posts controller
+ * does, since query filters such as `pre_get_posts` callbacks can change it. Without
+ * paging, the query returns every post on one page.
+ */
+ $query_per_page = (int) $query->get( 'posts_per_page' );
+ if ( $query->get( 'nopaging' ) || $query_per_page < 1 ) {
+ $total_pages = $total > 0 ? 1 : 0;
+ } else {
+ $total_pages = (int) ceil( $total / $query_per_page );
+ }
+
+ /*
+ * A page past the last one does not exist, so report it as not found instead of
+ * returning a bare empty list. A genuinely empty result set still returns zero
+ * totals and no error.
+ */
+ if ( $total > 0 && $page > $total_pages ) {
+ return $this->invalid_page_number_error();
+ }
+
+ /*
+ * Prime the parent and author caches with a single query each instead of one
+ * lookup per post, as the REST posts controller does. Hierarchical permalinks and
+ * inherited read permissions read the parent, and format_post() sets up every post
+ * with setup_postdata(), which reads the author.
+ */
+ update_post_parent_caches( $query->posts );
+ update_post_author_caches( $query->posts );
+
+ $posts = array();
+ foreach ( $query->posts as $post ) {
+ /*
+ * Skip posts of other post types, which query filters can add, such as a
+ * `pre_get_posts` callback that adds post types to the blog home without an
+ * is_main_query() check.
+ */
+ if ( ! $post instanceof WP_Post || $post_type !== $post->post_type ) {
+ continue;
+ }
+ if ( ! $this->check_read_permission( $post ) ) {
+ continue;
+ }
+ $posts[] = $this->format_post( $post, $fields );
+ }
+
+ /*
+ * Mirror the REST posts controller: totals come from the underlying WP_Query,
+ * while the row-level checks above may withhold individual returned rows. The
+ * totals can therefore count posts the current user cannot read, such as another
+ * author's draft listed in `ids`. This is deliberate: it only reveals that such a
+ * post exists, as a REST collection request with `include` and `status` does.
+ */
+ return $this->prepare_output( $posts, $total, $total_pages );
+ }
+
+ /**
+ * Executes the `core/content-create` ability.
+ *
+ * The post type and the capability to create posts of it are checked first, then every
+ * attribute rule, and only then is the post saved, so a rejected call writes nothing.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The ability input, as prepared by WP_Ability::execute().
+ * @return array|WP_Error The created post, or a WP_Error on failure.
+ */
+ private function execute_content_create( array $input ) {
+ // The author visibility memo is per call; see get_visible_author().
+ $this->visible_authors = array();
+
+ $data = $input['data'] ?? array();
+ $post_type_object = $this->get_exposed_post_type( $data['type'] ?? null );
+ if ( ! $post_type_object ) {
+ return $this->not_found_error();
+ }
+
+ if ( ! current_user_can( $post_type_object->cap->create_posts ) ) {
+ return new WP_Error(
+ 'content_cannot_create',
+ __( 'Sorry, you are not allowed to create posts as this user.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ $postarr = $this->prepare_post_data( $data, $post_type_object, null );
+ if ( is_wp_error( $postarr ) ) {
+ return $postarr;
+ }
+
+ return $this->save_post( $postarr, $this->normalize_fields( $input ) );
+ }
+
+ /**
+ * Executes the `core/content-update` ability.
+ *
+ * The post is looked up first, then the capability to edit it is checked, then every
+ * attribute rule, and only then is the post saved, so a rejected call writes nothing.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The ability input, as prepared by WP_Ability::execute().
+ * @return array|WP_Error The updated post, or a WP_Error on failure.
+ */
+ private function execute_content_update( array $input ) {
+ // The author visibility memo is per call; see get_visible_author().
+ $this->visible_authors = array();
+
+ $post = $this->get_requested_post( $input );
+ if ( ! $post ) {
+ return $this->not_found_error();
+ }
+
+ // Checked again after the permission callback, whose result a filter can change.
+ if ( ! current_user_can( 'edit_post', $post->ID ) ) {
+ return new WP_Error(
+ 'content_cannot_edit',
+ __( 'Sorry, you are not allowed to edit this post.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ /*
+ * A `data` that sends no attribute that can be written has nothing to apply, so it is
+ * rejected instead of saving the post unchanged.
+ */
+ $data = $input['data'] ?? array();
+ if ( empty( array_intersect_key( $data, array_flip( self::WRITE_ATTRIBUTES ) ) ) ) {
+ return $this->invalid_attribute_error( 'data', __( 'The data must be an object with at least one attribute to write.' ) );
+ }
+
+ $post_type_object = $this->get_exposed_post_type( $post->post_type );
+ if ( ! $post_type_object ) {
+ return $this->not_found_error();
+ }
+
+ $postarr = $this->prepare_post_data( $data, $post_type_object, $post );
+ if ( is_wp_error( $postarr ) ) {
+ return $postarr;
+ }
+
+ return $this->save_post( $postarr, $this->normalize_fields( $input ) );
+ }
+
+ /**
+ * Executes the `core/content-delete` ability.
+ *
+ * The post is looked up first, then the capability to delete it is checked. The post is
+ * deleted permanently when `permanent` is true; otherwise it is moved to the Trash. The
+ * outcome is confirmed against the stored post afterwards.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The ability input, as prepared by WP_Ability::execute().
+ * @return array|WP_Error The outcome, or a WP_Error on failure.
+ */
+ private function execute_content_delete( array $input ) {
+ $post = $this->get_requested_post( $input );
+ if ( ! $post ) {
+ return $this->not_found_error();
+ }
+
+ // Checked again after the permission callback, whose result a filter can change.
+ if ( ! current_user_can( 'delete_post', $post->ID ) ) {
+ return new WP_Error(
+ 'content_cannot_delete',
+ __( 'Sorry, you are not allowed to delete this post.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ if ( true === ( $input['permanent'] ?? false ) ) {
+ $deleted = wp_delete_post( $post->ID, true );
+
+ return $deleted && null === get_post( $post->ID ) ? array( 'outcome' => 'deleted' ) : $this->delete_failed_error();
+ }
+
+ /*
+ * Checked before wp_trash_post() is called: without a Trash, it deletes the post
+ * permanently instead.
+ */
+ if ( ! $this->can_trash( $post ) ) {
+ return new WP_Error(
+ 'content_trash_not_supported',
+ __( 'The post does not support trashing. Set "permanent" to delete it.' ),
+ array( 'status' => 501 )
+ );
+ }
+
+ if ( 'trash' === $post->post_status ) {
+ return new WP_Error(
+ 'content_already_trashed',
+ __( 'The post has already been trashed.' ),
+ array( 'status' => 410 )
+ );
+ }
+
+ $trashed = wp_trash_post( $post->ID );
+
+ return $trashed && 'trash' === get_post_status( $post->ID ) ? array( 'outcome' => 'trashed' ) : $this->delete_failed_error();
+ }
+
+ /**
+ * Returns the post that `where` names, when it exists and has the named exposed type.
+ *
+ * The ID is read once, with {@see self::parse_filter_int()}, and that same integer is used
+ * for the lookup, the capability checks, and the write. An ID that is not a whole number
+ * of at least 1 names no post.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The ability input.
+ * @return WP_Post|null The post, or null when `where` names no post of an exposed type.
+ */
+ private function get_requested_post( array $input ): ?WP_Post {
+ $where = $input['where'] ?? array();
+ $post_type_object = $this->get_exposed_post_type( $where['type'] ?? null );
+ $post_id = $this->parse_filter_int( $where['id'] ?? null, 1 );
+ if ( ! $post_type_object || null === $post_id ) {
+ return null;
+ }
+
+ $post = get_post( $post_id );
+
+ return $post instanceof WP_Post && $post_type_object->name === $post->post_type ? $post : null;
+ }
+
+ /**
+ * Checks the `data` attributes and builds the array passed to the save.
+ *
+ * Shared by the create and update abilities. Only the attributes of
+ * {@see self::WRITE_ATTRIBUTES} that were sent reach the array, each mapped to one post
+ * field, next to the values the server sets: the post type on create, the post ID on
+ * update. The first rule that fails is returned and nothing is written.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param WP_Post_Type $post_type_object The post type of the post being written.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return array|WP_Error The unslashed post array, or a WP_Error.
+ */
+ private function prepare_post_data( array $data, WP_Post_Type $post_type_object, ?WP_Post $post ) {
+ $post_type = $post_type_object->name;
+
+ $error = $this->check_supported_attributes( $data, $post_type );
+ if ( $error ) {
+ return $error;
+ }
+
+ $postarr = array();
+ $text_fields = array(
+ 'title' => 'post_title',
+ 'content' => 'post_content',
+ 'excerpt' => 'post_excerpt',
+ );
+
+ foreach ( $text_fields as $attribute => $field ) {
+ if ( array_key_exists( $attribute, $data ) ) {
+ $postarr[ $field ] = $data[ $attribute ];
+ }
+ }
+
+ $status = $this->prepare_status( $data, $post_type_object, $post );
+ if ( is_wp_error( $status ) ) {
+ return $status;
+ }
+ if ( null !== $status ) {
+ $postarr['post_status'] = $status;
+ }
+
+ $author = $this->prepare_author( $data, $post_type_object, $post );
+ if ( is_wp_error( $author ) ) {
+ return $author;
+ }
+ if ( null !== $author ) {
+ $postarr['post_author'] = $author;
+ }
+
+ $parent = $this->prepare_parent( $data, $post_type, $post );
+ if ( is_wp_error( $parent ) ) {
+ return $parent;
+ }
+ if ( null !== $parent ) {
+ $postarr['post_parent'] = $parent;
+ }
+
+ $dates = $this->prepare_date( $data, $post, $status );
+ if ( is_wp_error( $dates ) ) {
+ return $dates;
+ }
+ $postarr = array_merge( $postarr, $dates );
+
+ $final_status = $postarr['post_status'] ?? $post->post_status ?? 'draft';
+ $final_parent = $postarr['post_parent'] ?? (int) ( $post->post_parent ?? 0 );
+
+ $slug = $this->prepare_slug( $data, $post_type_object, $post, $final_status, $final_parent );
+ if ( is_wp_error( $slug ) ) {
+ return $slug;
+ }
+ if ( null !== $slug ) {
+ $postarr['post_name'] = $slug;
+ }
+
+ if ( $post ) {
+ $postarr['ID'] = $post->ID;
+
+ // A stored page template that no longer exists must not fail an unrelated update.
+ $postarr['page_template'] = null;
+ } else {
+ $postarr['post_type'] = $post_type;
+ $postarr['post_status'] = $final_status;
+ }
+
+ return $postarr;
+ }
+
+ /**
+ * Rejects the sent attributes that the post type does not support.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param string $post_type The post type name.
+ * @return WP_Error|null The error for the first unsupported attribute, or null.
+ */
+ private function check_supported_attributes( array $data, string $post_type ): ?WP_Error {
+ /*
+ * Intentionally strict: an attribute that cannot be stored is an error and is never
+ * ignored, even when its value would change nothing.
+ */
+ $features = array(
+ 'title' => 'title',
+ 'content' => 'editor',
+ 'excerpt' => 'excerpt',
+ 'author' => 'author',
+ );
+ foreach ( $features as $attribute => $feature ) {
+ if ( array_key_exists( $attribute, $data ) && ! post_type_supports( $post_type, $feature ) ) {
+ return $this->invalid_attribute_error(
+ $attribute,
+ /* translators: 1: Attribute name, such as "content", 2: Post type feature, such as "editor". */
+ sprintf( __( 'The %1$s attribute is only supported for post types that support the %2$s feature.' ), $attribute, $feature )
+ );
+ }
+ }
+
+ if ( array_key_exists( 'parent', $data ) && ! is_post_type_hierarchical( $post_type ) ) {
+ return $this->invalid_attribute_error( 'parent', __( 'The parent attribute is only supported for hierarchical post types.' ) );
+ }
+
+ return null;
+ }
+
+ /**
+ * Checks the sent `status`.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param WP_Post_Type $post_type_object The post type of the post being written.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return string|WP_Error|null The status, null when none is sent, or a WP_Error.
+ */
+ private function prepare_status( array $data, WP_Post_Type $post_type_object, ?WP_Post $post ) {
+ if ( ! array_key_exists( 'status', $data ) ) {
+ return null;
+ }
+
+ $status = $data['status'];
+ $status_object = get_post_status_object( $status );
+
+ /*
+ * Intentionally strict: a status that is not registered is an error and is never
+ * replaced by another status. Internal statuses, such as `trash`, can never be set,
+ * not even when the post already has them.
+ */
+ if ( ! $status_object instanceof stdClass || ! empty( $status_object->internal ) ) {
+ return $this->invalid_attribute_error( 'status', __( 'The status must be a registered post status that is not internal.' ) );
+ }
+
+ // Keeping the stored status changes nothing.
+ if ( $post && $post->post_status === $status ) {
+ return $status;
+ }
+
+ /*
+ * Intentionally strict: every status that makes a post visible needs the capability
+ * to publish posts of the type, including custom ones.
+ */
+ $makes_visible = 'future' === $status || ! empty( $status_object->public ) || ! empty( $status_object->private ) || is_post_status_viewable( $status_object );
+ if ( $makes_visible && ! current_user_can( $post_type_object->cap->publish_posts ) ) {
+ return new WP_Error(
+ 'content_cannot_publish',
+ 'private' === $status
+ ? __( 'Sorry, you are not allowed to create private posts in this post type.' )
+ : __( 'Sorry, you are not allowed to publish posts in this post type.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ return $status;
+ }
+
+ /**
+ * Checks the sent `author`.
+ *
+ * The permission to name another user is checked before the user is looked up, so the
+ * error never tells whether a user ID exists.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param WP_Post_Type $post_type_object The post type of the post being written.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return int|WP_Error|null The author ID, null when none is sent or it is unchanged, or a WP_Error.
+ */
+ private function prepare_author( array $data, WP_Post_Type $post_type_object, ?WP_Post $post ) {
+ if ( ! array_key_exists( 'author', $data ) ) {
+ return null;
+ }
+
+ $author_id = $this->parse_filter_int( $data['author'], 1 );
+ if ( null === $author_id ) {
+ return $this->invalid_attribute_error( 'author', __( 'The author must be a user ID.' ) );
+ }
+
+ // Keeping the stored author changes nothing.
+ if ( $post && (int) $post->post_author === $author_id ) {
+ return null;
+ }
+
+ if ( get_current_user_id() === $author_id ) {
+ return $author_id;
+ }
+
+ if ( ! current_user_can( $post_type_object->cap->edit_others_posts ) ) {
+ return new WP_Error(
+ 'content_cannot_edit_others',
+ $post
+ ? __( 'Sorry, you are not allowed to update posts as this user.' )
+ : __( 'Sorry, you are not allowed to create posts as this user.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ // Intentionally strict: the author must be an existing user who belongs to this site.
+ if ( ! get_userdata( $author_id ) || ( is_multisite() && ! is_user_member_of_blog( $author_id ) ) ) {
+ return $this->invalid_attribute_error( 'author', __( 'The author must be an existing user of this site.' ) );
+ }
+
+ return $author_id;
+ }
+
+ /**
+ * Checks the sent `parent`.
+ *
+ * Every failure returns the same error, so it never tells whether a post ID exists.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param string $post_type The post type name.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return int|WP_Error|null The parent ID, null when none is sent or it is unchanged, or a WP_Error.
+ */
+ private function prepare_parent( array $data, string $post_type, ?WP_Post $post ) {
+ if ( ! array_key_exists( 'parent', $data ) ) {
+ return null;
+ }
+
+ $reason = __( 'The parent must be 0, or a readable post of the same post type that is neither the post itself nor one of its descendants.' );
+ $parent_id = $this->parse_filter_int( $data['parent'], 0 );
+ if ( null === $parent_id ) {
+ return $this->invalid_attribute_error( 'parent', $reason );
+ }
+
+ // Keeping the stored parent changes nothing.
+ if ( $post && (int) $post->post_parent === $parent_id ) {
+ return null;
+ }
+
+ if ( 0 === $parent_id ) {
+ return 0;
+ }
+
+ /*
+ * Intentionally strict: a parent must be readable, of the same type and free of
+ * loops; it is never silently reset.
+ */
+ $parent = get_post( $parent_id );
+ if ( ! $parent instanceof WP_Post || $post_type !== $parent->post_type || ! $this->check_read_permission( $parent ) ) {
+ return $this->invalid_attribute_error( 'parent', $reason );
+ }
+
+ if ( $post && ( $post->ID === $parent->ID || in_array( $post->ID, get_post_ancestors( $parent ), true ) ) ) {
+ return $this->invalid_attribute_error( 'parent', $reason );
+ }
+
+ return $parent_id;
+ }
+
+ /**
+ * Checks the sent `date` and returns the date fields to save.
+ *
+ * `site` wins when both `site` and `gmt` are sent. On update, a sent date that equals the
+ * stored one counts as not sent, so a draft with a floating date keeps floating, unless
+ * the call moves it to a status whose dates do not float with a date that is still ahead.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @param string|null $status The sent status, or null when none is sent.
+ * @return array|WP_Error The date fields to save, empty for none, or a WP_Error.
+ */
+ private function prepare_date( array $data, ?WP_Post $post, ?string $status ) {
+ if ( ! array_key_exists( 'date', $data ) ) {
+ return array();
+ }
+
+ $date = $data['date'];
+ if ( isset( $date['site'] ) ) {
+ $dates = rest_get_date_with_gmt( $date['site'] );
+ } elseif ( isset( $date['gmt'] ) ) {
+ $dates = rest_get_date_with_gmt( $date['gmt'], true );
+ } else {
+ $dates = null;
}
- if ( is_int( $author_id ) ) {
- $query_args['author'] = $author_id;
+ if ( null === $dates ) {
+ return $this->invalid_attribute_error( 'date', __( 'The date must be an object with a valid `site` or `gmt` date.' ) );
}
- if ( null !== $parent ) {
- $query_args['post_parent'] = $parent;
+ $fields = array(
+ 'post_date' => $dates[0],
+ 'post_date_gmt' => $dates[1],
+ );
+
+ if ( ! $post ) {
+ return $fields;
}
- /*
- * A slug that names no user or a user the current user may not see, or an ID and a slug
- * that name different users, match no post, like IDs and slugs that name no post, rather
- * than failing the query. An `id` is not looked up: the query matches the stored author
- * ID, so the posts of a deleted user still match it.
- */
- if ( false === $author_id ) {
- return $this->prepare_output( array(), 0, 0 );
+ $fields['edit_date'] = true;
+
+ $is_floating = '0000-00-00 00:00:00' === $post->post_date_gmt;
+ if ( isset( $date['site'] ) ) {
+ $is_unchanged = $post->post_date === $dates[0];
+ } else {
+ $stored_gmt = $is_floating ? get_gmt_from_date( $post->post_date ) : $post->post_date_gmt;
+ $is_unchanged = $stored_gmt === $dates[1];
}
- $query = new WP_Query( $query_args );
- $total = $this->get_query_total( $query, $query_args, $page );
+ if ( ! $is_unchanged ) {
+ return $fields;
+ }
/*
- * Count the pages with the page size the query ran with, as the REST posts controller
- * does, since query filters such as `pre_get_posts` callbacks can change it. Without
- * paging, the query returns every post on one page.
+ * Intentionally strict: sending back the date a floating draft shows, in either form,
+ * never pins it. The one exception is a call that also moves the draft to a status
+ * whose dates do not float, with a date still ahead: the date is stored, so the post
+ * is scheduled for the date it shows instead of being published at once.
*/
- $query_per_page = (int) $query->get( 'posts_per_page' );
- if ( $query->get( 'nopaging' ) || $query_per_page < 1 ) {
- $total_pages = $total > 0 ? 1 : 0;
- } else {
- $total_pages = (int) ceil( $total / $query_per_page );
+ $schedules = $is_floating
+ && null !== $status
+ && ! in_array( $status, get_post_stati( array( 'date_floating' => true ) ), true )
+ && $dates[1] > gmdate( 'Y-m-d H:i:s' );
+
+ return $schedules ? $fields : array();
+ }
+
+ /**
+ * Checks the sent `slug` and returns the slug to save.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param WP_Post_Type $post_type_object The post type of the post being written.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @param string $status The status the post will have.
+ * @param int $parent_id The parent ID the post will have.
+ * @return string|WP_Error|null The slug, null when none is sent, or a WP_Error.
+ */
+ private function prepare_slug( array $data, WP_Post_Type $post_type_object, ?WP_Post $post, string $status, int $parent_id ) {
+ if ( ! array_key_exists( 'slug', $data ) ) {
+ return null;
}
/*
- * A page past the last one does not exist, so report it as not found instead of
- * returning a bare empty list. A genuinely empty result set still returns zero
- * totals and no error.
+ * Intentionally strict: the save drops the slug of a pending post when the user cannot
+ * publish it, so the slug is an error here instead of being dropped without notice.
*/
- if ( $total > 0 && $page > $total_pages ) {
- return $this->invalid_page_number_error();
+ if ( 'pending' === $status ) {
+ $can_publish = $post
+ ? current_user_can( 'publish_post', $post->ID )
+ : current_user_can( $post_type_object->cap->publish_posts );
+ if ( ! $can_publish ) {
+ return $this->invalid_attribute_error( 'slug', __( 'The slug of a pending post can only be set by a user who can publish the post.' ) );
+ }
+ }
+
+ $slug = sanitize_title( $data['slug'] );
+
+ // Intentionally strict: a slug that sanitizes to nothing is an error.
+ if ( '' === $slug ) {
+ return $this->invalid_attribute_error( 'slug', __( 'The slug must contain characters that are valid in a slug.' ) );
}
/*
- * Prime the parent and author caches with a single query each instead of one
- * lookup per post, as the REST posts controller does. Hierarchical permalinks and
- * inherited read permissions read the parent, and format_post() sets up every post
- * with setup_postdata(), which reads the author.
+ * Intentionally strict: a draft never takes the slug of another post that shares its
+ * parent. The save keeps the slugs of drafts and pending posts as given, so they are
+ * made unique here as if the post were published.
*/
- update_post_parent_caches( $query->posts );
- update_post_author_caches( $query->posts );
+ if ( in_array( $status, array( 'draft', 'pending' ), true ) ) {
+ $slug = wp_unique_post_slug( $slug, $post ? $post->ID : 0, 'publish', $post_type_object->name, $parent_id );
+ }
- $posts = array();
- foreach ( $query->posts as $post ) {
- /*
- * Skip posts of other post types, which query filters can add, such as a
- * `pre_get_posts` callback that adds post types to the blog home without an
- * is_main_query() check.
- */
- if ( ! $post instanceof WP_Post || $post_type !== $post->post_type ) {
- continue;
- }
- if ( ! $this->check_read_permission( $post ) ) {
- continue;
- }
- $posts[] = $this->format_post( $post, $fields );
+ return $slug;
+ }
+
+ /**
+ * Saves a prepared post and returns it in the requested fields.
+ *
+ * The post is saved through the regular save functions, as the current user, so the
+ * default filters, such as the markup filtering for users without `unfiltered_html`, and
+ * the default hooks apply as in any other save.
+ *
+ * @since 7.3.0
+ *
+ * @param array $postarr The unslashed post array from prepare_post_data(). It
+ * holds an `ID` when the post is updated.
+ * @param list $fields The requested field paths.
+ * @return array|WP_Error The saved post, only its ID when the current user
+ * may not read it, or a WP_Error on failure.
+ */
+ private function save_post( array $postarr, array $fields ) {
+ $postarr = wp_slash( $postarr );
+ $post_id = isset( $postarr['ID'] ) ? wp_update_post( $postarr, true ) : wp_insert_post( $postarr, true );
+
+ if ( is_wp_error( $post_id ) ) {
+ $is_database_error = in_array( $post_id->get_error_code(), array( 'db_insert_error', 'db_update_error' ), true );
+ $post_id->add_data( array( 'status' => $is_database_error ? 500 : 400 ) );
+
+ return $post_id;
+ }
+
+ // get_post() would return the global post for an ID of 0.
+ $post = $post_id > 0 ? get_post( $post_id ) : null;
+ if ( ! $post instanceof WP_Post ) {
+ return $this->not_found_error();
}
/*
- * Mirror the REST posts controller: totals come from the underlying WP_Query,
- * while the row-level checks above may withhold individual returned rows. The
- * totals can therefore count posts the current user cannot read, such as another
- * author's draft listed in `ids`. This is deliberate: it only reveals that such a
- * post exists, as a REST collection request with `include` and `status` does.
+ * Intentionally strict: the saved post passes the same read check as every query
+ * row. When the current user may no longer read it, for example after moving it to
+ * a status they cannot read, the write stands but only its ID is returned.
*/
- return $this->prepare_output( $posts, $total, $total_pages );
+ if ( ! $this->check_read_permission( $post ) ) {
+ return array( 'id' => $post->ID );
+ }
+
+ return $this->format_post( $post, $fields );
+ }
+
+ /**
+ * Checks whether the site can move a post to the Trash.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_Post $post The post.
+ * @return bool Whether the post can be trashed.
+ */
+ private function can_trash( WP_Post $post ): bool {
+ return EMPTY_TRASH_DAYS > 0 && ( 'attachment' !== $post->post_type || MEDIA_TRASH );
}
/**
* Reads an object member of the input, such as `where` or `pagination`.
*
* Accepts what schema validation reads as an object: an array, a `stdClass`, or an
- * empty string. Only the REST run controller converts input to the schema types, so
- * callers that bypass it, such as a direct WP_Ability::execute() call, can pass any of them.
+ * empty string. WP_Ability::execute() converts input to the schema types, but
+ * WP_Ability::check_permissions() does not, so a permission callback can receive any of them.
*
* @since 7.2.0
*
@@ -841,6 +1635,25 @@ private function get_requested_statuses( array $where ): array {
return array_map( 'sanitize_key', $this->parse_list_input( $where, 'status' ) );
}
+ /**
+ * Returns the statuses the `status` filter accepts.
+ *
+ * These are the statuses that are not internal, followed by `trash`, so trashed posts can
+ * be queried by name. `trash` is never one of the statuses a query covers by default, see
+ * {@see self::normalize_statuses()}, and like every status that is not publicly viewable
+ * it requires edit access, see {@see self::can_query_status()}.
+ *
+ * @since 7.3.0
+ *
+ * @return list Post status slugs.
+ */
+ private function get_queryable_statuses(): array {
+ $statuses = array_values( get_post_stati( array( 'internal' => false ) ) );
+ $statuses[] = 'trash';
+
+ return $statuses;
+ }
+
/**
* Normalizes the statuses a query covers.
*
@@ -1215,7 +2028,7 @@ private function get_content_query_input_schema( array $post_types, array $statu
'type' => 'string',
'enum' => $statuses,
),
- 'description' => __( 'Filter readable posts by one or more post statuses. Defaults to publish, or, when `ids` or `slugs` is given, to every status the current user may query. Statuses that are not publicly viewable, other than private, require edit access.' ),
+ 'description' => __( 'Filter readable posts by one or more post statuses. Defaults to publish, or, when `ids` or `slugs` is given, to every status the current user may query. Statuses that are not publicly viewable, other than private, require edit access. Trashed posts are only covered when `trash` is requested.' ),
),
'author' => array(
'type' => 'object',
@@ -1271,6 +2084,207 @@ private function get_content_query_input_schema( array $post_types, array $statu
);
}
+ /**
+ * Returns the `data` attributes shared by the create and update input schemas.
+ *
+ * @since 7.3.0
+ *
+ * @param list $statuses Post status slugs that can be set.
+ * @return array The attribute schemas, keyed by attribute name.
+ */
+ private function get_content_write_properties( array $statuses ): array {
+ return array(
+ 'title' => array(
+ 'type' => 'string',
+ 'description' => __( 'The raw post title. Only supported for post types that support titles.' ),
+ ),
+ 'content' => array(
+ 'type' => 'string',
+ 'description' => __( 'The raw post content, such as block markup. Only supported for post types that support the editor.' ),
+ ),
+ 'excerpt' => array(
+ 'type' => 'string',
+ 'description' => __( 'The raw post excerpt. Only supported for post types that support excerpts.' ),
+ ),
+ 'status' => array(
+ 'type' => 'string',
+ 'enum' => $statuses,
+ 'description' => __( 'The post status. A status that makes the post visible, such as publish, future, or private, requires the capability to publish posts of the type. A published post with a future date is scheduled, and a scheduled post with a past date is published.' ),
+ ),
+ 'slug' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'description' => __( 'The post slug. It is sanitized as a post slug is, and made unique among the posts of the type that share its parent.' ),
+ ),
+ 'date' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'minProperties' => 1,
+ 'properties' => array(
+ 'site' => array(
+ 'type' => 'string',
+ 'format' => 'date-time',
+ 'description' => __( "The publication date, in ISO 8601 format. Read in the site's timezone unless it has a UTC offset." ),
+ ),
+ 'gmt' => array(
+ 'type' => 'string',
+ 'format' => 'date-time',
+ 'description' => __( 'The publication date, in ISO 8601 format. Read as GMT unless it has a UTC offset.' ),
+ ),
+ ),
+ 'description' => __( 'The publication date. When both `site` and `gmt` are given, `site` is used.' ),
+ ),
+ 'author' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ 'description' => __( 'The user ID of the author. Naming a user other than the current one requires the capability to edit the posts of others. Only supported for post types that support authors.' ),
+ ),
+ 'parent' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ 'description' => __( 'The parent post ID: a readable post of the same type, or 0 for a top-level post. Only supported for hierarchical post types.' ),
+ ),
+ );
+ }
+
+ /**
+ * Builds the `where` schema that names one post, shared by the update and delete abilities.
+ *
+ * @since 7.3.0
+ *
+ * @param list $post_types Exposed post type names.
+ * @param string $description The description of `where`.
+ * @return array The `where` JSON Schema.
+ */
+ private function get_content_where_post_schema( array $post_types, string $description ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'type', 'id' ),
+ 'properties' => array(
+ 'type' => array(
+ 'type' => 'string',
+ 'enum' => $post_types,
+ 'description' => __( 'The post type of the post.' ),
+ ),
+ 'id' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ 'description' => __( 'The post ID.' ),
+ ),
+ ),
+ 'description' => $description,
+ );
+ }
+
+ /**
+ * Builds the input schema for the `core/content-create` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $post_types Exposed post type names.
+ * @param list $statuses Post status slugs that can be set.
+ * @return array The input JSON Schema.
+ */
+ private function get_content_create_input_schema( array $post_types, array $statuses ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'data' ),
+ 'properties' => array(
+ 'data' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'type' ),
+ 'properties' => array_merge(
+ array(
+ 'type' => array(
+ 'type' => 'string',
+ 'enum' => $post_types,
+ 'description' => __( 'The post type of the post to create.' ),
+ ),
+ ),
+ $this->get_content_write_properties( $statuses )
+ ),
+ 'description' => __( 'The post to create. The status defaults to draft.' ),
+ ),
+ 'fields' => $this->get_fields_input_schema(),
+ ),
+ );
+ }
+
+ /**
+ * Builds the input schema for the `core/content-update` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $post_types Exposed post type names.
+ * @param list $statuses Post status slugs that can be set.
+ * @return array The input JSON Schema.
+ */
+ private function get_content_update_input_schema( array $post_types, array $statuses ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where', 'data' ),
+ 'properties' => array(
+ 'where' => $this->get_content_where_post_schema( $post_types, __( 'Selects the post to update, by its type and ID.' ) ),
+ 'data' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'minProperties' => 1,
+ 'properties' => $this->get_content_write_properties( $statuses ),
+ 'description' => __( 'The attributes to change. Attributes that are left out keep their stored values.' ),
+ ),
+ 'fields' => $this->get_fields_input_schema(),
+ ),
+ );
+ }
+
+ /**
+ * Builds the input schema for the `core/content-delete` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $post_types Exposed post type names.
+ * @return array The input JSON Schema.
+ */
+ private function get_content_delete_input_schema( array $post_types ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where' ),
+ 'properties' => array(
+ 'where' => $this->get_content_where_post_schema( $post_types, __( 'Selects the post to delete, by its type and ID.' ) ),
+ 'permanent' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether to delete the post permanently instead of moving it to the Trash. Defaults to false.' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Builds the output schema for the `core/content-delete` ability.
+ *
+ * @since 7.3.0
+ *
+ * @return array The output JSON Schema.
+ */
+ private function get_content_delete_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'outcome' ),
+ 'properties' => array(
+ 'outcome' => array(
+ 'type' => 'string',
+ 'description' => __( 'What happened to the post: `trashed` when it was moved to the Trash, `deleted` when it was deleted permanently.' ),
+ ),
+ ),
+ );
+ }
+
/**
* Builds the output schema of a single post, shared by all content abilities.
*
@@ -1342,7 +2356,7 @@ private function get_content_query_output_schema(): array {
* the current user may not see is reported like a missing one.
*
* The `author` field and the `author` slug filter share this rule, so the filter never
- * confirms a slug the field withholds. The post count is kept per author for the query,
+ * confirms a slug the field withholds. The post count is kept per author for the call,
* since count_user_posts() is not cached.
*
* @since 7.2.0
@@ -1769,7 +2783,7 @@ private function format_date( WP_Post $post, string $field, bool $gmt ): ?string
*/
$date = ( $gmt ? $datetime->setTimezone( new DateTimeZone( 'UTC' ) ) : $datetime )->format( 'c' );
- return rest_parse_date( $date ) ? $date : null;
+ return false !== rest_parse_date( $date ) ? $date : null;
}
/**
@@ -1833,4 +2847,63 @@ private function invalid_filter_error( string $param, string $message ): WP_Erro
)
);
}
+
+ /**
+ * Builds the error for a post that cannot be found.
+ *
+ * Returned alike for a missing post, a post of another type, and a post type that is not
+ * exposed to abilities, so it never tells which one applies.
+ *
+ * @since 7.3.0
+ *
+ * @return WP_Error The not found error.
+ */
+ private function not_found_error(): WP_Error {
+ return new WP_Error(
+ 'content_not_found',
+ __( 'The requested content was not found.' ),
+ array( 'status' => 404 )
+ );
+ }
+
+ /**
+ * Builds the error for a `data` attribute that cannot be applied.
+ *
+ * The error data maps the attribute's input path, such as `data[title]`, to the message
+ * under `params`, so callers can tell which attribute failed without parsing the
+ * translated message.
+ *
+ * @since 7.3.0
+ *
+ * @param string $attribute The attribute name, such as `title`, or `data` for the whole object.
+ * @param string $message The error message.
+ * @return WP_Error The invalid attribute error.
+ */
+ private function invalid_attribute_error( string $attribute, string $message ): WP_Error {
+ $param = 'data' === $attribute ? 'data' : "data[{$attribute}]";
+
+ return new WP_Error(
+ 'content_invalid_attribute',
+ $message,
+ array(
+ 'status' => 400,
+ 'params' => array( $param => $message ),
+ )
+ );
+ }
+
+ /**
+ * Builds the error for a delete or trash call that failed or could not be confirmed.
+ *
+ * @since 7.3.0
+ *
+ * @return WP_Error The delete failed error.
+ */
+ private function delete_failed_error(): WP_Error {
+ return new WP_Error(
+ 'content_delete_failed',
+ __( 'The post could not be deleted.' ),
+ array( 'status' => 500 )
+ );
+ }
}
diff --git a/tests/phpunit/tests/abilities-api/testcase-content-write-ability.php b/tests/phpunit/tests/abilities-api/testcase-content-write-ability.php
new file mode 100644
index 0000000000000..bab079369a663
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/testcase-content-write-ability.php
@@ -0,0 +1,422 @@
+
+ */
+ protected const CONTENT_ABILITIES = array( 'core/content-query', 'core/content-create', 'core/content-update', 'core/content-delete' );
+
+ /**
+ * An ID that no post or user has.
+ *
+ * @since 7.3.0
+ *
+ * @var int
+ */
+ protected const MISSING_ID = 987654321;
+
+ /**
+ * The roles of the matrix tests.
+ *
+ * @since 7.3.0
+ *
+ * @var list
+ */
+ protected const ROLES = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
+
+ /**
+ * The statuses of the matrix posts. `trash_` is a post trashed from ``.
+ *
+ * @since 7.3.0
+ *
+ * @var list
+ */
+ protected const MATRIX_STATUSES = array( 'draft', 'pending', 'publish', 'future', 'private', 'trash_draft', 'trash_publish' );
+
+ /**
+ * Shared user IDs keyed by role or fixture name.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected static $user_ids = array();
+
+ /**
+ * Shared post IDs keyed by fixture name.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected static $post_ids = array();
+
+ /**
+ * Forgets the shared fixtures, so a test class never reads the ones of another.
+ *
+ * @since 7.3.0
+ */
+ public static function wpTearDownAfterClass(): void {
+ self::$user_ids = array();
+ self::$post_ids = array();
+ }
+
+ /**
+ * Unregisters the content abilities and registers the content category.
+ *
+ * @since 7.3.0
+ */
+ public function set_up(): void {
+ parent::set_up();
+
+ foreach ( self::CONTENT_ABILITIES as $ability_name ) {
+ if ( wp_has_ability( $ability_name ) ) {
+ wp_unregister_ability( $ability_name );
+ }
+ }
+
+ if ( ! wp_has_ability_category( 'content' ) ) {
+ global $wp_current_filter;
+ $wp_current_filter[] = 'wp_abilities_api_categories_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it.
+ wp_register_ability_category(
+ 'content',
+ array(
+ 'label' => 'Content',
+ 'description' => 'Content.',
+ )
+ );
+ }
+ }
+
+ /**
+ * Unregisters the content abilities and the category, and resets the post types.
+ *
+ * @since 7.3.0
+ */
+ public function tear_down(): void {
+ foreach ( self::CONTENT_ABILITIES as $ability_name ) {
+ if ( wp_has_ability( $ability_name ) ) {
+ wp_unregister_ability( $ability_name );
+ }
+ }
+
+ if ( wp_has_ability_category( 'content' ) ) {
+ wp_unregister_ability_category( 'content' );
+ }
+
+ /*
+ * A test may turn off `show_in_abilities` on `post` and `page`, and the next class's
+ * wpSetUpBeforeClass() runs before the next set_up() resets the post types.
+ */
+ $this->reset_post_types();
+
+ parent::tear_down();
+ }
+
+ /**
+ * Registers the content abilities inside a faked init action.
+ *
+ * @since 7.3.0
+ */
+ protected function register_abilities(): void {
+ global $wp_current_filter;
+ $wp_current_filter[] = 'wp_abilities_api_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it.
+ ( new WP_Abilities_Content() )->register();
+ }
+
+ /**
+ * Registers the content abilities and returns the callbacks of the ability under test.
+ *
+ * The callbacks call private methods, so tests that skip input validation or the
+ * permission check capture them from the registration arguments.
+ *
+ * @since 7.3.0
+ *
+ * @return array The permission and execute callbacks, keyed by argument name.
+ */
+ protected function get_ability_callbacks(): array {
+ $ability = static::ABILITY;
+ $callbacks = array();
+
+ add_filter(
+ 'wp_register_ability_args',
+ static function ( array $args, string $name ) use ( &$callbacks, $ability ): array {
+ if ( $ability === $name ) {
+ $callbacks = array(
+ 'permission_callback' => $args['permission_callback'],
+ 'execute_callback' => $args['execute_callback'],
+ );
+ }
+
+ return $args;
+ },
+ 10,
+ 2
+ );
+
+ $this->register_abilities();
+
+ $this->assertArrayHasKey( 'execute_callback', $callbacks, "The {$ability} ability should be registered with callbacks." );
+
+ return $callbacks;
+ }
+
+ /**
+ * Runs the registered ability under test with the given input.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input.
+ * @return mixed The ability result.
+ */
+ protected function run_ability( $input ) {
+ $ability = static::ABILITY;
+
+ $this->assertTrue( wp_has_ability( $ability ), "The {$ability} ability should be registered." );
+
+ return wp_get_ability( $ability )->execute( $input );
+ }
+
+ /**
+ * Logs in as the shared user with the given role or fixture name.
+ *
+ * @since 7.3.0
+ *
+ * @param string $role The role or fixture name.
+ */
+ protected function login_as( string $role ): void {
+ wp_set_current_user( self::$user_ids[ $role ] );
+ }
+
+ /**
+ * Takes a snapshot of the stored content: the number of posts per type and status,
+ * revisions included, the number of meta rows and term relationships, and, when a post
+ * is given, the row and meta of that post.
+ *
+ * @since 7.3.0
+ *
+ * @param int|null $post_id Optional. The post ID. Default null.
+ * @return array The snapshot.
+ */
+ protected function snapshot( ?int $post_id = null ): array {
+ global $wpdb;
+
+ $snapshot = array(
+ 'posts' => $wpdb->get_results( "SELECT post_type, post_status, COUNT(*) AS total FROM {$wpdb->posts} GROUP BY post_type, post_status ORDER BY post_type, post_status", ARRAY_A ),
+ 'meta' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->postmeta}" ),
+ 'terms' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->term_relationships}" ),
+ );
+
+ if ( null !== $post_id ) {
+ $snapshot['post'] = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id ), ARRAY_A );
+ $snapshot['post_meta'] = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d ORDER BY meta_id", $post_id ), ARRAY_A );
+ }
+
+ return $snapshot;
+ }
+
+ /**
+ * Asserts that a result is an error with the given code and status.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $code The expected error code.
+ * @param int $status The expected error status.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_error( $result, string $code, int $status, string $context ): void {
+ $this->assertWPError( $result, "{$context}: the call should fail." );
+ $this->assertSame( $code, $result->get_error_code(), "{$context}: the error code should be {$code}." );
+
+ $data = $result->get_error_data();
+ $this->assertIsArray( $data, "{$context}: the error should carry data." );
+ $this->assertSame( $status, $data['status'] ?? null, "{$context}: the error status should be {$status}." );
+ }
+
+ /**
+ * Asserts that a result is the error of a call that the permission callback refused.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_refused( $result, string $context ): void {
+ $this->assertWPError( $result, "{$context}: the call should fail." );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), "{$context}: the permission callback should refuse the call." );
+ }
+
+ /**
+ * Asserts that a result is the invalid attribute error for the given attribute.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $attribute The attribute name.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_invalid_attribute( $result, string $attribute, string $context ): void {
+ $this->assert_error( $result, 'content_invalid_attribute', 400, $context );
+
+ $message = $result->get_error_message();
+ $this->assertNotSame( '', $message, "{$context}: the message should give the reason." );
+ $this->assertSame( array( "data[{$attribute}]" => $message ), $result->get_error_data()['params'] ?? array(), "{$context}: the params should hold only the input path of the attribute, with the reason." );
+ }
+
+ /**
+ * Asserts that a result is the not-found error.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_not_found( $result, string $context ): void {
+ $this->assert_error( $result, 'content_not_found', 404, $context );
+ $this->assertSame( 'The requested content was not found.', $result->get_error_message(), "{$context}: the message should be the not-found message." );
+ }
+
+ /**
+ * Removes the `description` keywords of a schema at every depth.
+ *
+ * @since 7.3.0
+ *
+ * @param array $schema The schema.
+ * @return array The schema without descriptions.
+ */
+ protected function strip_descriptions( array $schema ): array {
+ unset( $schema['description'] );
+ foreach ( $schema as $key => $value ) {
+ if ( is_array( $value ) ) {
+ $schema[ $key ] = $this->strip_descriptions( $value );
+ }
+ }
+
+ return $schema;
+ }
+
+ /**
+ * Returns the forms a `where` can take in input that was not prepared.
+ *
+ * @return array The type of the ID, and
+ * whether `where` is an object.
+ */
+ public static function data_unprepared_where_forms(): array {
+ return array(
+ 'integer ID' => array( 'integer', false ),
+ 'integer string ID' => array( 'string', false ),
+ 'float ID' => array( 'float', false ),
+ 'where that is an object' => array( 'integer', true ),
+ );
+ }
+
+ /**
+ * Builds a `where` for a post in one of the forms of unprepared input.
+ *
+ * @since 7.3.0
+ *
+ * @param int $post_id The post ID.
+ * @param string $id_type The type to send the ID as.
+ * @param bool $as_object Whether to send `where` as an object.
+ * @return array|stdClass The `where`.
+ */
+ protected function build_unprepared_where( int $post_id, string $id_type, bool $as_object ) {
+ $id = $post_id;
+ settype( $id, $id_type );
+
+ $where = array(
+ 'type' => get_post_type( $post_id ),
+ 'id' => $id,
+ );
+
+ return $as_object ? (object) $where : $where;
+ }
+
+ /**
+ * Returns posts that cannot be reached as a `post`.
+ *
+ * @return array The posts, as fixture names.
+ */
+ public static function data_posts_that_are_not_posts(): array {
+ return array(
+ 'revision' => array( 'revision' ),
+ 'attachment' => array( 'attachment' ),
+ 'page' => array( 'admin_page' ),
+ 'missing' => array( 'missing' ),
+ 'reusable block' => array( 'reusable_block' ),
+ 'template' => array( 'template' ),
+ 'menu item' => array( 'menu_item' ),
+ 'autosave' => array( 'autosave' ),
+ );
+ }
+
+ /**
+ * Returns statuses that can never be set.
+ *
+ * @return array The statuses.
+ */
+ public static function data_statuses_that_can_never_be_set(): array {
+ return array(
+ 'trash' => array( 'trash' ),
+ 'auto-draft' => array( 'auto-draft' ),
+ 'inherit' => array( 'inherit' ),
+ 'unregistered' => array( 'cw_unregistered' ),
+ 'request-pending' => array( 'request-pending' ),
+ 'request-confirmed' => array( 'request-confirmed' ),
+ 'upper case' => array( 'PUBLISH' ),
+ 'trailing space' => array( 'publish ' ),
+ 'empty string' => array( '' ),
+ 'comma-joined list' => array( 'draft,publish' ),
+ );
+ }
+
+ /**
+ * Returns authors that a user without `edit_others_posts` may not name.
+ *
+ * @return array The authors, as fixture names.
+ */
+ public static function data_authors_named_without_edit_others_posts(): array {
+ return array(
+ 'existing user' => array( 'editor' ),
+ 'missing user' => array( 'missing' ),
+ );
+ }
+
+ /**
+ * Returns date values without a usable value for a direct call.
+ *
+ * @return array}> The dates.
+ */
+ public static function data_dates_without_a_usable_value(): array {
+ return array(
+ 'empty date' => array( array() ),
+ 'site date that cannot be parsed' => array( array( 'site' => 'not a date' ) ),
+ 'GMT date that cannot be parsed' => array( array( 'gmt' => 'not a date' ) ),
+ );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php
index 0a6b9fd447093..ead4da1b29c2d 100644
--- a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php
@@ -11,6 +11,15 @@
*/
class Tests_Abilities_API_WpRegisterCoreContentAbility extends WP_UnitTestCase {
+ /**
+ * The content abilities, which every test unregisters before and after it runs.
+ *
+ * @since 7.3.0
+ *
+ * @var list
+ */
+ private const CONTENT_ABILITIES = array( 'core/content-query', 'core/content-create', 'core/content-update', 'core/content-delete' );
+
/**
* Globals that rendering a post changes: the global post and the globals that
* setup_postdata() populates.
@@ -142,8 +151,10 @@ public static function wpSetUpBeforeClass( $factory ): void {
public function set_up(): void {
parent::set_up();
- if ( wp_has_ability( 'core/content-query' ) ) {
- wp_unregister_ability( 'core/content-query' );
+ foreach ( self::CONTENT_ABILITIES as $ability_name ) {
+ if ( wp_has_ability( $ability_name ) ) {
+ wp_unregister_ability( $ability_name );
+ }
}
if ( ! wp_has_ability_category( 'content' ) ) {
@@ -160,13 +171,15 @@ public function set_up(): void {
}
/**
- * Removes the ability and its category, and resets the post types, after each test.
+ * Removes the content abilities and their category, and resets the post types, after each test.
*
* @since 7.2.0
*/
public function tear_down(): void {
- if ( wp_has_ability( 'core/content-query' ) ) {
- wp_unregister_ability( 'core/content-query' );
+ foreach ( self::CONTENT_ABILITIES as $ability_name ) {
+ if ( wp_has_ability( $ability_name ) ) {
+ wp_unregister_ability( $ability_name );
+ }
}
if ( wp_has_ability_category( 'content' ) ) {
@@ -186,7 +199,7 @@ public function tear_down(): void {
}
/**
- * Registers the core/content-query ability inside a faked init action.
+ * Registers the content abilities inside a faked init action.
*
* @since 7.2.0
*/
@@ -356,7 +369,7 @@ public function test_input_schema_models_a_flat_where(): void {
$this->assertTrue( $status['uniqueItems'], 'The status filter should reject duplicate statuses.' );
$this->assertSame( 1, $status['minItems'], 'The status filter should require at least one status.' );
$this->assertSame( 'string', $status['items']['type'], 'The status filter should contain status names.' );
- $this->assertSameSets( array_values( get_post_stati( array( 'internal' => false ) ) ), $status['items']['enum'], 'The status filter should expose the statuses that are not internal.' );
+ $this->assertSame( array_merge( array_values( get_post_stati( array( 'internal' => false ) ) ), array( 'trash' ) ), $status['items']['enum'], 'The status filter should expose the statuses that are not internal, then trash.' );
$author = $where['properties']['author'];
@@ -5611,6 +5624,41 @@ public function test_malformed_date_is_null( string $field, string $column ): vo
$this->assertNull( $result['items'][0][ $object ][ $key ], 'A malformed date should be null.' );
}
+ /**
+ * A stored date at the Unix epoch is returned: a timestamp of zero is a date, not a
+ * date that could not be parsed.
+ *
+ * @ticket 66706
+ * @dataProvider data_date_fields
+ * @since 7.3.0
+ *
+ * @param string $field The field path to request, such as `date.site`.
+ * @param string $column The cached post column to set to the Unix epoch.
+ */
+ public function test_date_at_the_unix_epoch_is_returned( string $field, string $column ): void {
+ $this->login_as( 'administrator' );
+ $this->register_ability();
+
+ $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) );
+
+ $this->replace_cached_post_date_columns( $post_id, array( $column => '1970-01-01 00:00:00' ) );
+
+ list( $object, $key ) = explode( '.', $field );
+
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'ids' => array( $post_id ),
+ ),
+ 'fields' => array( 'id', $field ),
+ )
+ );
+
+ $this->assertIsArray( $result, 'A date at the Unix epoch should pass output validation.' );
+ $this->assertSame( '1970-01-01T00:00:00+00:00', $result['items'][0][ $object ][ $key ] ?? null, 'A date at the Unix epoch should be returned.' );
+ }
+
/**
* Returns `where.author` values that are not an object holding an ID or a slug: values
* that are not objects, empty values, and objects with an unknown property.
@@ -6319,12 +6367,6 @@ public static function data_where_filters_with_statuses_that_cannot_be_queried()
'status' => array( 'unregistered_status' ),
),
),
- 'trash' => array(
- 'where' => array(
- 'type' => 'post',
- 'status' => array( 'trash' ),
- ),
- ),
'inherit' => array(
'where' => array(
'type' => 'post',
@@ -6750,4 +6792,235 @@ public function test_author_filter_names_authors_who_are_not_site_members(): voi
$this->assertIsArray( $by_id, 'An author with published posts on the site should be filterable by ID without being a member.' );
$this->assertSame( array( $post_id ), wp_list_pluck( $by_id['items'], 'id' ), 'The ID should return the author\'s posts on the site.' );
}
+
+ /**
+ * Creates a post in the Trash.
+ *
+ * @since 7.3.0
+ *
+ * @param string $author The author, as a role or fixture name.
+ * @return int The post ID.
+ */
+ private function create_trashed_post( string $author ): int {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids[ $author ],
+ 'post_status' => 'publish',
+ )
+ );
+ wp_trash_post( $post_id );
+
+ $this->assertSame( 'trash', get_post_status( $post_id ), 'Precondition: the post should be in the Trash.' );
+
+ return $post_id;
+ }
+
+ /**
+ * Runs a query and returns the IDs of the items.
+ *
+ * @since 7.3.0
+ *
+ * @param array $where The `where` filters.
+ * @return list The IDs of the returned items.
+ */
+ private function query_ids( array $where ): array {
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => $where,
+ 'fields' => array( 'id' ),
+ )
+ );
+
+ $this->assertIsArray( $result, 'The query should succeed.' );
+
+ return wp_list_pluck( $result['items'], 'id' );
+ }
+
+ /**
+ * `trash` requested by name returns the trashed posts to roles that may edit them.
+ *
+ * @ticket 66706
+ * @dataProvider data_roles_with_edit_access_to_other_users_posts
+ * @since 7.3.0
+ *
+ * @param string $role The role to query as.
+ */
+ public function test_trash_requested_by_name_returns_trashed_posts( string $role ): void {
+ $post_id = $this->create_trashed_post( 'author' );
+
+ $this->login_as( $role );
+ $this->register_ability();
+
+ $this->assertSame(
+ array( $post_id ),
+ $this->query_ids(
+ array(
+ 'type' => 'post',
+ 'status' => array( 'trash' ),
+ )
+ ),
+ 'The trashed post should be returned.'
+ );
+ }
+
+ /**
+ * `trash` can be requested next to another status.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_trash_can_be_requested_next_to_another_status(): void {
+ $post_id = $this->create_trashed_post( 'author' );
+
+ $this->login_as( 'editor' );
+ $this->register_ability();
+
+ $this->assertSameSets(
+ array( $post_id, self::$post_ids['published'] ),
+ $this->query_ids(
+ array(
+ 'type' => 'post',
+ 'ids' => array( $post_id, self::$post_ids['published'] ),
+ 'status' => array( 'publish', 'trash' ),
+ )
+ ),
+ 'The trashed and the published post should be returned.'
+ );
+ }
+
+ /**
+ * A query without a status does not cover `trash`, also not when it lists slugs.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slugs_without_a_status_do_not_cover_trashed_posts(): void {
+ $post_id = $this->create_trashed_post( 'author' );
+
+ $this->login_as( 'administrator' );
+ $this->register_ability();
+
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'slugs' => array( get_post( $post_id )->post_name ),
+ ),
+ 'fields' => array( 'id' ),
+ )
+ );
+
+ $this->assertSame( self::EMPTY_RESULT, $result, 'A query by slug without a status should neither return nor count a trashed post.' );
+ }
+
+ /**
+ * A query without a status does not cover `trash`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_query_without_a_status_does_not_cover_trashed_posts(): void {
+ $post_id = $this->create_trashed_post( 'administrator' );
+
+ $this->login_as( 'administrator' );
+ $this->register_ability();
+
+ $this->assertNotContains( $post_id, $this->query_ids( array( 'type' => 'post' ) ), 'A query without a status should not return a trashed post.' );
+ }
+
+ /**
+ * Querying `trash` needs `edit_posts`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_trash_needs_edit_posts(): void {
+ $this->create_trashed_post( 'author' );
+
+ $this->login_as( 'subscriber' );
+ $this->register_ability();
+
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'status' => array( 'trash' ),
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'A subscriber should not be able to query the Trash.' );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The permission callback should refuse a subscriber.' );
+ }
+
+ /**
+ * Returns roles that may query the Trash but only edit their own posts.
+ *
+ * @return array The roles.
+ */
+ public static function data_roles_that_edit_only_their_own_trashed_posts(): array {
+ return array(
+ 'author' => array( 'author_secondary' ),
+ 'contributor' => array( 'contributor' ),
+ );
+ }
+
+ /**
+ * Trashed rows pass the per-post read check: a role that edits only its own posts gets its
+ * own trashed post and not the trashed post of another user.
+ *
+ * @ticket 66706
+ * @dataProvider data_roles_that_edit_only_their_own_trashed_posts
+ * @since 7.3.0
+ *
+ * @param string $role The role to query as.
+ */
+ public function test_trash_returns_only_the_trashed_posts_the_user_may_read( string $role ): void {
+ $own_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids[ $role ],
+ 'post_status' => 'draft',
+ )
+ );
+ $other_id = $this->create_trashed_post( 'author' );
+ wp_trash_post( $own_id );
+
+ $this->login_as( $role );
+ $this->register_ability();
+
+ $this->assertSame(
+ array( $own_id ),
+ $this->query_ids(
+ array(
+ 'type' => 'post',
+ 'ids' => array( $own_id, $other_id ),
+ 'status' => array( 'trash' ),
+ )
+ ),
+ 'Only the own trashed post should be returned.'
+ );
+ }
+
+ /**
+ * Other internal statuses are still rejected.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_other_internal_statuses_are_still_rejected(): void {
+ $this->login_as( 'administrator' );
+ $this->register_ability();
+
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'status' => array( 'auto-draft' ),
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'An auto-draft query should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject auto-draft.' );
+ }
}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentCreateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentCreateAbility.php
new file mode 100644
index 0000000000000..2aa37a2828180
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentCreateAbility.php
@@ -0,0 +1,2577 @@
+ $factory->user->create( array( 'role' => 'administrator' ) ),
+ 'editor' => $factory->user->create( array( 'role' => 'editor' ) ),
+ 'author' => $factory->user->create( array( 'role' => 'author' ) ),
+ 'contributor' => $factory->user->create( array( 'role' => 'contributor' ) ),
+ 'subscriber' => $factory->user->create( array( 'role' => 'subscriber' ) ),
+ 'page_writer' => $factory->user->create( array( 'role' => 'subscriber' ) ),
+ 'publisher' => $factory->user->create( array( 'role' => 'contributor' ) ),
+ );
+
+ // A user who may create pages but not read the drafts of other users.
+ get_userdata( self::$user_ids['page_writer'] )->add_cap( 'edit_pages' );
+
+ // A user who may publish posts but not edit published posts.
+ get_userdata( self::$user_ids['publisher'] )->add_cap( 'publish_posts' );
+
+ self::$post_ids = array(
+ 'published_post' => $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ 'post_name' => 'shared-slug',
+ )
+ ),
+ 'published_page' => $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ ),
+ 'other_parent_page' => $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ ),
+ 'editor_draft_page' => $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ )
+ ),
+ );
+
+ self::$post_ids['child_page'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_parent' => self::$post_ids['published_page'],
+ 'post_name' => 'child',
+ )
+ );
+
+ // A page of the administrator in the Trash.
+ self::$post_ids['trashed_page'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ );
+ wp_trash_post( self::$post_ids['trashed_page'] );
+
+ $revisioned_id = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_content' => 'First version.',
+ )
+ );
+ wp_update_post(
+ array(
+ 'ID' => $revisioned_id,
+ 'post_content' => 'Second version.',
+ )
+ );
+ self::$post_ids['page_revision'] = (int) array_key_first( wp_get_post_revisions( $revisioned_id ) );
+ }
+
+ /**
+ * Returns the post a create call returned.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @return WP_Post|null The post with the returned ID, or null when there is none.
+ */
+ private function get_created_post( $result ): ?WP_Post {
+ $this->assertIsArray( $result, 'The create call should succeed.' );
+ $this->assertArrayHasKey( 'id', $result, 'The created post should be returned with its ID.' );
+
+ return get_post( $result['id'] );
+ }
+
+ /**
+ * Registers a post type exposed to abilities with the given supported features.
+ *
+ * @since 7.3.0
+ *
+ * @param string $name The post type name.
+ * @param list $supports The supported features.
+ */
+ private function register_exposed_post_type( string $name, array $supports ): void {
+ register_post_type(
+ $name,
+ array(
+ 'public' => true,
+ 'show_in_abilities' => true,
+ 'supports' => $supports,
+ )
+ );
+ }
+
+ /**
+ * The ability is registered in the content category with its label and annotations.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_registers_the_ability(): void {
+ $this->register_abilities();
+
+ $ability = wp_get_ability( self::ABILITY );
+
+ $this->assertInstanceOf( WP_Ability::class, $ability, 'The core/content-create ability should be registered.' );
+ $this->assertSame( 'Create Content', $ability->get_label(), 'The ability should have its label.' );
+ $this->assertSame( 'content', $ability->get_category(), 'The ability should use the content category.' );
+ $this->assertTrue( $ability->get_meta_item( 'public', false ), 'The ability should be marked public.' );
+
+ $annotations = $ability->get_meta_item( 'annotations', array() );
+ $this->assertFalse( $annotations['readonly'], 'The ability should not be marked read-only.' );
+ $this->assertFalse( $annotations['destructive'], 'The ability should not be marked destructive.' );
+ $this->assertFalse( $annotations['idempotent'], 'The ability should not be marked idempotent.' );
+ }
+
+ /**
+ * The ability is not registered when no post type is exposed to abilities.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_is_not_registered_without_exposed_post_types(): void {
+ foreach ( array( 'post', 'page' ) as $post_type ) {
+ get_post_type_object( $post_type )->show_in_abilities = false;
+ }
+
+ $this->register_abilities();
+
+ $this->assertFalse( wp_has_ability( self::ABILITY ), 'The create ability should not be registered without an exposed post type.' );
+ }
+
+ /**
+ * The input schema takes `data`, with the post type and the allowed attributes, and `fields`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_input_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The create ability should be registered.' );
+
+ $schema = wp_get_ability( self::ABILITY )->get_input_schema();
+
+ $this->assertSame( 'object', $schema['type'], 'The input should be an object.' );
+ $this->assertFalse( $schema['additionalProperties'], 'The input should reject unknown keys.' );
+ $this->assertSame( array( 'data' ), $schema['required'], 'The input should require data.' );
+ $this->assertSame( array( 'data', 'fields' ), array_keys( $schema['properties'] ), 'The input should take data and fields.' );
+
+ $data = $schema['properties']['data'];
+
+ $this->assertSame( 'object', $data['type'], 'The data should be an object.' );
+ $this->assertFalse( $data['additionalProperties'], 'The data should reject unknown keys.' );
+ $this->assertSame( array( 'type' ), $data['required'], 'The data should require the post type.' );
+ $this->assertSame( array( 'type', 'title', 'content', 'excerpt', 'status', 'slug', 'date', 'author', 'parent' ), array_keys( $data['properties'] ), 'The data should take the post type and the allowed attributes.' );
+
+ $properties = $data['properties'];
+
+ $this->assertSame( 'string', $properties['type']['type'], 'The post type should be a string.' );
+ $this->assertSameSets( array( 'post', 'page' ), $properties['type']['enum'], 'The post type should list the exposed post types.' );
+ $this->assertSame( 'string', $properties['title']['type'], 'The title should be a string.' );
+ $this->assertSame( 'string', $properties['content']['type'], 'The content should be a string.' );
+ $this->assertSame( 'string', $properties['excerpt']['type'], 'The excerpt should be a string.' );
+ $this->assertSame( 'string', $properties['status']['type'], 'The status should be a string.' );
+ $this->assertSame( array( 'publish', 'future', 'draft', 'pending', 'private' ), $properties['status']['enum'], 'The status should list the statuses that are not internal.' );
+ $this->assertSame( 'string', $properties['slug']['type'], 'The slug should be a string.' );
+ $this->assertSame( 1, $properties['slug']['minLength'], 'The slug should not be empty.' );
+ $this->assertSame( 'integer', $properties['author']['type'], 'The author should be an integer.' );
+ $this->assertSame( 1, $properties['author']['minimum'], 'The author should be at least 1.' );
+ $this->assertSame( 'integer', $properties['parent']['type'], 'The parent should be an integer.' );
+ $this->assertSame( 0, $properties['parent']['minimum'], 'The parent should be at least 0.' );
+
+ $date = $properties['date'];
+
+ $this->assertSame( 'object', $date['type'], 'The date should be an object.' );
+ $this->assertFalse( $date['additionalProperties'], 'The date should reject unknown keys.' );
+ $this->assertSame( 1, $date['minProperties'], 'The date should hold at least one value.' );
+ $this->assertSame( array( 'site', 'gmt' ), array_keys( $date['properties'] ), 'The date should take a site and a GMT value.' );
+ $this->assertSame( 'string', $date['properties']['site']['type'], 'The site date should be a string.' );
+ $this->assertSame( 'date-time', $date['properties']['site']['format'], 'The site date should be a date-time.' );
+ $this->assertSame( 'string', $date['properties']['gmt']['type'], 'The GMT date should be a string.' );
+ $this->assertSame( 'date-time', $date['properties']['gmt']['format'], 'The GMT date should be a date-time.' );
+
+ $this->assertTrue( wp_has_ability( 'core/content-query' ), 'The query ability should be registered next to the create ability.' );
+
+ $query_schema = wp_get_ability( 'core/content-query' )->get_input_schema();
+
+ $this->assertSame(
+ $this->strip_descriptions( $query_schema['properties']['fields'] ),
+ $this->strip_descriptions( $schema['properties']['fields'] ),
+ 'The fields should be the same list as the fields of the query.'
+ );
+ }
+
+ /**
+ * The output is one post item, the same object as an item of the query.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_output_schema_is_a_query_item(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The create ability should be registered.' );
+
+ $schema = wp_get_ability( self::ABILITY )->get_output_schema();
+ $item = wp_get_ability( 'core/content-query' )->get_output_schema()['properties']['items']['items'];
+
+ $this->assertSame( 'object', $schema['type'], 'The output should be an object.' );
+ $this->assertFalse( $schema['additionalProperties'], 'The output should not take unknown keys.' );
+ $this->assertSame( array( 'id' ), $schema['required'], 'The output should always hold the ID.' );
+ $this->assertSame( $this->strip_descriptions( $item ), $this->strip_descriptions( $schema ), 'The output should be the same object as a query item.' );
+ }
+
+ /**
+ * The schema enums are built from the site when the ability is registered.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_schema_enums_list_the_exposed_post_types_and_registered_statuses(): void {
+ $this->register_exposed_post_type( 'cw_book', array( 'title' ) );
+ register_post_type( 'cw_hidden', array( 'public' => true ) );
+ register_post_status(
+ 'cw_archived',
+ array(
+ 'label' => 'Archived',
+ 'public' => true,
+ )
+ );
+
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The create ability should be registered.' );
+
+ $properties = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties'];
+
+ $this->assertSameSets( array( 'post', 'page', 'cw_book' ), $properties['type']['enum'], 'The post type should list every exposed post type and no other.' );
+ $this->assertSameSets( array_values( get_post_stati( array( 'internal' => false ) ) ), $properties['status']['enum'], 'The status should list every registered status that is not internal.' );
+ $this->assertContains( 'cw_archived', $properties['status']['enum'], 'The status should list a custom status.' );
+ }
+
+ /**
+ * A post created with only a type and a title is a draft, returned in the default fields.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_creates_a_draft_with_the_default_fields(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Launch notes',
+ ),
+ )
+ );
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSameSets( array( 'id', 'type', 'status', 'date', 'slug', 'title' ), array_keys( $result ), 'The default fields should be returned.' );
+ $this->assertSame( $post->ID, $result['id'], 'The ID should be the ID of the new post.' );
+ $this->assertSame( 'post', $result['type'], 'The type should be post.' );
+ $this->assertSame( 'draft', $result['status'], 'The post should be a draft.' );
+ $this->assertSameSets( array( 'site', 'gmt' ), array_keys( $result['date'] ), 'The date should be given in site time and GMT.' );
+ $this->assertNotFalse( rest_parse_date( $result['date']['site'] ), 'The site date should be a date-time.' );
+ $this->assertNotFalse( rest_parse_date( $result['date']['gmt'] ), 'The GMT date should be a date-time.' );
+ $this->assertSame( '', $result['slug'], 'A draft without a slug should have an empty slug.' );
+ $this->assertSame( array( 'rendered' => 'Launch notes' ), $result['title'], 'The title should be returned rendered.' );
+ $this->assertSame( 'Launch notes', $post->post_title, 'The title should be stored.' );
+ }
+
+ /**
+ * A published child page is returned in the chosen fields.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_creates_a_published_child_page_with_chosen_fields(): void {
+ $this->set_permalink_structure( '/%postname%/' );
+
+ $parent_id = self::factory()->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_name' => 'products',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'page',
+ 'title' => 'Pricing',
+ 'content' => "\nPlans start at 9 euro per month.
\n",
+ 'status' => 'publish',
+ 'parent' => $parent_id,
+ 'slug' => 'pricing',
+ ),
+ 'fields' => array( 'status', 'link', 'title.rendered', 'content.rendered', 'parent' ),
+ )
+ );
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSameSets( array( 'id', 'status', 'link', 'title', 'content', 'parent' ), array_keys( $result ), 'The chosen fields should be returned.' );
+ $this->assertSame( $post->ID, $result['id'], 'The ID should be the ID of the new page.' );
+ $this->assertSame( 'publish', $result['status'], 'The page should be published.' );
+ $this->assertSame( home_url( '/products/pricing/' ), $result['link'], 'The link should include the parent.' );
+ $this->assertSame( array( 'rendered' => 'Pricing' ), $result['title'], 'The title should be returned rendered.' );
+ $this->assertSame( $parent_id, $result['parent'], 'The parent should be returned.' );
+
+ // The rendered markup comes from the regular content filters, as for any query item.
+ $this->assertSame( $this->query_item( 'page', $post->ID, array( 'content.rendered' ) )['content'], $result['content'], 'The content should be rendered as the query renders it.' );
+ $this->assertStringContainsString( 'Plans start at 9 euro per month.
', $result['content']['rendered'], 'The rendered content should hold the paragraph.' );
+ }
+
+ /**
+ * Returns the item that core/content-query gives for one post and the given fields.
+ *
+ * @since 7.3.0
+ *
+ * @param string $type The post type.
+ * @param int $post_id The post ID.
+ * @param list $fields The fields.
+ * @return array The query item.
+ */
+ private function query_item( string $type, int $post_id, array $fields ): array {
+ $this->assertTrue( wp_has_ability( 'core/content-query' ), 'The query ability should be registered.' );
+
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => $type,
+ 'ids' => array( $post_id ),
+ ),
+ 'fields' => $fields,
+ )
+ );
+
+ $this->assertIsArray( $result, 'The query for the post should succeed.' );
+ $this->assertCount( 1, $result['items'], 'The query should return the post.' );
+
+ return $result['items'][0];
+ }
+
+ /**
+ * An attribute the post type does not support is an invalid attribute.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_rejects_a_parent_for_a_post_type_that_is_not_hierarchical(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Launch notes',
+ 'parent' => self::$post_ids['published_post'],
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'A parent for a post should be rejected.' );
+ $this->assertSame( 'content_invalid_attribute', $result->get_error_code(), 'The error should be the invalid attribute error.' );
+ $this->assertSame( 'The parent attribute is only supported for hierarchical post types.', $result->get_error_message(), 'The message should give the reason.' );
+ $this->assertSame( 400, $result->get_error_data()['status'], 'The status should be 400.' );
+ $this->assertSame( array( 'data[parent]' => 'The parent attribute is only supported for hierarchical post types.' ), $result->get_error_data()['params'], 'The params should give the reason for the parent.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns users that the permission callback refuses.
+ *
+ * @return array The users.
+ */
+ public static function data_users_refused_by_the_permission_callback(): array {
+ return array(
+ 'logged out' => array(
+ 'role' => null,
+ ),
+ 'subscriber' => array(
+ 'role' => 'subscriber',
+ ),
+ );
+ }
+
+ /**
+ * A logged-out user and a user without `create_posts` are refused before the ability runs.
+ *
+ * @ticket 66706
+ * @dataProvider data_users_refused_by_the_permission_callback
+ * @since 7.3.0
+ *
+ * @param string|null $role The role to log in as, or null to stay logged out.
+ */
+ public function test_permission_callback_refuses_users_who_cannot_create_posts( ?string $role ): void {
+ if ( null !== $role ) {
+ $this->login_as( $role );
+ }
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Refused',
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'The call should be refused.' );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The permission callback should refuse the call.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns inputs for which the permission callback returns false, even for an administrator.
+ *
+ * @return array The inputs.
+ */
+ public static function data_inputs_refused_by_the_permission_callback(): array {
+ return array(
+ 'no input' => array(
+ 'input' => null,
+ ),
+ 'no data' => array(
+ 'input' => array(),
+ ),
+ 'data that is a string' => array(
+ 'input' => array( 'data' => 'post' ),
+ ),
+ 'no type' => array(
+ 'input' => array( 'data' => array( 'title' => 'x' ) ),
+ ),
+ 'type that is a list' => array(
+ 'input' => array( 'data' => array( 'type' => array( 'post' ) ) ),
+ ),
+ 'type that is a number' => array(
+ 'input' => array( 'data' => array( 'type' => 1 ) ),
+ ),
+ 'unexposed type' => array(
+ 'input' => array( 'data' => array( 'type' => 'attachment' ) ),
+ ),
+ 'unregistered type' => array(
+ 'input' => array( 'data' => array( 'type' => 'cw_missing' ) ),
+ ),
+ );
+ }
+
+ /**
+ * The permission callback returns false for missing or malformed input.
+ *
+ * @ticket 66706
+ * @dataProvider data_inputs_refused_by_the_permission_callback
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_returns_false_for_malformed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should return false.' );
+ }
+
+ /**
+ * The permission callback returns true for a user who may create posts of an exposed type.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_returns_true_for_a_user_who_may_create_posts(): void {
+ $this->login_as( 'contributor' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertTrue( $permission( array( 'data' => array( 'type' => 'post' ) ) ), 'The permission callback should return true.' );
+ }
+
+ /**
+ * Returns the outcome of creating a post per role and requested status.
+ *
+ * @return array The cases.
+ */
+ public static function data_create_by_role_and_status(): array {
+ $publish_message = 'Sorry, you are not allowed to publish posts in this post type.';
+ $private_message = 'Sorry, you are not allowed to create private posts in this post type.';
+
+ return array(
+ 'administrator, no status' => array( 'administrator', null, 'draft', null ),
+ 'administrator, draft' => array( 'administrator', 'draft', 'draft', null ),
+ 'administrator, pending' => array( 'administrator', 'pending', 'pending', null ),
+ 'administrator, publish' => array( 'administrator', 'publish', 'publish', null ),
+ 'administrator, future' => array( 'administrator', 'future', 'future', null ),
+ 'administrator, private' => array( 'administrator', 'private', 'private', null ),
+ 'editor, no status' => array( 'editor', null, 'draft', null ),
+ 'editor, draft' => array( 'editor', 'draft', 'draft', null ),
+ 'editor, pending' => array( 'editor', 'pending', 'pending', null ),
+ 'editor, publish' => array( 'editor', 'publish', 'publish', null ),
+ 'editor, future' => array( 'editor', 'future', 'future', null ),
+ 'editor, private' => array( 'editor', 'private', 'private', null ),
+ 'author, no status' => array( 'author', null, 'draft', null ),
+ 'author, draft' => array( 'author', 'draft', 'draft', null ),
+ 'author, pending' => array( 'author', 'pending', 'pending', null ),
+ 'author, publish' => array( 'author', 'publish', 'publish', null ),
+ 'author, future' => array( 'author', 'future', 'future', null ),
+ 'author, private' => array( 'author', 'private', 'private', null ),
+ 'contributor, no status' => array( 'contributor', null, 'draft', null ),
+ 'contributor, draft' => array( 'contributor', 'draft', 'draft', null ),
+ 'contributor, pending' => array( 'contributor', 'pending', 'pending', null ),
+ 'contributor, publish' => array( 'contributor', 'publish', 'content_cannot_publish', $publish_message ),
+ 'contributor, future' => array( 'contributor', 'future', 'content_cannot_publish', $publish_message ),
+ 'contributor, private' => array( 'contributor', 'private', 'content_cannot_publish', $private_message ),
+ );
+ }
+
+ /**
+ * Each role may create posts in the statuses it may set, as their own author.
+ *
+ * `future`, `publish` and `private` need `publish_posts`. A scheduled post is sent with a
+ * date in the future.
+ *
+ * @ticket 66706
+ * @dataProvider data_create_by_role_and_status
+ * @since 7.3.0
+ *
+ * @param string $role The role to create as.
+ * @param string|null $status The requested status, or null to send none.
+ * @param string $expected The stored status, or the error code.
+ * @param string|null $message The error message, or null on success.
+ */
+ public function test_create_by_role_and_status( string $role, ?string $status, string $expected, ?string $message ): void {
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $data = array(
+ 'type' => 'post',
+ 'title' => 'Matrix post',
+ );
+ if ( null !== $status ) {
+ $data['status'] = $status;
+ }
+ if ( 'future' === $status ) {
+ $data['date'] = array( 'gmt' => self::FUTURE_GMT );
+ }
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => $data,
+ 'fields' => array( 'status' ),
+ )
+ );
+
+ if ( null !== $message ) {
+ $this->assert_error( $result, $expected, 403, 'Creating a post in a status the role may not set' );
+ $this->assertSame( $message, $result->get_error_message(), 'The message should name what the role may not do.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ return;
+ }
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSame( $expected, $result['status'], 'The returned status should be the stored status.' );
+ $this->assertSame( $expected, $post->post_status, 'The post should be stored in the expected status.' );
+ $this->assertSame( self::$user_ids[ $role ], (int) $post->post_author, 'The current user should be the author.' );
+ $this->assertSame( 'post', $post->post_type, 'The post should have the requested type.' );
+ }
+
+ /**
+ * A type whose `show_in_abilities` is turned off after registration cannot be created.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_type_no_longer_exposed_cannot_be_created(): void {
+ $this->login_as( 'administrator' );
+ $callbacks = $this->get_ability_callbacks();
+
+ get_post_type_object( 'post' )->show_in_abilities = false;
+
+ $before = $this->snapshot();
+ $input = array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Hidden',
+ ),
+ );
+
+ $result = $this->run_ability( $input );
+
+ $this->assertWPError( $result, 'The regular call should fail.' );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The permission callback should refuse a type that is no longer exposed.' );
+
+ $direct = $callbacks['execute_callback']( $input );
+
+ $this->assert_error( $direct, 'content_not_found', 404, 'A direct call for a type that is no longer exposed' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns direct-call inputs without an exposed post type.
+ *
+ * @return array}> The inputs.
+ */
+ public static function data_direct_inputs_without_an_exposed_type(): array {
+ return array(
+ 'no data' => array(
+ 'input' => array(),
+ ),
+ 'no type' => array(
+ 'input' => array( 'data' => array( 'title' => 'x' ) ),
+ ),
+ 'attachment' => array(
+ 'input' => array(
+ 'data' => array(
+ 'type' => 'attachment',
+ 'title' => 'x',
+ ),
+ ),
+ ),
+ 'revision' => array(
+ 'input' => array(
+ 'data' => array(
+ 'type' => 'revision',
+ 'title' => 'x',
+ ),
+ ),
+ ),
+ 'unexposed type' => array(
+ 'input' => array(
+ 'data' => array(
+ 'type' => 'cw_hidden',
+ 'title' => 'x',
+ ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Called directly, input without an exposed post type is the not-found error.
+ *
+ * @ticket 66706
+ * @dataProvider data_direct_inputs_without_an_exposed_type
+ * @since 7.3.0
+ *
+ * @param array $input The input.
+ */
+ public function test_direct_call_without_an_exposed_type_is_not_found( array $input ): void {
+ register_post_type( 'cw_hidden', array( 'public' => true ) );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot();
+ $result = $execute( $input );
+
+ $this->assert_error( $result, 'content_not_found', 404, 'A direct call without an exposed type' );
+ $this->assertSame( 'The requested content was not found.', $result->get_error_message(), 'The message should be the not-found message.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns `data` values that are invalid in some way.
+ *
+ * @return array}> The data.
+ */
+ public static function data_invalid_data(): array {
+ return array(
+ 'parent on a post' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'parent' => 1,
+ ),
+ ),
+ 'unregistered status' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'status' => 'cw_unregistered',
+ ),
+ ),
+ 'publish' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'status' => 'publish',
+ ),
+ ),
+ 'empty slug' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'x',
+ 'slug' => '!!!',
+ ),
+ ),
+ 'missing author' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'x',
+ 'author' => self::MISSING_ID,
+ ),
+ ),
+ 'title that is a list' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => array( 'x' ),
+ ),
+ ),
+ 'invalid date' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'x',
+ 'date' => array( 'site' => 'not a date' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Called directly by a user without `create_posts`, the call fails on the capability before
+ * anything about the attributes is checked.
+ *
+ * @ticket 66706
+ * @dataProvider data_invalid_data
+ * @since 7.3.0
+ *
+ * @param array $data The data.
+ */
+ public function test_direct_call_without_create_posts_fails_before_the_attributes( array $data ): void {
+ $this->login_as( 'subscriber' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot();
+ $result = $execute( array( 'data' => $data ) );
+
+ $this->assert_error( $result, 'content_cannot_create', 403, 'A direct call without create_posts' );
+ $this->assertSame( 'Sorry, you are not allowed to create posts as this user.', $result->get_error_message(), 'The message should be the create message.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns keys that are not part of the input.
+ *
+ * @return array The keys and values.
+ */
+ public static function data_keys_outside_the_allow_list(): array {
+ return array(
+ 'ID' => array( 'ID', 1 ),
+ 'post_type' => array( 'post_type', 'page' ),
+ 'post_password' => array( 'post_password', 'secret' ),
+ 'meta_input' => array( 'meta_input', array( 'cw_key' => 'value' ) ),
+ 'tax_input' => array( 'tax_input', array( 'category' => array( 1 ) ) ),
+ 'comment_status' => array( 'comment_status', 'closed' ),
+ 'post_author' => array( 'post_author', 1 ),
+ 'import_id' => array( 'import_id', 7654321 ),
+ 'guid' => array( 'guid', 'https://example.org/forged' ),
+ 'page_template' => array( 'page_template', 'cw-template.php' ),
+ 'modified' => array( 'modified', '2001-01-01T00:00:00' ),
+ 'post_modified' => array( 'post_modified', '2001-01-01 00:00:00' ),
+ 'post_modified_gmt' => array( 'post_modified_gmt', '2001-01-01 00:00:00' ),
+ 'sticky' => array( 'sticky', true ),
+ 'tags_input' => array( 'tags_input', array( 'cw-tag' ) ),
+ 'post_category' => array( 'post_category', array( 2 ) ),
+ 'menu_order' => array( 'menu_order', 5 ),
+ 'post_mime_type' => array( 'post_mime_type', 'image/jpeg' ),
+ );
+ }
+
+ /**
+ * A key outside the allow-list fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_keys_outside_the_allow_list
+ * @since 7.3.0
+ *
+ * @param string $key The key.
+ * @param mixed $value The value.
+ */
+ public function test_key_outside_the_allow_list_fails_input_validation( string $key, $value ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Extra key',
+ $key => $value,
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the key.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * An internal or unregistered status fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_that_can_never_be_set
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_status_that_can_never_be_set_fails_input_validation( string $status ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Status',
+ 'status' => $status,
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the status.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Called directly, an internal or unregistered status is an invalid status.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_that_can_never_be_set
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_direct_call_rejects_a_status_that_can_never_be_set( string $status ): void {
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot();
+ $result = $execute(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Status',
+ 'status' => $status,
+ ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'status', 'A direct call with a status that can never be set' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A status that is no longer registered when the call runs is an invalid status.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_status_no_longer_registered_is_rejected(): void {
+ register_post_status(
+ 'cw_temporary',
+ array(
+ 'label' => 'Temporary',
+ 'public' => true,
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ _unregister_post_status( 'cw_temporary' );
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Temporary',
+ 'status' => 'cw_temporary',
+ ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'status', 'A status that is no longer registered' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Registers custom statuses of every visibility, before the abilities are registered.
+ *
+ * @since 7.3.0
+ */
+ private function register_custom_statuses(): void {
+ register_post_status(
+ 'cw_public',
+ array(
+ 'label' => 'Public',
+ 'public' => true,
+ )
+ );
+ register_post_status(
+ 'cw_private',
+ array(
+ 'label' => 'Private',
+ 'private' => true,
+ )
+ );
+ register_post_status(
+ 'cw_viewable',
+ array(
+ 'label' => 'Viewable',
+ 'internal' => false,
+ 'public' => false,
+ 'publicly_queryable' => true,
+ )
+ );
+
+ $this->assertTrue( is_post_status_viewable( 'cw_viewable' ), 'Precondition: the viewable status should be publicly viewable.' );
+ $this->assertFalse( get_post_status_object( 'cw_viewable' )->internal, 'Precondition: the viewable status should not be internal.' );
+ register_post_status(
+ 'cw_protected',
+ array(
+ 'label' => 'Protected',
+ 'protected' => true,
+ )
+ );
+ }
+
+ /**
+ * Returns custom statuses that make a post visible.
+ *
+ * @return array The statuses.
+ */
+ public static function data_custom_statuses_that_make_a_post_visible(): array {
+ return array(
+ 'public' => array( 'cw_public' ),
+ 'private' => array( 'cw_private' ),
+ 'publicly viewable' => array( 'cw_viewable' ),
+ );
+ }
+
+ /**
+ * A custom status that makes a post visible needs `publish_posts`, and the refusal uses the
+ * general message, also for a custom private status.
+ *
+ * @ticket 66706
+ * @dataProvider data_custom_statuses_that_make_a_post_visible
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_custom_visible_status_needs_publish_posts( string $status ): void {
+ $this->register_custom_statuses();
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Custom status',
+ 'status' => $status,
+ ),
+ )
+ );
+
+ $this->assert_error( $result, 'content_cannot_publish', 403, 'A custom visible status without publish_posts' );
+ $this->assertSame( 'Sorry, you are not allowed to publish posts in this post type.', $result->get_error_message(), 'A custom status, also a private one, should get the general message.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A user with `publish_posts` may set a custom status that makes a post visible.
+ *
+ * @ticket 66706
+ * @dataProvider data_custom_statuses_that_make_a_post_visible
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_custom_visible_status_is_set_with_publish_posts( string $status ): void {
+ $this->register_custom_statuses();
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Custom status',
+ 'status' => $status,
+ ),
+ )
+ );
+
+ $this->assertSame( $status, $this->get_created_post( $result )->post_status, 'The custom status should be stored.' );
+ }
+
+ /**
+ * A custom status that is neither public, private nor publicly viewable needs nothing beyond
+ * `create_posts`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_custom_status_that_keeps_a_post_hidden_needs_no_publish_posts(): void {
+ $this->register_custom_statuses();
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Protected status',
+ 'status' => 'cw_protected',
+ ),
+ )
+ );
+
+ $this->assertSame( 'cw_protected', $this->get_created_post( $result )->post_status, 'The custom status should be stored.' );
+ }
+
+ /**
+ * Returns dates that change the stored status of a new post.
+ *
+ * @return array The cases.
+ */
+ public static function data_statuses_reported_as_stored(): array {
+ return array(
+ 'publish with a future date' => array( 'publish', self::FUTURE_GMT, 'future' ),
+ 'future with a past date' => array( 'future', '2016-12-12T19:00:00', 'publish' ),
+ );
+ }
+
+ /**
+ * The regular save rules decide the stored status, and the output reports it.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_reported_as_stored
+ * @since 7.3.0
+ *
+ * @param string $status The requested status.
+ * @param string $gmt The requested GMT date.
+ * @param string $expected The stored status.
+ */
+ public function test_output_reports_the_stored_status( string $status, string $gmt, string $expected ): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Scheduled',
+ 'status' => $status,
+ 'date' => array( 'gmt' => $gmt ),
+ ),
+ 'fields' => array( 'status' ),
+ )
+ );
+
+ $this->assertSame( $expected, $this->get_created_post( $result )->post_status, 'The post should be stored in the expected status.' );
+ $this->assertSame( $expected, $result['status'], 'The output should report the stored status.' );
+ }
+
+ /**
+ * A user without `edit_others_posts` gets the same error for an existing and a missing
+ * author, so the error never tells whether a user exists.
+ *
+ * @ticket 66706
+ * @dataProvider data_authors_named_without_edit_others_posts
+ * @since 7.3.0
+ *
+ * @param string $author The author, as a fixture name.
+ */
+ public function test_naming_another_author_without_edit_others_posts_is_refused( string $author ): void {
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Ghost written',
+ 'author' => self::$user_ids[ $author ] ?? self::MISSING_ID,
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'Naming another author should fail.' );
+ $this->assertSame(
+ array(
+ 'code' => 'content_cannot_edit_others',
+ 'message' => 'Sorry, you are not allowed to create posts as this user.',
+ 'data' => array( 'status' => 403 ),
+ ),
+ array(
+ 'code' => $result->get_error_code(),
+ 'message' => $result->get_error_message(),
+ 'data' => $result->get_error_data(),
+ ),
+ 'The error should be the same whether the user exists or not.'
+ );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A user without `edit_others_posts` may name themselves as the author.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_naming_oneself_as_the_author_needs_no_edit_others_posts(): void {
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Own post',
+ 'author' => self::$user_ids['contributor'],
+ ),
+ )
+ );
+
+ $this->assertSame( self::$user_ids['contributor'], (int) $this->get_created_post( $result )->post_author, 'The current user should be the author.' );
+ }
+
+ /**
+ * A user with `edit_others_posts` may name another existing user as the author.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_naming_another_author_with_edit_others_posts(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'For the author',
+ 'author' => self::$user_ids['author'],
+ ),
+ )
+ );
+
+ $this->assertSame( self::$user_ids['author'], (int) $this->get_created_post( $result )->post_author, 'The named user should be the author.' );
+ }
+
+ /**
+ * A user with `edit_others_posts` who names a missing user gets the invalid author error.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_naming_a_missing_author_with_edit_others_posts_is_an_invalid_author(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Nobody',
+ 'author' => self::MISSING_ID,
+ ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'author', 'A missing author' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * On multisite, a user who is not a member of the site cannot be the author.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_naming_an_author_who_is_not_a_member_of_the_site_is_an_invalid_author(): void {
+ $non_member = self::factory()->user->create( array( 'role' => 'author' ) );
+ remove_user_from_blog( $non_member, get_current_blog_id() );
+
+ $this->assertFalse( is_user_member_of_blog( $non_member ), 'Precondition: the user should not be a member of the site.' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Not a member',
+ 'author' => $non_member,
+ ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'author', 'An author who is not a member of the site' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * On multisite, a user without `edit_others_posts` who names a user who is not a member of the
+ * site gets the same error as for a missing user.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_naming_a_non_member_without_edit_others_posts_is_refused_like_a_missing_user(): void {
+ $non_member = self::factory()->user->create( array( 'role' => 'author' ) );
+ remove_user_from_blog( $non_member, get_current_blog_id() );
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $errors = array();
+ foreach ( array(
+ 'non-member' => $non_member,
+ 'missing' => self::MISSING_ID,
+ ) as $key => $author ) {
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Ghost written',
+ 'author' => $author,
+ ),
+ )
+ );
+ $this->assertWPError( $result, "Naming the {$key} user should fail." );
+ $errors[ $key ] = array( $result->get_error_code(), $result->get_error_message(), $result->get_error_data() );
+ }
+
+ $this->assertSame( 'content_cannot_edit_others', $errors['missing'][0], 'The error should be the authorship error.' );
+ $this->assertSame( $errors['missing'], $errors['non-member'], 'The error should be the same for a non-member and a missing user.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written for either user.' );
+ }
+
+ /**
+ * Returns parents that a page may not have.
+ *
+ * @return array The parents, as fixture names.
+ */
+ public static function data_parents_that_cannot_be_used(): array {
+ return array(
+ 'missing post' => array( 'missing' ),
+ 'post of another type' => array( 'published_post' ),
+ 'page the user may not read' => array( 'editor_draft_page' ),
+ 'revision of a page' => array( 'page_revision' ),
+ );
+ }
+
+ /**
+ * A missing parent, a parent of another type and a parent the user may not read give one
+ * identical error, so the error never tells whether a post exists.
+ *
+ * @ticket 66706
+ * @dataProvider data_parents_that_cannot_be_used
+ * @since 7.3.0
+ *
+ * @param string $parent_key The parent, as a fixture name.
+ */
+ public function test_parent_that_cannot_be_used_gives_one_identical_error( string $parent_key ): void {
+ $this->login_as( 'page_writer' );
+ $this->register_abilities();
+
+ $this->assertTrue( current_user_can( get_post_type_object( 'page' )->cap->create_posts ), 'Precondition: the user should be able to create pages.' );
+ $this->assertFalse( current_user_can( 'read_post', self::$post_ids['editor_draft_page'] ), 'Precondition: the user should not be able to read the draft page of the editor.' );
+
+ $create = function ( int $parent_id ) {
+ return $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'page',
+ 'title' => 'Child',
+ 'parent' => $parent_id,
+ ),
+ )
+ );
+ };
+
+ $before = $this->snapshot();
+ $reference = $create( self::MISSING_ID );
+ $result = $create( self::$post_ids[ $parent_key ] ?? self::MISSING_ID );
+
+ $this->assert_invalid_attribute( $result, 'parent', 'A parent that cannot be used' );
+ $this->assertSame( $reference->get_error_data(), $result->get_error_data(), 'The error data, with its reason, should be the same as for a missing parent.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A readable page of the same type can be the parent, and `0` makes a top-level page.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_parent_is_stored(): void {
+ $this->login_as( 'page_writer' );
+ $this->register_abilities();
+
+ $child = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'page',
+ 'title' => 'Child',
+ 'parent' => self::$post_ids['published_page'],
+ ),
+ 'fields' => array( 'parent' ),
+ )
+ );
+ $top = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'page',
+ 'title' => 'Top',
+ 'parent' => 0,
+ ),
+ 'fields' => array( 'parent' ),
+ )
+ );
+
+ $this->assertSame( self::$post_ids['published_page'], $this->get_created_post( $child )->post_parent, 'The parent should be stored.' );
+ $this->assertSame( self::$post_ids['published_page'], $child['parent'], 'The parent should be returned.' );
+ $this->assertSame( 0, $this->get_created_post( $top )->post_parent, 'A parent of 0 should make a top-level page.' );
+ }
+
+ /**
+ * Returns attributes that a post type does not support.
+ *
+ * @return array The cases.
+ */
+ public static function data_unsupported_attributes(): array {
+ return array(
+ 'excerpt of a page' => array( 'page', 'excerpt', 'An excerpt' ),
+ 'parent of a post' => array( 'post', 'parent', 1 ),
+ 'parent 0 of a post' => array( 'post', 'parent', 0 ),
+ 'title without title support' => array( 'cw_no_title', 'title', 'A title' ),
+ 'content without editor support' => array( 'cw_title_only', 'content', 'Some content' ),
+ 'excerpt without excerpt support' => array( 'cw_title_only', 'excerpt', 'An excerpt' ),
+ 'author without author support' => array( 'cw_title_only', 'author', 1 ),
+ 'empty title without title support' => array( 'cw_no_title', 'title', '' ),
+ );
+ }
+
+ /**
+ * An attribute the post type does not support is rejected, even when it would change nothing.
+ *
+ * @ticket 66706
+ * @dataProvider data_unsupported_attributes
+ * @since 7.3.0
+ *
+ * @param string $type The post type.
+ * @param string $attribute The attribute.
+ * @param mixed $value The value.
+ */
+ public function test_unsupported_attribute_is_rejected( string $type, string $attribute, $value ): void {
+ $this->register_exposed_post_type( 'cw_no_title', array( 'editor' ) );
+ $this->register_exposed_post_type( 'cw_title_only', array( 'title' ) );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $data = array(
+ 'type' => $type,
+ $attribute => $value,
+ );
+ if ( 'title' !== $attribute && 'cw_no_title' !== $type ) {
+ $data['title'] = 'Unsupported';
+ }
+ if ( 'cw_no_title' === $type ) {
+ $data['content'] = 'Unsupported';
+ }
+ if ( 'author' === $attribute ) {
+ $data['author'] = self::$user_ids['administrator'];
+ }
+
+ $before = $this->snapshot();
+ $result = $this->run_ability( array( 'data' => $data ) );
+
+ $this->assert_invalid_attribute( $result, $attribute, 'An unsupported attribute' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns attribute values of the wrong type.
+ *
+ * @return array The cases.
+ */
+ public static function data_values_of_the_wrong_type(): array {
+ return array(
+ 'title that is a number' => array( 'post', 'title', 123 ),
+ 'title that is a list' => array( 'post', 'title', array( 'x' ) ),
+ 'title that is null' => array( 'post', 'title', null ),
+ 'content that is a boolean' => array( 'post', 'content', true ),
+ 'excerpt that is a number' => array( 'post', 'excerpt', 5 ),
+ 'status that is a number' => array( 'post', 'status', 1 ),
+ 'slug that is a list' => array( 'post', 'slug', array( 'slug' ) ),
+ 'date that is a string' => array( 'post', 'date', '2016-12-12T14:00:00' ),
+ 'date with a number' => array( 'post', 'date', array( 'site' => 123 ) ),
+ 'date that cannot be parsed' => array( 'post', 'date', array( 'site' => 'not a date' ) ),
+ 'GMT date that cannot be parsed' => array( 'post', 'date', array( 'gmt' => 'not a date' ) ),
+ 'author that is text' => array( 'post', 'author', 'abc' ),
+ 'author 0' => array( 'post', 'author', 0 ),
+ 'author that is a fraction' => array( 'post', 'author', 1.5 ),
+ 'parent that is negative' => array( 'page', 'parent', -1 ),
+ 'parent that is text' => array( 'page', 'parent', 'abc' ),
+ );
+ }
+
+ /**
+ * A value of the wrong type fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_values_of_the_wrong_type
+ * @since 7.3.0
+ *
+ * @param string $type The post type.
+ * @param string $attribute The attribute.
+ * @param mixed $value The value.
+ */
+ public function test_value_of_the_wrong_type_fails_input_validation( string $type, string $attribute, $value ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $data = array( 'type' => $type );
+ if ( 'title' !== $attribute ) {
+ $data['title'] = 'Wrong type';
+ }
+ $data[ $attribute ] = $value;
+
+ $before = $this->snapshot();
+ $result = $this->run_ability( array( 'data' => $data ) );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the value.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * An empty title is valid next to other content.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_empty_title_is_valid(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => '',
+ 'content' => 'Only content.',
+ ),
+ )
+ );
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSame( '', $post->post_title, 'The empty title should be stored.' );
+ $this->assertSame( 'Only content.', $post->post_content, 'The content should be stored.' );
+ }
+
+ /**
+ * A save error keeps its own code and message, with status 400 when the post is empty.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_empty_post_is_the_save_error(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => '',
+ 'content' => '',
+ 'excerpt' => '',
+ ),
+ )
+ );
+
+ $this->assert_error( $result, 'empty_content', 400, 'An empty post' );
+ $this->assertSame( 'Content, title, and excerpt are empty.', $result->get_error_message(), 'The message should be the message of the save error.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A database error during the save keeps its own code and message, with status 500.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_database_error_is_the_save_error(): void {
+ global $wpdb;
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+
+ $suppress = $wpdb->suppress_errors();
+ add_filter(
+ 'query',
+ static function ( $query ) {
+ return str_starts_with( $query, 'INSERT' ) ? '],' : $query;
+ }
+ );
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Database error',
+ ),
+ )
+ );
+
+ $wpdb->suppress_errors( $suppress );
+
+ $this->assert_error( $result, 'db_insert_error', 500, 'A database error' );
+ $this->assertSame( 'Could not insert post into the database.', $result->get_error_message(), 'The message should be the message of the save error.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written after a database error.' );
+ }
+
+ /**
+ * The after-insert hooks fire once, as in any regular save.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_after_insert_hooks_fire_once(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = did_action( 'wp_after_insert_post' );
+
+ $this->get_created_post(
+ $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Hooks',
+ ),
+ )
+ )
+ );
+
+ $this->assertSame( 1, did_action( 'wp_after_insert_post' ) - $before, 'wp_after_insert_post should fire once.' );
+ }
+
+ /**
+ * Returns slugs and the slug they are stored as.
+ *
+ * @return array The cases.
+ */
+ public static function data_slugs(): array {
+ return array(
+ 'plain' => array( 'launch-notes', 'launch-notes' ),
+ 'with capitals' => array( 'Launch Notes!', 'launch-notes' ),
+ 'accented characters' => array( 'tęst-acceńted-chäræcters', 'test-accented-charaecters' ),
+ );
+ }
+
+ /**
+ * A slug is sanitized and stored.
+ *
+ * @ticket 66706
+ * @dataProvider data_slugs
+ * @since 7.3.0
+ *
+ * @param string $slug The sent slug.
+ * @param string $expected The stored slug.
+ */
+ public function test_slug_is_sanitized_and_stored( string $slug, string $expected ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Slug',
+ 'slug' => $slug,
+ ),
+ 'fields' => array( 'slug' ),
+ )
+ );
+
+ $this->assertSame( $expected, $this->get_created_post( $result )->post_name, 'The sanitized slug should be stored.' );
+ $this->assertSame( $expected, $result['slug'], 'The stored slug should be returned.' );
+ }
+
+ /**
+ * A slug that sanitizes to nothing is an invalid slug.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_that_sanitizes_to_nothing_is_rejected(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Slug',
+ 'slug' => '!!!',
+ ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'slug', 'A slug that sanitizes to nothing' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A user who may not publish posts cannot set the slug of a pending post.
+ *
+ * Intentionally strict: the save would drop the slug, so it is an error instead of being
+ * dropped without notice.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_of_a_pending_post_is_rejected_without_publish_posts(): void {
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Pending slug',
+ 'status' => 'pending',
+ 'slug' => 'pending-slug',
+ ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'slug', 'A slug on a pending post without publish_posts' );
+ $this->assertSame( 'The slug of a pending post can only be set by a user who can publish the post.', $result->get_error_message(), 'The message should say who may set the slug.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written for a slug that cannot be stored.' );
+ }
+
+ /**
+ * A user who may publish posts sets the slug of a pending post.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_of_a_pending_post_is_stored_with_publish_posts(): void {
+ $this->login_as( 'publisher' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Pending slug',
+ 'status' => 'pending',
+ 'slug' => 'pending-slug',
+ ),
+ 'fields' => array( 'status', 'slug' ),
+ )
+ );
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSame( 'pending', $post->post_status, 'The post should be pending.' );
+ $this->assertSame( 'pending-slug', $post->post_name, 'The slug of the pending post should be stored.' );
+ $this->assertSame( 'pending-slug', $result['slug'], 'The slug of the pending post should be returned.' );
+ }
+
+ /**
+ * Returns statuses for which the slug of a published post is made unique.
+ *
+ * @return array The statuses, or null for the default.
+ */
+ public static function data_statuses_with_unique_slugs(): array {
+ return array(
+ 'default status' => array( null ),
+ 'draft' => array( 'draft' ),
+ 'pending' => array( 'pending' ),
+ 'publish' => array( 'publish' ),
+ );
+ }
+
+ /**
+ * A new post never takes the slug of another post, also as a draft or a pending post.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_with_unique_slugs
+ * @since 7.3.0
+ *
+ * @param string|null $status The status, or null to send none.
+ */
+ public function test_slug_of_another_post_is_made_unique( ?string $status ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $data = array(
+ 'type' => 'post',
+ 'title' => 'Shared',
+ 'slug' => 'shared-slug',
+ );
+ if ( null !== $status ) {
+ $data['status'] = $status;
+ }
+
+ $result = $this->run_ability( array( 'data' => $data ) );
+
+ $this->assertSame( 'shared-slug-2', $this->get_created_post( $result )->post_name, 'The slug should be made unique.' );
+ }
+
+ /**
+ * Returns parents for a draft page with the slug of an existing child page.
+ *
+ * @return array The cases.
+ */
+ public static function data_draft_page_slugs_by_parent(): array {
+ return array(
+ 'shared parent' => array( 'published_page', 'child-2' ),
+ 'different parent' => array( 'other_parent_page', 'child' ),
+ );
+ }
+
+ /**
+ * A draft page is made unique among the pages that share its parent only.
+ *
+ * @ticket 66706
+ * @dataProvider data_draft_page_slugs_by_parent
+ * @since 7.3.0
+ *
+ * @param string $parent_key The parent, as a fixture name.
+ * @param string $expected The stored slug.
+ */
+ public function test_draft_page_slug_is_unique_among_its_siblings( string $parent_key, string $expected ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'page',
+ 'title' => 'Child',
+ 'slug' => 'child',
+ 'parent' => self::$post_ids[ $parent_key ],
+ ),
+ )
+ );
+
+ $this->assertSame( $expected, $this->get_created_post( $result )->post_name, 'The slug should be unique among the siblings.' );
+ }
+
+ /**
+ * Returns sent dates and the dates they are stored as, in America/New_York.
+ *
+ * @return array, local: string, gmt: string}> The cases.
+ */
+ public static function data_dates(): array {
+ return array(
+ 'site without offset' => array( array( 'site' => '2016-12-12T14:00:00' ), '2016-12-12 14:00:00', '2016-12-12 19:00:00' ),
+ 'GMT without offset' => array( array( 'gmt' => '2016-12-12T19:00:00' ), '2016-12-12 14:00:00', '2016-12-12 19:00:00' ),
+ 'site with an offset' => array( array( 'site' => '2016-12-12T18:00:00-01:00' ), '2016-12-12 14:00:00', '2016-12-12 19:00:00' ),
+ 'GMT with an offset' => array( array( 'gmt' => '2016-12-12T18:00:00-01:00' ), '2016-12-12 14:00:00', '2016-12-12 19:00:00' ),
+ 'both, the site wins' => array(
+ array(
+ 'site' => '2016-12-12T14:00:00',
+ 'gmt' => '2001-01-01T00:00:00',
+ ),
+ '2016-12-12 14:00:00',
+ '2016-12-12 19:00:00',
+ ),
+ );
+ }
+
+ /**
+ * A sent date sets both the local and the GMT date of a new draft.
+ *
+ * @ticket 66706
+ * @dataProvider data_dates
+ * @since 7.3.0
+ *
+ * @param array $date The sent date.
+ * @param string $local The stored local date.
+ * @param string $gmt The stored GMT date.
+ */
+ public function test_date_is_stored_local_and_gmt( array $date, string $local, string $gmt ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Dated',
+ 'date' => $date,
+ ),
+ )
+ );
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSame( 'draft', $post->post_status, 'The post should be a draft.' );
+ $this->assertSame( $local, $post->post_date, 'The local date should be stored.' );
+ $this->assertSame( $gmt, $post->post_date_gmt, 'The GMT date should be stored.' );
+ }
+
+ /**
+ * A draft created without a date has a floating date.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_draft_without_a_date_floats(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $post = $this->get_created_post(
+ $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Floating',
+ ),
+ )
+ )
+ );
+
+ $this->assertSame( '0000-00-00 00:00:00', $post->post_date_gmt, 'The draft should have no GMT date.' );
+ }
+
+ /**
+ * A date that is not a date-time fails input validation.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_date_that_is_not_a_date_time_fails_input_validation(): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Invalid date',
+ 'date' => array( 'site' => '2010-60-01T02:00:00Z' ),
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the date.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns markup and the values it is stored and rendered as for a user without
+ * `unfiltered_html`.
+ *
+ * @return array The cases.
+ */
+ public static function data_filtered_markup(): array {
+ return array(
+ 'backslashes and non-ASCII text' => array(
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯
',
+ ),
+ 'entities' => array(
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <
',
+ ),
+ 'a script' => array(
+ 'div
strong ',
+ 'div strong ',
+ 'div strong',
+ 'div
strong ',
+ "div
\n strong
",
+ ),
+ 'a link with extra attributes' => array(
+ 'link',
+ 'link',
+ 'link',
+ 'link',
+ 'link
',
+ ),
+ );
+ }
+
+ /**
+ * Creates a post with the same markup in the title, content and excerpt, and returns the
+ * raw and rendered values.
+ *
+ * @since 7.3.0
+ *
+ * @param string $markup The markup.
+ * @return array The ability result.
+ */
+ private function create_with_markup( string $markup ): array {
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => $markup,
+ 'content' => $markup,
+ 'excerpt' => $markup,
+ ),
+ 'fields' => array( 'title', 'content.raw', 'content.rendered', 'excerpt.raw', 'excerpt.rendered' ),
+ )
+ );
+
+ $this->assertIsArray( $result, 'The post with markup should be created.' );
+
+ return $result;
+ }
+
+ /**
+ * The markup of an author, who lacks `unfiltered_html`, is filtered as on any other save.
+ *
+ * @ticket 66706
+ * @dataProvider data_filtered_markup
+ * @since 7.3.0
+ *
+ * @param string $input The sent markup.
+ * @param string $title_raw The stored title.
+ * @param string $title_rendered The rendered title, trimmed.
+ * @param string $text_raw The stored content and excerpt.
+ * @param string $text_rendered The rendered content and excerpt, trimmed.
+ */
+ public function test_markup_of_an_author_is_filtered( string $input, string $title_raw, string $title_rendered, string $text_raw, string $text_rendered ): void {
+ $this->login_as( 'author' );
+
+ $this->assertFalse( current_user_can( 'unfiltered_html' ), 'Precondition: the author should not have unfiltered_html.' );
+
+ $result = $this->create_with_markup( $input );
+
+ $this->assertSame( $title_raw, $result['title']['raw'], 'The stored title should be filtered.' );
+ $this->assertSame( $title_rendered, trim( $result['title']['rendered'] ), 'The rendered title should be filtered.' );
+ $this->assertSame( $text_raw, $result['content']['raw'], 'The stored content should be filtered.' );
+ $this->assertSame( $text_rendered, trim( $result['content']['rendered'] ), 'The rendered content should be filtered.' );
+ $this->assertSame( $text_raw, $result['excerpt']['raw'], 'The stored excerpt should be filtered.' );
+ $this->assertSame( $text_rendered, trim( $result['excerpt']['rendered'] ), 'The rendered excerpt should be filtered.' );
+ }
+
+ /**
+ * The markup of a contributor is filtered.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_markup_of_a_contributor_is_filtered(): void {
+ $this->login_as( 'contributor' );
+
+ $result = $this->create_with_markup( 'div
strong ' );
+
+ $this->assertSame( 'div strong ', $result['title']['raw'], 'The stored title should be filtered.' );
+ $this->assertSame( 'div
strong ', $result['content']['raw'], 'The stored content should be filtered.' );
+ $this->assertSame( 'div
strong ', $result['excerpt']['raw'], 'The stored excerpt should be filtered.' );
+ }
+
+ /**
+ * On multisite, the markup of a site administrator, who lacks `unfiltered_html`, is filtered.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_markup_of_a_site_administrator_is_filtered_on_multisite(): void {
+ $this->login_as( 'administrator' );
+
+ $this->assertFalse( current_user_can( 'unfiltered_html' ), 'Precondition: the site administrator should not have unfiltered_html.' );
+
+ $result = $this->create_with_markup( 'div
strong ' );
+
+ $this->assertSame( 'div strong ', $result['title']['raw'], 'The stored title should be filtered.' );
+ $this->assertSame( 'div
strong ', $result['content']['raw'], 'The stored content should be filtered.' );
+ }
+
+ /**
+ * Asserts that markup is stored unchanged.
+ *
+ * @since 7.3.0
+ */
+ private function assert_markup_is_stored_unchanged(): void {
+ $this->assertTrue( current_user_can( 'unfiltered_html' ), 'Precondition: the user should have unfiltered_html.' );
+
+ $markup = 'div
strong ';
+ $result = $this->create_with_markup( $markup );
+
+ $this->assertSame( $markup, $result['title']['raw'], 'The stored title should not be filtered.' );
+ $this->assertSame( $markup, $result['content']['raw'], 'The stored content should not be filtered.' );
+ $this->assertSame( $markup, $result['excerpt']['raw'], 'The stored excerpt should not be filtered.' );
+ }
+
+ /**
+ * The markup of an administrator with `unfiltered_html` is stored unchanged.
+ *
+ * @group ms-excluded
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_markup_of_an_administrator_is_not_filtered(): void {
+ $this->login_as( 'administrator' );
+
+ $this->assert_markup_is_stored_unchanged();
+ }
+
+ /**
+ * On multisite, the markup of a super admin is stored unchanged.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_markup_of_a_super_admin_is_not_filtered(): void {
+ $super_admin = self::factory()->user->create( array( 'role' => 'administrator' ) );
+ grant_super_admin( $super_admin );
+ wp_set_current_user( $super_admin );
+
+ $this->assert_markup_is_stored_unchanged();
+ }
+
+ /**
+ * Quotes, backslashes and non-ASCII text survive a round trip unchanged.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_quotes_backslashes_and_non_ascii_text_survive_a_round_trip(): void {
+ $text = 'He said "it\'s done" \\ C:\\path\\to\\file \\\\server – café, naïve, 日本語, emoji ✓';
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => $text,
+ 'content' => $text,
+ 'excerpt' => $text,
+ ),
+ 'fields' => array( 'title.raw', 'content.raw', 'excerpt.raw' ),
+ )
+ );
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSame( $text, $post->post_title, 'The stored title should be unchanged.' );
+ $this->assertSame( $text, $post->post_content, 'The stored content should be unchanged.' );
+ $this->assertSame( $text, $post->post_excerpt, 'The stored excerpt should be unchanged.' );
+ $this->assertSame( $text, $result['title']['raw'], 'The returned title should be unchanged.' );
+ $this->assertSame( $text, $result['content']['raw'], 'The returned content should be unchanged.' );
+ $this->assertSame( $text, $result['excerpt']['raw'], 'The returned excerpt should be unchanged.' );
+ }
+
+ /**
+ * Raw fields are left out when the writer cannot edit the post after the write.
+ *
+ * The user may publish posts but not edit published posts.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_raw_fields_are_left_out_when_the_writer_cannot_edit_the_new_post(): void {
+ $this->login_as( 'publisher' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Published once',
+ 'content' => 'Body.',
+ 'status' => 'publish',
+ ),
+ 'fields' => array( 'title', 'content.raw', 'content.rendered' ),
+ )
+ );
+
+ $post = $this->get_created_post( $result );
+
+ $this->assertSame( 'publish', $post->post_status, 'The post should be published.' );
+ $this->assertFalse( current_user_can( 'edit_post', $post->ID ), 'Precondition: the user should not be able to edit the published post.' );
+ $this->assertSame( array( 'rendered' => 'Published once' ), $result['title'], 'The title should be returned without its raw value.' );
+ $this->assertSame( array( 'rendered' => "Body.
\n" ), $result['content'], 'The content should be returned without its raw value.' );
+ }
+
+ /**
+ * The current user is checked at each call, also on the same instance.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_each_call_checks_the_current_user(): void {
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $input = array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Twice',
+ ),
+ );
+
+ $this->login_as( 'author' );
+ $first = $execute( $input );
+
+ $this->login_as( 'subscriber' );
+ $before = $this->snapshot();
+ $second = $execute( $input );
+
+ $this->assertSame( self::$user_ids['author'], (int) $this->get_created_post( $first )->post_author, 'The first call should create a post for the author.' );
+ $this->assert_error( $second, 'content_cannot_create', 403, 'The second call as a subscriber' );
+ $this->assertSame( $before, $this->snapshot(), 'The second call should write nothing.' );
+ }
+
+ /**
+ * Only the requested fields are returned, and the ID always is.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_returns_the_requested_fields_and_the_id(): void {
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Fields',
+ ),
+ 'fields' => array( 'author', 'title.rendered' ),
+ )
+ );
+
+ $user = wp_get_current_user();
+ $post = $this->get_created_post( $result );
+
+ $this->assertSame(
+ array(
+ 'id' => $post->ID,
+ 'title' => array( 'rendered' => 'Fields' ),
+ 'author' => array(
+ 'id' => $user->ID,
+ 'name' => $user->display_name,
+ 'slug' => $user->user_nicename,
+ ),
+ ),
+ $result,
+ 'The ID and the requested fields should be returned.'
+ );
+ }
+
+ /**
+ * Called directly, an empty date or a date that cannot be parsed is an invalid attribute.
+ *
+ * @ticket 66706
+ * @dataProvider data_dates_without_a_usable_value
+ * @since 7.3.0
+ *
+ * @param array $date The date.
+ */
+ public function test_direct_call_rejects_a_date_without_a_usable_value( array $date ): void {
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot();
+ $result = $execute(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Unusable date',
+ 'date' => $date,
+ ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'date', 'A direct call with a date without a usable value' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A pending post that a contributor creates without a date has a floating date.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_pending_post_of_a_contributor_without_a_date_floats(): void {
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $post = $this->get_created_post(
+ $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Pending and floating',
+ 'status' => 'pending',
+ ),
+ )
+ )
+ );
+
+ $this->assertSame( 'pending', $post->post_status, 'The post should be pending.' );
+ $this->assertSame( '0000-00-00 00:00:00', $post->post_date_gmt, 'The pending post should have no GMT date.' );
+ }
+
+ /**
+ * A type that gets `show_in_abilities` after the abilities were registered is not in the type
+ * enum, so a create of that type fails input validation.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_type_exposed_after_registration_fails_input_validation(): void {
+ register_post_type(
+ 'cw_late',
+ array(
+ 'public' => true,
+ 'supports' => array( 'title' ),
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ get_post_type_object( 'cw_late' )->show_in_abilities = true;
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'cw_late',
+ 'title' => 'Exposed too late',
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'A create of a type exposed after registration should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject a type exposed after registration.' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written for a type exposed after registration.' );
+ }
+
+ /**
+ * Registers an exposed post type whose create capability differs from its edit capability.
+ *
+ * @since 7.3.0
+ */
+ private function register_type_with_its_own_create_capability(): void {
+ register_post_type(
+ 'cw_book',
+ array(
+ 'public' => true,
+ 'show_in_abilities' => true,
+ 'supports' => array( 'title', 'editor' ),
+ 'capability_type' => 'cw_book',
+ 'map_meta_cap' => true,
+ 'capabilities' => array( 'create_posts' => 'create_cw_books' ),
+ )
+ );
+
+ $caps = get_post_type_object( 'cw_book' )->cap;
+
+ $this->assertSame( 'create_cw_books', $caps->create_posts, 'Precondition: the type should have its own create capability.' );
+ $this->assertSame( 'edit_cw_books', $caps->edit_posts, 'Precondition: the type should have its own edit capability.' );
+ }
+
+ /**
+ * A user with only the create capability of a type may create a draft of it, but may not
+ * publish it.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_user_with_only_the_create_capability_creates_a_draft_and_cannot_publish(): void {
+ $this->register_type_with_its_own_create_capability();
+
+ $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) );
+ get_userdata( $user_id )->add_cap( 'create_cw_books' );
+ wp_set_current_user( $user_id );
+
+ $this->assertFalse( current_user_can( 'edit_cw_books' ), 'Precondition: the user should not have the edit capability.' );
+
+ $this->register_abilities();
+
+ $draft = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'cw_book',
+ 'title' => 'Draft book',
+ ),
+ )
+ );
+
+ $post = $this->get_created_post( $draft );
+
+ $this->assertSame( 'cw_book', $post->post_type, 'The draft should be of the custom type.' );
+ $this->assertSame( 'draft', $post->post_status, 'The new post should be a draft.' );
+ $this->assertSame( $user_id, (int) $post->post_author, 'The user should be the author of the draft.' );
+
+ $before = $this->snapshot();
+ $published = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'cw_book',
+ 'title' => 'Published book',
+ 'status' => 'publish',
+ ),
+ )
+ );
+
+ $this->assert_error( $published, 'content_cannot_publish', 403, 'Publishing with only the create capability' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written for the refused publish.' );
+ }
+
+ /**
+ * Called directly, a user with only the edit capability of a type, and not its create
+ * capability, may not create a post of it.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_direct_call_with_only_the_edit_capability_cannot_create(): void {
+ $this->register_type_with_its_own_create_capability();
+
+ $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) );
+ get_userdata( $user_id )->add_cap( 'edit_cw_books' );
+ wp_set_current_user( $user_id );
+
+ $this->assertFalse( current_user_can( 'create_cw_books' ), 'Precondition: the user should not have the create capability.' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot();
+ $result = $execute(
+ array(
+ 'data' => array(
+ 'type' => 'cw_book',
+ 'title' => 'Book',
+ ),
+ )
+ );
+
+ $this->assert_error( $result, 'content_cannot_create', 403, 'A direct call with only the edit capability' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * On multisite, after switching to a second site, a user who is an editor only on the first
+ * site may not create posts there.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_editor_of_the_first_site_only_is_refused_on_the_second_site(): void {
+ $blog_id = self::factory()->blog->create();
+
+ $this->assertFalse( is_user_member_of_blog( self::$user_ids['editor'], $blog_id ), 'Precondition: the editor should not be a member of the second site.' );
+
+ $this->login_as( 'editor' );
+ $first_before = $this->snapshot();
+
+ switch_to_blog( $blog_id );
+ $callbacks = $this->get_ability_callbacks();
+ $input = array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Second site',
+ ),
+ );
+
+ $second_before = $this->snapshot();
+ $regular = $this->run_ability( $input );
+ $direct = $callbacks['execute_callback']( $input );
+ $second_after = $this->snapshot();
+
+ restore_current_blog();
+
+ $this->assertWPError( $regular, 'The regular call on the second site should fail.' );
+ $this->assertSame( 'ability_invalid_permissions', $regular->get_error_code(), 'The permission callback should use the capabilities of the second site.' );
+ $this->assert_error( $direct, 'content_cannot_create', 403, 'A direct call on the second site' );
+ $this->assertSame( $second_before, $second_after, 'Nothing should be written on the second site.' );
+ $this->assertSame( $first_before, $this->snapshot(), 'Nothing should be written on the first site.' );
+ }
+
+ /**
+ * On multisite, after switching to a second site, an editor of that site who names a user who
+ * is a member only of the first site gets the invalid author error.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_member_of_the_first_site_only_is_an_invalid_author_on_the_second_site(): void {
+ $blog_id = self::factory()->blog->create();
+ $editor_id = self::factory()->user->create( array( 'role' => 'subscriber' ) );
+ add_user_to_blog( $blog_id, $editor_id, 'editor' );
+
+ $this->assertFalse( is_user_member_of_blog( self::$user_ids['author'], $blog_id ), 'Precondition: the author should not be a member of the second site.' );
+
+ wp_set_current_user( $editor_id );
+ switch_to_blog( $blog_id );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Second site',
+ 'author' => self::$user_ids['author'],
+ ),
+ )
+ );
+ $after = $this->snapshot();
+
+ restore_current_blog();
+
+ $this->assert_invalid_attribute( $result, 'author', 'An author who is a member of the first site only' );
+ $this->assertSame( $before, $after, 'Nothing should be written on the second site.' );
+ }
+
+ /**
+ * A page in the Trash that the user may read is accepted as the parent.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_trashed_page_the_user_may_read_is_accepted_as_the_parent(): void {
+ $parent_id = self::$post_ids['trashed_page'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assertSame( 'trash', get_post_status( $parent_id ), 'Precondition: the parent should be in the Trash.' );
+ $this->assertTrue( current_user_can( 'read_post', $parent_id ), 'Precondition: the editor should be able to read the trashed page.' );
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'page',
+ 'title' => 'Child of a trashed page',
+ 'parent' => $parent_id,
+ ),
+ )
+ );
+
+ $this->assertSame( $parent_id, $this->get_created_post( $result )->post_parent, 'The trashed page should be stored as the parent.' );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentDeleteAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentDeleteAbility.php
new file mode 100644
index 0000000000000..47d8340c150f3
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentDeleteAbility.php
@@ -0,0 +1,1168 @@
+user->create( array( 'role' => $role ) );
+ }
+ self::$user_ids['other'] = $factory->user->create( array( 'role' => 'editor' ) );
+
+ // One post per owner and status, for the matrix tests.
+ foreach ( array_merge( self::ROLES, array( 'other' ) ) as $owner ) {
+ foreach ( self::MATRIX_STATUSES as $status ) {
+ $stored_status = str_replace( 'trash_', '', $status );
+ $post_id = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids[ $owner ],
+ 'post_status' => $stored_status,
+ 'post_date' => 'future' === $stored_status ? '2099-01-01 00:00:00' : '',
+ )
+ );
+ if ( $stored_status !== $status ) {
+ wp_trash_post( $post_id );
+ }
+ self::$post_ids[ "{$owner}:{$status}" ] = $post_id;
+ }
+ }
+
+ self::$post_ids['admin_post'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ )
+ );
+
+ foreach ( array( 'admin_page', 'front_page', 'posts_page', 'privacy_page' ) as $page ) {
+ self::$post_ids[ $page ] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ );
+ }
+
+ self::$post_ids['attachment'] = $factory->attachment->create_object(
+ 'image.jpg',
+ self::$post_ids['admin_post'],
+ array(
+ 'post_mime_type' => 'image/jpeg',
+ 'post_author' => self::$user_ids['administrator'],
+ )
+ );
+
+ $revisioned_id = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ 'post_content' => 'First version.',
+ )
+ );
+ wp_update_post(
+ array(
+ 'ID' => $revisioned_id,
+ 'post_content' => 'Second version.',
+ )
+ );
+ self::$post_ids['revision'] = (int) array_key_first( wp_get_post_revisions( $revisioned_id ) );
+ self::$post_ids['autosave'] = (int) _wp_put_post_revision( get_post( $revisioned_id ), true );
+
+ // Posts of core types that are not exposed.
+ foreach ( array(
+ 'reusable_block' => 'wp_block',
+ 'template' => 'wp_template',
+ 'menu_item' => 'nav_menu_item',
+ ) as $fixture => $post_type ) {
+ self::$post_ids[ $fixture ] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => $post_type,
+ 'post_status' => 'publish',
+ )
+ );
+ }
+ }
+
+ /**
+ * Builds the input that deletes a post.
+ *
+ * @since 7.3.0
+ *
+ * @param int $post_id The post ID.
+ * @param bool|null $permanent The `permanent` value, or null to send none.
+ * @return array The input.
+ */
+ private function delete_input( int $post_id, ?bool $permanent = null ): array {
+ $input = array(
+ 'where' => array(
+ 'type' => get_post_type( $post_id ),
+ 'id' => $post_id,
+ ),
+ );
+ if ( null !== $permanent ) {
+ $input['permanent'] = $permanent;
+ }
+
+ return $input;
+ }
+
+ /**
+ * Asserts that a result is the 403 delete error.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ private function assert_cannot_delete( $result, string $context ): void {
+ $this->assert_error( $result, 'content_cannot_delete', 403, $context );
+ $this->assertSame( 'Sorry, you are not allowed to delete this post.', $result->get_error_message(), "{$context}: the message should be the delete message." );
+ }
+
+ /**
+ * Asserts that a post was moved to the Trash and the result says so.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param int $post_id The post ID.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ private function assert_trashed( $result, int $post_id, string $context ): void {
+ $this->assertSame( array( 'outcome' => 'trashed' ), $result, "{$context}: the outcome should be trashed." );
+
+ clean_post_cache( $post_id );
+
+ $this->assertSame( 'trash', get_post_status( $post_id ), "{$context}: the post should be in the Trash." );
+ }
+
+ /**
+ * Asserts that a post was deleted permanently and the result says so.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param int $post_id The post ID.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ private function assert_deleted( $result, int $post_id, string $context ): void {
+ $this->assertSame( array( 'outcome' => 'deleted' ), $result, "{$context}: the outcome should be deleted." );
+
+ clean_post_cache( $post_id );
+
+ $this->assertNull( get_post( $post_id ), "{$context}: the post should no longer exist." );
+ }
+
+ /**
+ * The ability is registered in the content category with its label and annotations.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_registers_the_ability(): void {
+ $this->register_abilities();
+
+ $ability = wp_get_ability( self::ABILITY );
+
+ $this->assertInstanceOf( WP_Ability::class, $ability, 'The core/content-delete ability should be registered.' );
+ $this->assertSame( 'Delete Content', $ability->get_label(), 'The ability should have its label.' );
+ $this->assertSame( 'content', $ability->get_category(), 'The ability should use the content category.' );
+ $this->assertTrue( $ability->get_meta_item( 'public', false ), 'The ability should be marked public.' );
+
+ $annotations = $ability->get_meta_item( 'annotations', array() );
+ $this->assertFalse( $annotations['readonly'], 'The ability should not be marked read-only.' );
+ $this->assertTrue( $annotations['destructive'], 'The ability should be marked destructive.' );
+ $this->assertTrue( $annotations['idempotent'], 'The ability should be marked idempotent.' );
+ }
+
+ /**
+ * The ability is not registered when no post type is exposed to abilities.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_is_not_registered_without_exposed_post_types(): void {
+ foreach ( array( 'post', 'page' ) as $post_type ) {
+ get_post_type_object( $post_type )->show_in_abilities = false;
+ }
+
+ $this->register_abilities();
+
+ $this->assertFalse( wp_has_ability( self::ABILITY ), 'The delete ability should not be registered without an exposed post type.' );
+ }
+
+ /**
+ * The input schema takes `where`, with the post type and ID, and `permanent`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_input_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The delete ability should be registered.' );
+
+ $schema = wp_get_ability( self::ABILITY )->get_input_schema();
+
+ $this->assertSame( 'object', $schema['type'], 'The input should be an object.' );
+ $this->assertFalse( $schema['additionalProperties'], 'The input should reject unknown keys.' );
+ $this->assertSame( array( 'where' ), $schema['required'], 'The input should require where.' );
+ $this->assertSame( array( 'where', 'permanent' ), array_keys( $schema['properties'] ), 'The input should take where and permanent.' );
+ $this->assertSame( 'boolean', $schema['properties']['permanent']['type'], 'Permanent should be a boolean.' );
+
+ $update_where = wp_get_ability( 'core/content-update' )->get_input_schema()['properties']['where'];
+
+ $this->assertSame( $this->strip_descriptions( $update_where ), $this->strip_descriptions( $schema['properties']['where'] ), 'The where should be the same as on update.' );
+ $this->assertSame( array( 'type', 'id' ), $schema['properties']['where']['required'], 'The where should require the type and the ID.' );
+ $this->assertSame( 1, $schema['properties']['where']['properties']['id']['minimum'], 'The ID should be at least 1.' );
+ }
+
+ /**
+ * The output holds the outcome only.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_output_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The delete ability should be registered.' );
+
+ $schema = wp_get_ability( self::ABILITY )->get_output_schema();
+
+ $this->assertSame( 'object', $schema['type'], 'The output should be an object.' );
+ $this->assertFalse( $schema['additionalProperties'], 'The output should not take unknown keys.' );
+ $this->assertSame( array( 'outcome' ), $schema['required'], 'The output should require the outcome.' );
+ $this->assertSame( array( 'outcome' ), array_keys( $schema['properties'] ), 'The output should hold the outcome only.' );
+ $this->assertSame( 'string', $schema['properties']['outcome']['type'], 'The outcome should be a string.' );
+ }
+
+ /**
+ * A post is moved to the Trash by default.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_trashes_a_post(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assert_trashed(
+ $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ )
+ ),
+ $post_id,
+ 'Trashing a post'
+ );
+ }
+
+ /**
+ * A page is deleted permanently with `permanent`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_deletes_a_page_permanently(): void {
+ $post_id = self::$post_ids['admin_page'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assert_deleted(
+ $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'page',
+ 'id' => $post_id,
+ ),
+ 'permanent' => true,
+ )
+ ),
+ $post_id,
+ 'Deleting a page permanently'
+ );
+ }
+
+ /**
+ * Trashing a post that is already in the Trash is the already-trashed error.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_rejects_trashing_a_trashed_post(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $input = array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ );
+
+ $this->assert_trashed( $this->run_ability( $input ), $post_id, 'The first call' );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $input );
+
+ $this->assertWPError( $result, 'Trashing the post again should fail.' );
+ $this->assertSame(
+ array(
+ 'code' => 'content_already_trashed',
+ 'message' => 'The post has already been trashed.',
+ 'data' => array( 'status' => 410 ),
+ ),
+ array(
+ 'code' => $result->get_error_code(),
+ 'message' => $result->get_error_message(),
+ 'data' => $result->get_error_data(),
+ ),
+ 'The error should be the already-trashed error.'
+ );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A logged-out user is refused before the ability runs.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_refuses_a_logged_out_user(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $this->delete_input( $post_id, true ) );
+
+ $this->assertWPError( $result, 'The call should be refused.' );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The permission callback should refuse a logged-out user.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns inputs for which the permission callback returns false, even for an administrator.
+ *
+ * @return array The inputs.
+ */
+ public static function data_inputs_refused_by_the_permission_callback(): array {
+ return array(
+ 'no input' => array( null ),
+ 'no where' => array( array( 'permanent' => true ) ),
+ 'where that is a string' => array( array( 'where' => 'post' ) ),
+ 'type that is a number' => array(
+ array(
+ 'where' => array(
+ 'type' => 1,
+ 'id' => 1,
+ ),
+ ),
+ ),
+ 'unexposed type' => array(
+ array(
+ 'where' => array(
+ 'type' => 'revision',
+ 'id' => 1,
+ ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * The permission callback returns false for missing or malformed input.
+ *
+ * @ticket 66706
+ * @dataProvider data_inputs_refused_by_the_permission_callback
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_returns_false_for_malformed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should return false.' );
+ }
+
+ /**
+ * The permission callback returns false for a post the user cannot delete, in every form the
+ * post can be named in input that was not prepared.
+ *
+ * @ticket 66706
+ * @dataProvider data_unprepared_where_forms
+ * @since 7.3.0
+ *
+ * @param string $id_type The type to send the ID as.
+ * @param bool $as_object Whether to send `where` as an object.
+ */
+ public function test_permission_callback_returns_false_for_a_post_the_user_cannot_delete( string $id_type, bool $as_object ): void {
+ $this->login_as( 'contributor' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $where = $this->build_unprepared_where( self::$post_ids['admin_post'], $id_type, $as_object );
+
+ $this->assertFalse( $permission( array( 'where' => $where ) ), 'The permission callback should return false.' );
+ }
+
+ /**
+ * The permission callback returns true for a post the user can delete.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_returns_true_for_a_post_the_user_can_delete(): void {
+ $this->login_as( 'author' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertTrue( $permission( $this->delete_input( self::$post_ids['author:draft'] ) ), 'The permission callback should return true.' );
+ }
+
+ /**
+ * The permission callback lets a post that does not exist through, also for a user who may
+ * delete nothing.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_lets_a_missing_post_through(): void {
+ $this->login_as( 'subscriber' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertTrue(
+ $permission(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => self::MISSING_ID,
+ ),
+ )
+ ),
+ 'The permission callback should return true.'
+ );
+ }
+
+ /**
+ * A permission result that a filter turned into a grant does not skip the capability check
+ * on the post.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_granted_permission_result_does_not_skip_the_capability_check(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+ add_filter( 'wp_ability_permission_result', '__return_true' );
+
+ $before = $this->snapshot( $post_id );
+ $trash = $this->run_ability( $this->delete_input( $post_id ) );
+ $permanent = $this->run_ability( $this->delete_input( $post_id, true ) );
+
+ $this->assert_cannot_delete( $trash, 'A trash granted by a filter' );
+ $this->assert_cannot_delete( $permanent, 'A permanent delete granted by a filter' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns ID values that are not a whole number of at least 1.
+ *
+ * @return array The IDs.
+ */
+ public static function data_ids_that_are_not_whole_numbers_of_at_least_1(): array {
+ return array(
+ 'digits and letters' => array( '123abc' ),
+ 'fraction' => array( 1.5 ),
+ 'zero' => array( 0 ),
+ 'negative' => array( -1 ),
+ 'true' => array( true ),
+ 'null' => array( null ),
+ 'list' => array( array( 1 ) ),
+ );
+ }
+
+ /**
+ * An ID that is not a whole number of at least 1 fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_ids_that_are_not_whole_numbers_of_at_least_1
+ * @since 7.3.0
+ *
+ * @param mixed $id The ID.
+ */
+ public function test_id_that_is_not_a_whole_number_fails_input_validation( $id ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( self::$post_ids['admin_post'] );
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $id,
+ ),
+ 'permanent' => true,
+ )
+ );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the ID.' );
+ $this->assertSame( $before, $this->snapshot( self::$post_ids['admin_post'] ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A revision, an autosave, an attachment, a post of another exposed or non-exposed type and a
+ * missing post are not found as a `post`, even by an administrator and even for a permanent
+ * delete.
+ *
+ * @ticket 66706
+ * @dataProvider data_posts_that_are_not_posts
+ * @since 7.3.0
+ *
+ * @param string $post The post, as a fixture name.
+ */
+ public function test_post_of_another_type_is_not_found( string $post ): void {
+ $post_id = self::$post_ids[ $post ] ?? self::MISSING_ID;
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'permanent' => true,
+ )
+ );
+
+ $this->assert_not_found( $result, 'A post that is not a post' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Called directly, a post of a type that is not exposed is not found, whatever its ID.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_direct_call_for_a_type_that_is_not_exposed_is_not_found(): void {
+ register_post_type( 'cw_hidden', array( 'public' => true ) );
+ $post_id = self::factory()->post->create( array( 'post_type' => 'cw_hidden' ) );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'cw_hidden',
+ 'id' => $post_id,
+ ),
+ 'permanent' => true,
+ )
+ );
+
+ $this->assert_not_found( $result, 'A direct call for a type that is not exposed' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A post type whose `show_in_abilities` is turned off after registration cannot be deleted.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_type_no_longer_exposed_cannot_be_deleted(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'administrator' );
+ $callbacks = $this->get_ability_callbacks();
+
+ get_post_type_object( 'post' )->show_in_abilities = false;
+
+ $input = $this->delete_input( $post_id, true );
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $input );
+
+ $this->assertWPError( $result, 'The regular call should fail.' );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The permission callback should refuse a type that is no longer exposed.' );
+ $this->assert_not_found( $callbacks['execute_callback']( $input ), 'A direct call for a type that is no longer exposed' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns direct-call inputs with a malformed `where`.
+ *
+ * @return array}> The inputs.
+ */
+ public static function data_direct_inputs_with_a_malformed_where(): array {
+ return array(
+ 'no where' => array( array( 'permanent' => true ) ),
+ 'no type' => array( array( 'where' => array( 'id' => 1 ) ) ),
+ 'no ID' => array( array( 'where' => array( 'type' => 'post' ) ) ),
+ );
+ }
+
+ /**
+ * Called directly, a malformed `where` is the not-found error.
+ *
+ * @ticket 66706
+ * @dataProvider data_direct_inputs_with_a_malformed_where
+ * @since 7.3.0
+ *
+ * @param array $input The input.
+ */
+ public function test_direct_call_with_a_malformed_where_is_not_found( array $input ): void {
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( self::$post_ids['admin_post'] );
+
+ $this->assert_not_found( $execute( $input ), 'A direct call with a malformed where' );
+ $this->assertSame( $before, $this->snapshot( self::$post_ids['admin_post'] ), 'Nothing should be deleted for a malformed where.' );
+ }
+
+ /**
+ * The lookup comes before the capability: a user who may delete nothing gets the not-found
+ * error for a missing post, and is refused for an existing post.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_lookup_comes_before_the_capability(): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( self::$post_ids['admin_post'] );
+ $missing = $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => self::MISSING_ID,
+ ),
+ )
+ );
+ $existing = $this->run_ability( $this->delete_input( self::$post_ids['admin_post'] ) );
+
+ $this->assert_not_found( $missing, 'A missing post' );
+ $this->assert_refused( $existing, 'An existing post the user may not delete' );
+ $this->assertSame( $before, $this->snapshot( self::$post_ids['admin_post'] ), 'The refused post should still exist, unchanged.' );
+ }
+
+ /**
+ * Returns whether each role may delete each matrix post.
+ *
+ * @return array The cases.
+ */
+ public static function data_delete_matrix(): array {
+ return array(
+ 'administrator, own, draft' => array( 'administrator', 'administrator', 'draft', true ),
+ 'administrator, own, pending' => array( 'administrator', 'administrator', 'pending', true ),
+ 'administrator, own, publish' => array( 'administrator', 'administrator', 'publish', true ),
+ 'administrator, own, future' => array( 'administrator', 'administrator', 'future', true ),
+ 'administrator, own, private' => array( 'administrator', 'administrator', 'private', true ),
+ 'administrator, own, trash_draft' => array( 'administrator', 'administrator', 'trash_draft', true ),
+ 'administrator, own, trash_publish' => array( 'administrator', 'administrator', 'trash_publish', true ),
+ 'administrator, other, draft' => array( 'administrator', 'other', 'draft', true ),
+ 'administrator, other, pending' => array( 'administrator', 'other', 'pending', true ),
+ 'administrator, other, publish' => array( 'administrator', 'other', 'publish', true ),
+ 'administrator, other, future' => array( 'administrator', 'other', 'future', true ),
+ 'administrator, other, private' => array( 'administrator', 'other', 'private', true ),
+ 'administrator, other, trash_draft' => array( 'administrator', 'other', 'trash_draft', true ),
+ 'administrator, other, trash_publish' => array( 'administrator', 'other', 'trash_publish', true ),
+ 'editor, own, draft' => array( 'editor', 'editor', 'draft', true ),
+ 'editor, own, pending' => array( 'editor', 'editor', 'pending', true ),
+ 'editor, own, publish' => array( 'editor', 'editor', 'publish', true ),
+ 'editor, own, future' => array( 'editor', 'editor', 'future', true ),
+ 'editor, own, private' => array( 'editor', 'editor', 'private', true ),
+ 'editor, own, trash_draft' => array( 'editor', 'editor', 'trash_draft', true ),
+ 'editor, own, trash_publish' => array( 'editor', 'editor', 'trash_publish', true ),
+ 'editor, other, draft' => array( 'editor', 'other', 'draft', true ),
+ 'editor, other, pending' => array( 'editor', 'other', 'pending', true ),
+ 'editor, other, publish' => array( 'editor', 'other', 'publish', true ),
+ 'editor, other, future' => array( 'editor', 'other', 'future', true ),
+ 'editor, other, private' => array( 'editor', 'other', 'private', true ),
+ 'editor, other, trash_draft' => array( 'editor', 'other', 'trash_draft', true ),
+ 'editor, other, trash_publish' => array( 'editor', 'other', 'trash_publish', true ),
+ 'author, own, draft' => array( 'author', 'author', 'draft', true ),
+ 'author, own, pending' => array( 'author', 'author', 'pending', true ),
+ 'author, own, publish' => array( 'author', 'author', 'publish', true ),
+ 'author, own, future' => array( 'author', 'author', 'future', true ),
+ 'author, own, private' => array( 'author', 'author', 'private', true ),
+ 'author, own, trash_draft' => array( 'author', 'author', 'trash_draft', true ),
+ 'author, own, trash_publish' => array( 'author', 'author', 'trash_publish', true ),
+ 'author, other, draft' => array( 'author', 'other', 'draft', false ),
+ 'author, other, pending' => array( 'author', 'other', 'pending', false ),
+ 'author, other, publish' => array( 'author', 'other', 'publish', false ),
+ 'author, other, future' => array( 'author', 'other', 'future', false ),
+ 'author, other, private' => array( 'author', 'other', 'private', false ),
+ 'author, other, trash_draft' => array( 'author', 'other', 'trash_draft', false ),
+ 'author, other, trash_publish' => array( 'author', 'other', 'trash_publish', false ),
+ 'contributor, own, draft' => array( 'contributor', 'contributor', 'draft', true ),
+ 'contributor, own, pending' => array( 'contributor', 'contributor', 'pending', true ),
+ 'contributor, own, publish' => array( 'contributor', 'contributor', 'publish', false ),
+ 'contributor, own, future' => array( 'contributor', 'contributor', 'future', false ),
+ 'contributor, own, private' => array( 'contributor', 'contributor', 'private', true ),
+ 'contributor, own, trash_draft' => array( 'contributor', 'contributor', 'trash_draft', true ),
+ 'contributor, own, trash_publish' => array( 'contributor', 'contributor', 'trash_publish', false ),
+ 'contributor, other, draft' => array( 'contributor', 'other', 'draft', false ),
+ 'contributor, other, pending' => array( 'contributor', 'other', 'pending', false ),
+ 'contributor, other, publish' => array( 'contributor', 'other', 'publish', false ),
+ 'contributor, other, future' => array( 'contributor', 'other', 'future', false ),
+ 'contributor, other, private' => array( 'contributor', 'other', 'private', false ),
+ 'contributor, other, trash_draft' => array( 'contributor', 'other', 'trash_draft', false ),
+ 'contributor, other, trash_publish' => array( 'contributor', 'other', 'trash_publish', false ),
+ 'subscriber, own, draft' => array( 'subscriber', 'subscriber', 'draft', false ),
+ 'subscriber, own, pending' => array( 'subscriber', 'subscriber', 'pending', false ),
+ 'subscriber, own, publish' => array( 'subscriber', 'subscriber', 'publish', false ),
+ 'subscriber, own, future' => array( 'subscriber', 'subscriber', 'future', false ),
+ 'subscriber, own, private' => array( 'subscriber', 'subscriber', 'private', false ),
+ 'subscriber, own, trash_draft' => array( 'subscriber', 'subscriber', 'trash_draft', false ),
+ 'subscriber, own, trash_publish' => array( 'subscriber', 'subscriber', 'trash_publish', false ),
+ 'subscriber, other, draft' => array( 'subscriber', 'other', 'draft', false ),
+ 'subscriber, other, pending' => array( 'subscriber', 'other', 'pending', false ),
+ 'subscriber, other, publish' => array( 'subscriber', 'other', 'publish', false ),
+ 'subscriber, other, future' => array( 'subscriber', 'other', 'future', false ),
+ 'subscriber, other, private' => array( 'subscriber', 'other', 'private', false ),
+ 'subscriber, other, trash_draft' => array( 'subscriber', 'other', 'trash_draft', false ),
+ 'subscriber, other, trash_publish' => array( 'subscriber', 'other', 'trash_publish', false ),
+ );
+ }
+
+ /**
+ * Each role may trash the posts it may delete, gets the 410 error for those already in the
+ * Trash, and is refused for the others, whatever their status.
+ *
+ * @ticket 66706
+ * @dataProvider data_delete_matrix
+ * @since 7.3.0
+ *
+ * @param string $role The role to delete as.
+ * @param string $owner The role of the author of the post, or `other`.
+ * @param string $status The matrix status of the post.
+ * @param bool $may_delete Whether the role may delete the post.
+ */
+ public function test_trash_matrix( string $role, string $owner, string $status, bool $may_delete ): void {
+ $post_id = self::$post_ids[ "{$owner}:{$status}" ];
+
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $this->delete_input( $post_id ) );
+
+ if ( $may_delete && ! str_starts_with( $status, 'trash_' ) ) {
+ $this->assert_trashed( $result, $post_id, 'Trashing a post the role may delete' );
+ return;
+ }
+
+ if ( $may_delete ) {
+ $this->assert_error( $result, 'content_already_trashed', 410, 'Trashing a trashed post the role may delete' );
+ } else {
+ $this->assert_refused( $result, 'Trashing a post the role may not delete' );
+ }
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Each role may delete permanently the posts it may delete, including posts in the Trash, and
+ * is refused for the others, whatever their status.
+ *
+ * @ticket 66706
+ * @dataProvider data_delete_matrix
+ * @since 7.3.0
+ *
+ * @param string $role The role to delete as.
+ * @param string $owner The role of the author of the post, or `other`.
+ * @param string $status The matrix status of the post.
+ * @param bool $may_delete Whether the role may delete the post.
+ */
+ public function test_permanent_delete_matrix( string $role, string $owner, string $status, bool $may_delete ): void {
+ $post_id = self::$post_ids[ "{$owner}:{$status}" ];
+
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $this->delete_input( $post_id, true ) );
+
+ if ( $may_delete ) {
+ $this->assert_deleted( $result, $post_id, 'Deleting a post the role may delete' );
+ return;
+ }
+
+ $this->assert_refused( $result, 'Deleting a post the role may not delete' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * `permanent` set to false moves the post to the Trash.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permanent_false_trashes_the_post(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assert_trashed( $this->run_ability( $this->delete_input( $post_id, false ) ), $post_id, 'Deleting with permanent false' );
+ }
+
+ /**
+ * A post that cannot be moved to the Trash is not deleted in its place: the call fails
+ * and asks for `permanent`, which then deletes the post.
+ *
+ * Attachments only support the Trash when `MEDIA_TRASH` is on, so the test exposes them.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_post_without_trash_support_needs_permanent(): void {
+ $post_id = self::$post_ids['attachment'];
+
+ get_post_type_object( 'attachment' )->show_in_abilities = true;
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assertFalse( MEDIA_TRASH, 'Precondition: attachments should not support the Trash.' );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $this->delete_input( $post_id ) );
+
+ $this->assert_error( $result, 'content_trash_not_supported', 501, 'Trashing a post without Trash support' );
+ $this->assertSame( 'The post does not support trashing. Set "permanent" to delete it.', $result->get_error_message(), 'The message should ask for a permanent delete.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'A post without Trash support should be left as it was.' );
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( $post_id, true ) ), $post_id, 'Deleting a post without Trash support permanently' );
+ }
+
+ /**
+ * Returns the special pages of the site.
+ *
+ * @return array The pages, as fixture names.
+ */
+ public static function data_special_pages(): array {
+ return array(
+ 'front page' => array( 'front_page' ),
+ 'posts page' => array( 'posts_page' ),
+ 'privacy policy page' => array( 'privacy_page' ),
+ );
+ }
+
+ /**
+ * Sets the special pages of the site.
+ *
+ * @since 7.3.0
+ */
+ private function set_special_pages(): void {
+ update_option( 'show_on_front', 'page' );
+ update_option( 'page_on_front', self::$post_ids['front_page'] );
+ update_option( 'page_for_posts', self::$post_ids['posts_page'] );
+ update_option( 'wp_page_for_privacy_policy', self::$post_ids['privacy_page'] );
+ }
+
+ /**
+ * An editor may delete neither the front page, the posts page nor the privacy policy page.
+ *
+ * @ticket 66706
+ * @dataProvider data_special_pages
+ * @since 7.3.0
+ *
+ * @param string $page The page, as a fixture name.
+ */
+ public function test_editor_cannot_delete_a_special_page( string $page ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $trash = $this->run_ability( $this->delete_input( $post_id ) );
+ $permanent = $this->run_ability( $this->delete_input( $post_id, true ) );
+
+ $this->assert_refused( $trash, 'An editor trashing a special page' );
+ $this->assert_refused( $permanent, 'An editor deleting a special page' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * On a single site, an administrator may trash the special pages.
+ *
+ * @group ms-excluded
+ *
+ * @ticket 66706
+ * @dataProvider data_special_pages
+ * @since 7.3.0
+ *
+ * @param string $page The page, as a fixture name.
+ */
+ public function test_administrator_can_trash_a_special_page( string $page ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assert_trashed( $this->run_ability( $this->delete_input( $post_id ) ), $post_id, 'An administrator trashing a special page' );
+ }
+
+ /**
+ * On a single site, an administrator may delete the special pages permanently.
+ *
+ * The page is not trashed first: trashing the front page or the posts page clears the
+ * option that makes it special.
+ *
+ * @group ms-excluded
+ *
+ * @ticket 66706
+ * @dataProvider data_special_pages
+ * @since 7.3.0
+ *
+ * @param string $page The page, as a fixture name.
+ */
+ public function test_administrator_can_delete_a_special_page( string $page ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( $post_id, true ) ), $post_id, 'An administrator deleting a special page' );
+ }
+
+ /**
+ * Returns the special pages of the site and whether a site administrator may delete them on
+ * multisite.
+ *
+ * @return array The cases.
+ */
+ public static function data_special_pages_for_a_site_administrator(): array {
+ return array(
+ 'front page' => array( 'front_page', true ),
+ 'posts page' => array( 'posts_page', true ),
+ 'privacy policy page' => array( 'privacy_page', false ),
+ );
+ }
+
+ /**
+ * On multisite, a site administrator may delete the front page and the posts page, but not
+ * the privacy policy page.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @dataProvider data_special_pages_for_a_site_administrator
+ * @since 7.3.0
+ *
+ * @param string $page The page, as a fixture name.
+ * @param bool $allowed Whether the site administrator may delete it.
+ */
+ public function test_site_administrator_deletes_special_pages_on_multisite( string $page, bool $allowed ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $this->delete_input( $post_id ) );
+
+ if ( $allowed ) {
+ $this->assert_trashed( $result, $post_id, 'A site administrator trashing a special page' );
+ return;
+ }
+
+ $this->assert_refused( $result, 'A site administrator trashing the privacy policy page' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * On multisite, a super admin may delete the special pages.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @dataProvider data_special_pages
+ * @since 7.3.0
+ *
+ * @param string $page The page, as a fixture name.
+ */
+ public function test_super_admin_can_delete_a_special_page_on_multisite( string $page ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $super_admin = self::factory()->user->create( array( 'role' => 'administrator' ) );
+ grant_super_admin( $super_admin );
+ wp_set_current_user( $super_admin );
+
+ $this->register_abilities();
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( $post_id, true ) ), $post_id, 'A super admin deleting a special page' );
+ }
+
+ /**
+ * Returns values for the pre-trash and pre-delete filters that stop the operation.
+ *
+ * @return array The cases.
+ */
+ public static function data_operations_that_are_stopped(): array {
+ return array(
+ 'trash, false' => array( false, 'pre_trash_post', false ),
+ 'trash, truthy without trashing' => array( false, 'pre_trash_post', true ),
+ 'delete, false' => array( true, 'pre_delete_post', false ),
+ 'delete, truthy without deleting' => array( true, 'pre_delete_post', true ),
+ );
+ }
+
+ /**
+ * When the trash or delete call fails or does not act, the result is the 500 error and the
+ * post is left as it was.
+ *
+ * @ticket 66706
+ * @dataProvider data_operations_that_are_stopped
+ * @since 7.3.0
+ *
+ * @param bool $permanent Whether the delete is permanent.
+ * @param string $filter The filter that stops the operation.
+ * @param mixed $value The value the filter returns.
+ */
+ public function test_operation_that_does_not_act_is_an_error( bool $permanent, string $filter, $value ): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ add_filter(
+ $filter,
+ static function () use ( $value ) {
+ return $value;
+ }
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $this->delete_input( $post_id, $permanent ) );
+
+ $this->assert_error( $result, 'content_delete_failed', 500, 'An operation that does not act' );
+ $this->assertSame( 'The post could not be deleted.', $result->get_error_message(), 'The message should be the failure message.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns keys that are not part of the input, and where they are sent.
+ *
+ * @return array The cases.
+ */
+ public static function data_keys_outside_the_allow_list(): array {
+ return array(
+ 'force' => array( null, 'force', true ),
+ 'ID' => array( null, 'ID', 1 ),
+ 'where status' => array( 'where', 'status', 'trash' ),
+ 'where ID' => array( 'where', 'ID', 1 ),
+ );
+ }
+
+ /**
+ * A key outside the allow-list fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_keys_outside_the_allow_list
+ * @since 7.3.0
+ *
+ * @param string|null $location Where the key is sent, or null for the top level.
+ * @param string $key The key.
+ * @param mixed $value The value.
+ */
+ public function test_key_outside_the_allow_list_fails_input_validation( ?string $location, string $key, $value ): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $input = $this->delete_input( $post_id );
+ if ( null === $location ) {
+ $input[ $key ] = $value;
+ } else {
+ $input[ $location ][ $key ] = $value;
+ }
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $input );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the key.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * The current user is checked at each call, also on the same instance.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_each_call_checks_the_current_user(): void {
+ $own_id = self::$post_ids['author:draft'];
+ $other_id = self::$post_ids['author:pending'];
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $this->login_as( 'author' );
+ $first = $execute( $this->delete_input( $own_id ) );
+
+ $this->login_as( 'contributor' );
+ $before = $this->snapshot( $other_id );
+ $second = $execute( $this->delete_input( $other_id ) );
+
+ $this->assert_trashed( $first, $own_id, 'The first call as the author' );
+ $this->assert_cannot_delete( $second, 'The second call as a contributor' );
+ $this->assertSame( $before, $this->snapshot( $other_id ), 'The second call should write nothing.' );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentUpdateAbility.php
new file mode 100644
index 0000000000000..a9e161d3174d1
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentUpdateAbility.php
@@ -0,0 +1,3371 @@
+user->create( array( 'role' => $role ) );
+ }
+ self::$user_ids['other'] = $factory->user->create( array( 'role' => 'editor' ) );
+ self::$user_ids['page_writer'] = $factory->user->create( array( 'role' => 'subscriber' ) );
+ self::$user_ids['publisher'] = $factory->user->create( array( 'role' => 'contributor' ) );
+
+ // A user who may edit their own draft pages but not read the drafts of other users.
+ get_userdata( self::$user_ids['page_writer'] )->add_cap( 'edit_pages' );
+
+ // A user who may publish posts but not edit published posts.
+ get_userdata( self::$user_ids['publisher'] )->add_cap( 'publish_posts' );
+
+ // One post per owner and status, for the matrix tests.
+ foreach ( array_merge( self::ROLES, array( 'other' ) ) as $owner ) {
+ foreach ( self::MATRIX_STATUSES as $status ) {
+ $stored_status = str_replace( 'trash_', '', $status );
+ $post_id = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids[ $owner ],
+ 'post_status' => $stored_status,
+ 'post_title' => "Matrix {$owner} {$status}",
+ 'post_date' => 'future' === $stored_status ? '2099-01-01 00:00:00' : '',
+ )
+ );
+ if ( $stored_status !== $status ) {
+ wp_trash_post( $post_id );
+ }
+ self::$post_ids[ "{$owner}:{$status}" ] = $post_id;
+ }
+ }
+
+ self::$post_ids['admin_post'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ 'post_title' => 'Launch notes',
+ 'post_name' => 'shared-slug',
+ )
+ );
+
+ self::$post_ids['admin_page'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ );
+
+ self::$post_ids['editor_draft_page'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ )
+ );
+
+ self::$post_ids['writer_page'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['page_writer'],
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ 'post_title' => 'Writer page',
+ )
+ );
+
+ self::$post_ids['writer_child'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_parent' => self::$post_ids['writer_page'],
+ )
+ );
+
+ self::$post_ids['writer_grandchild'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_parent' => self::$post_ids['writer_child'],
+ )
+ );
+
+ // A page of the writer whose stored parent the writer may not read.
+ self::$post_ids['writer_page_with_hidden_parent'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['page_writer'],
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ 'post_title' => 'Hidden parent',
+ 'post_parent' => self::$post_ids['editor_draft_page'],
+ )
+ );
+
+ self::$post_ids['attachment'] = $factory->attachment->create_object(
+ 'image.jpg',
+ self::$post_ids['admin_post'],
+ array(
+ 'post_mime_type' => 'image/jpeg',
+ 'post_author' => self::$user_ids['administrator'],
+ )
+ );
+
+ $revisioned_id = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ 'post_content' => 'First version.',
+ )
+ );
+ wp_update_post(
+ array(
+ 'ID' => $revisioned_id,
+ 'post_content' => 'Second version.',
+ )
+ );
+ $revisions = wp_get_post_revisions( $revisioned_id );
+ self::$post_ids['revision'] = (int) array_key_first( $revisions );
+ self::$post_ids['autosave'] = (int) _wp_put_post_revision( get_post( $revisioned_id ), true );
+
+ // Posts of core types that are not exposed.
+ foreach ( array(
+ 'reusable_block' => 'wp_block',
+ 'template' => 'wp_template',
+ 'menu_item' => 'nav_menu_item',
+ ) as $fixture => $post_type ) {
+ self::$post_ids[ $fixture ] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => $post_type,
+ 'post_status' => 'publish',
+ )
+ );
+ }
+
+ // An author whose role grants publish_posts, denied it for this user.
+ self::$user_ids['restricted_author'] = $factory->user->create( array( 'role' => 'author' ) );
+ get_userdata( self::$user_ids['restricted_author'] )->add_cap( 'publish_posts', false );
+
+ self::$post_ids['restricted_author:draft'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['restricted_author'],
+ 'post_status' => 'draft',
+ )
+ );
+ }
+
+ /**
+ * Runs the update ability on a post with the given data.
+ *
+ * @since 7.3.0
+ *
+ * @param int $post_id The post ID.
+ * @param array $data The data.
+ * @param list|null $fields The fields, or null for the default.
+ * @return mixed The ability result.
+ */
+ private function update_post( int $post_id, array $data, ?array $fields = null ) {
+ $input = array(
+ 'where' => array(
+ 'type' => get_post_type( $post_id ),
+ 'id' => $post_id,
+ ),
+ 'data' => $data,
+ );
+ if ( null !== $fields ) {
+ $input['fields'] = $fields;
+ }
+
+ return $this->run_ability( $input );
+ }
+
+ /**
+ * Asserts that a result is the post item of a successful update and returns the stored post.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param int $post_id The ID of the updated post.
+ * @return WP_Post The stored post.
+ */
+ private function assert_updated( $result, int $post_id ): WP_Post {
+ $this->assertIsArray( $result, 'The update should succeed.' );
+ $this->assertSame( $post_id, $result['id'] ?? null, 'The updated post should be returned with its ID.' );
+
+ clean_post_cache( $post_id );
+
+ return get_post( $post_id );
+ }
+
+ /**
+ * Creates a draft with a floating date, stored in the site's timezone with no GMT date.
+ *
+ * @since 7.3.0
+ *
+ * @param string $local The local date, as `Y-m-d H:i:s`.
+ * @return int The post ID.
+ */
+ private function create_floating_draft( string $local ): int {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_status' => 'draft',
+ 'post_title' => 'Floating',
+ 'post_date' => $local,
+ )
+ );
+
+ $this->assertSame( '0000-00-00 00:00:00', get_post( $post_id )->post_date_gmt, 'Precondition: the draft should have a floating date.' );
+
+ return $post_id;
+ }
+
+ /**
+ * Asserts that a stored GMT date is the current time, give or take a minute.
+ *
+ * @since 7.3.0
+ *
+ * @param string $gmt The stored GMT date.
+ * @param string $context What the date is, for the assertion message.
+ */
+ private function assert_is_now( string $gmt, string $context ): void {
+ $this->assertEqualsWithDelta( time(), strtotime( $gmt . ' UTC' ), 60, "{$context} should be the current time." );
+ }
+
+ /**
+ * The ability is registered in the content category with its label and annotations.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_registers_the_ability(): void {
+ $this->register_abilities();
+
+ $ability = wp_get_ability( self::ABILITY );
+
+ $this->assertInstanceOf( WP_Ability::class, $ability, 'The core/content-update ability should be registered.' );
+ $this->assertSame( 'Update Content', $ability->get_label(), 'The ability should have its label.' );
+ $this->assertSame( 'content', $ability->get_category(), 'The ability should use the content category.' );
+ $this->assertTrue( $ability->get_meta_item( 'public', false ), 'The ability should be marked public.' );
+
+ $annotations = $ability->get_meta_item( 'annotations', array() );
+ $this->assertFalse( $annotations['readonly'], 'The ability should not be marked read-only.' );
+ $this->assertFalse( $annotations['destructive'], 'The ability should not be marked destructive.' );
+ $this->assertTrue( $annotations['idempotent'], 'The ability should be marked idempotent.' );
+ }
+
+ /**
+ * The ability is not registered when no post type is exposed to abilities.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_is_not_registered_without_exposed_post_types(): void {
+ foreach ( array( 'post', 'page' ) as $post_type ) {
+ get_post_type_object( $post_type )->show_in_abilities = false;
+ }
+
+ $this->register_abilities();
+
+ $this->assertFalse( wp_has_ability( self::ABILITY ), 'The update ability should not be registered without an exposed post type.' );
+ }
+
+ /**
+ * The input schema takes `where`, with the post type and ID, `data`, with at least one
+ * attribute, and `fields`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_input_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The update ability should be registered.' );
+
+ $schema = wp_get_ability( self::ABILITY )->get_input_schema();
+
+ $this->assertSame( 'object', $schema['type'], 'The input should be an object.' );
+ $this->assertFalse( $schema['additionalProperties'], 'The input should reject unknown keys.' );
+ $this->assertSame( array( 'where', 'data' ), $schema['required'], 'The input should require where and data.' );
+ $this->assertSame( array( 'where', 'data', 'fields' ), array_keys( $schema['properties'] ), 'The input should take where, data and fields.' );
+
+ $where = $schema['properties']['where'];
+
+ $this->assertSame( 'object', $where['type'], 'The where should be an object.' );
+ $this->assertFalse( $where['additionalProperties'], 'The where should reject unknown keys.' );
+ $this->assertSame( array( 'type', 'id' ), $where['required'], 'The where should require the type and the ID.' );
+ $this->assertSame( array( 'type', 'id' ), array_keys( $where['properties'] ), 'The where should take the type and the ID.' );
+ $this->assertSame( 'string', $where['properties']['type']['type'], 'The type should be a string.' );
+ $this->assertSameSets( array( 'post', 'page' ), $where['properties']['type']['enum'], 'The type should list the exposed post types.' );
+ $this->assertSame( 'integer', $where['properties']['id']['type'], 'The ID should be an integer.' );
+ $this->assertSame( 1, $where['properties']['id']['minimum'], 'The ID should be at least 1.' );
+
+ $data = $schema['properties']['data'];
+
+ $this->assertSame( 'object', $data['type'], 'The data should be an object.' );
+ $this->assertFalse( $data['additionalProperties'], 'The data should reject unknown keys.' );
+ $this->assertSame( 1, $data['minProperties'], 'The data should hold at least one attribute.' );
+ $this->assertArrayNotHasKey( 'required', $data, 'The data should require no attribute.' );
+ $this->assertSame( array( 'title', 'content', 'excerpt', 'status', 'slug', 'date', 'author', 'parent' ), array_keys( $data['properties'] ), 'The data should take the allowed attributes and no post type.' );
+ $this->assertSame( array( 'publish', 'future', 'draft', 'pending', 'private' ), $data['properties']['status']['enum'], 'The status should list the statuses that are not internal.' );
+ $this->assertSame( 1, $data['properties']['slug']['minLength'], 'The slug should not be empty.' );
+ $this->assertSame( 1, $data['properties']['author']['minimum'], 'The author should be at least 1.' );
+ $this->assertSame( 0, $data['properties']['parent']['minimum'], 'The parent should be at least 0.' );
+ $this->assertSame( 1, $data['properties']['date']['minProperties'], 'The date should hold at least one value.' );
+ $this->assertSame( array( 'site', 'gmt' ), array_keys( $data['properties']['date']['properties'] ), 'The date should take a site and a GMT value.' );
+
+ $create_schema = wp_get_ability( 'core/content-create' )->get_input_schema();
+ $create_data = $create_schema['properties']['data']['properties'];
+ unset( $create_data['type'] );
+
+ $this->assertSame( $this->strip_descriptions( $create_data ), $this->strip_descriptions( $data['properties'] ), 'The attributes should have the same schemas as on create.' );
+
+ $query_schema = wp_get_ability( 'core/content-query' )->get_input_schema();
+
+ $this->assertSame(
+ $this->strip_descriptions( $query_schema['properties']['fields'] ),
+ $this->strip_descriptions( $schema['properties']['fields'] ),
+ 'The fields should be the same list as the fields of the query.'
+ );
+ }
+
+ /**
+ * The output is one post item, the same object as an item of the query.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_output_schema_is_a_query_item(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The update ability should be registered.' );
+
+ $schema = wp_get_ability( self::ABILITY )->get_output_schema();
+ $item = wp_get_ability( 'core/content-query' )->get_output_schema()['properties']['items']['items'];
+
+ $this->assertSame( array( 'id' ), $schema['required'], 'The output should always hold the ID.' );
+ $this->assertSame( $this->strip_descriptions( $item ), $this->strip_descriptions( $schema ), 'The output should be the same object as a query item.' );
+ }
+
+ /**
+ * A new title and excerpt are stored, and the post is returned in the chosen fields.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_updates_the_title_and_excerpt(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'draft',
+ 'post_title' => 'Launch notes',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => 'Launch notes, updated',
+ 'excerpt' => 'What shipped and what is next.',
+ ),
+ array( 'modified', 'title', 'excerpt' )
+ );
+
+ $this->assert_updated( $result, $post_id );
+
+ $this->assertSameSets( array( 'id', 'modified', 'title', 'excerpt' ), array_keys( $result ), 'The ID and the chosen fields should be returned.' );
+ $this->assertSameSets( array( 'site', 'gmt' ), array_keys( $result['modified'] ), 'The modified date should be given in site time and GMT.' );
+ $this->assertNotFalse( rest_parse_date( $result['modified']['gmt'] ), 'The modified GMT date should be a date-time.' );
+ $this->assertSame(
+ array(
+ 'raw' => 'Launch notes, updated',
+ 'rendered' => 'Launch notes, updated',
+ ),
+ $result['title'],
+ 'The new title should be returned raw and rendered.'
+ );
+ $this->assertSame(
+ array(
+ 'raw' => 'What shipped and what is next.',
+ 'rendered' => "What shipped and what is next.
\n",
+ 'protected' => false,
+ ),
+ $result['excerpt'],
+ 'The new excerpt should be returned raw, rendered and unprotected.'
+ );
+ }
+
+ /**
+ * A draft is published by setting its status.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_publishes_the_draft(): void {
+ $this->set_permalink_structure( '/%postname%/' );
+
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'draft',
+ 'post_title' => 'Launch notes, updated',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'status' => 'publish' ), array( 'status', 'slug', 'link' ) );
+
+ $this->assertSame(
+ array(
+ 'id' => $post_id,
+ 'status' => 'publish',
+ 'slug' => 'launch-notes-updated',
+ 'link' => home_url( '/launch-notes-updated/' ),
+ ),
+ $result,
+ 'The published post should be returned in the chosen fields.'
+ );
+ }
+
+ /**
+ * A post the user cannot edit is refused by the permission callback.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_rejects_a_post_the_user_cannot_edit(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'title' => 'Launch notes' ) );
+
+ $this->assert_refused( $result, 'Updating a post of another user' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A permission result that a filter turned into a grant does not skip the capability check
+ * on the post.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_granted_permission_result_does_not_skip_the_capability_check(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+ add_filter( 'wp_ability_permission_result', '__return_true' );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'title' => 'Granted by a filter' ) );
+
+ $this->assert_error( $result, 'content_cannot_edit', 403, 'An update granted by a filter' );
+ $this->assertSame( 'Sorry, you are not allowed to edit this post.', $result->get_error_message(), 'The message should be the edit message.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A logged-out user is refused before the ability runs.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_refuses_a_logged_out_user(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'title' => 'Refused' ) );
+
+ $this->assertWPError( $result, 'The call should be refused.' );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The permission callback should refuse a logged-out user.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns inputs for which the permission callback returns false, even for an administrator.
+ *
+ * @return array The inputs.
+ */
+ public static function data_inputs_refused_by_the_permission_callback(): array {
+ return array(
+ 'no input' => array( null ),
+ 'no where' => array( array( 'data' => array( 'title' => 'x' ) ) ),
+ 'where that is a string' => array(
+ array(
+ 'where' => 'post',
+ 'data' => array( 'title' => 'x' ),
+ ),
+ ),
+ 'type that is a list' => array(
+ array(
+ 'where' => array(
+ 'type' => array( 'post' ),
+ 'id' => 1,
+ ),
+ 'data' => array( 'title' => 'x' ),
+ ),
+ ),
+ 'unexposed type' => array(
+ array(
+ 'where' => array(
+ 'type' => 'attachment',
+ 'id' => 1,
+ ),
+ 'data' => array( 'title' => 'x' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * The permission callback returns false for missing or malformed input.
+ *
+ * @ticket 66706
+ * @dataProvider data_inputs_refused_by_the_permission_callback
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_returns_false_for_malformed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should return false.' );
+ }
+
+ /**
+ * The permission callback returns false for a post the user cannot edit, in every form the
+ * post can be named in input that was not prepared.
+ *
+ * @ticket 66706
+ * @dataProvider data_unprepared_where_forms
+ * @since 7.3.0
+ *
+ * @param string $id_type The type to send the ID as.
+ * @param bool $as_object Whether to send `where` as an object.
+ */
+ public function test_permission_callback_returns_false_for_a_post_the_user_cannot_edit( string $id_type, bool $as_object ): void {
+ $this->login_as( 'contributor' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse(
+ $permission(
+ array(
+ 'where' => $this->build_unprepared_where( self::$post_ids['admin_post'], $id_type, $as_object ),
+ 'data' => array( 'title' => 'x' ),
+ )
+ ),
+ 'The permission callback should return false.'
+ );
+ }
+
+ /**
+ * The permission callback returns true for a post the user can edit.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_returns_true_for_a_post_the_user_can_edit(): void {
+ $this->login_as( 'author' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertTrue(
+ $permission(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => self::$post_ids['author:draft'],
+ ),
+ 'data' => array( 'title' => 'x' ),
+ )
+ ),
+ 'The permission callback should return true.'
+ );
+ }
+
+ /**
+ * The permission callback lets a post that does not exist through, so that the call returns
+ * the not-found error, also for a user who may edit nothing.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_lets_a_missing_post_through(): void {
+ $this->login_as( 'subscriber' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $input = array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => self::MISSING_ID,
+ ),
+ 'data' => array( 'title' => 'x' ),
+ );
+
+ $this->assertTrue( $permission( $input ), 'The permission callback should return true.' );
+ $this->assert_not_found( $this->run_ability( $input ), 'A missing post' );
+ }
+
+ /**
+ * Returns ID values that are not a whole number of at least 1.
+ *
+ * @return array The IDs.
+ */
+ public static function data_ids_that_are_not_whole_numbers_of_at_least_1(): array {
+ return array(
+ 'digits and letters' => array( '123abc' ),
+ 'fraction' => array( 1.5 ),
+ 'zero' => array( 0 ),
+ 'negative' => array( -1 ),
+ 'true' => array( true ),
+ 'null' => array( null ),
+ 'list' => array( array( 1 ) ),
+ 'empty string' => array( '' ),
+ );
+ }
+
+ /**
+ * An ID that is not a whole number of at least 1 fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_ids_that_are_not_whole_numbers_of_at_least_1
+ * @since 7.3.0
+ *
+ * @param mixed $id The ID.
+ */
+ public function test_id_that_is_not_a_whole_number_fails_input_validation( $id ): void {
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( self::$post_ids['admin_post'] );
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $id,
+ ),
+ 'data' => array( 'title' => 'Invalid ID' ),
+ )
+ );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the ID.' );
+ $this->assertSame( $before, $this->snapshot( self::$post_ids['admin_post'] ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A revision, an autosave, an attachment, a post of another exposed or non-exposed type and a
+ * missing post are not found as a `post`, even by an administrator.
+ *
+ * @ticket 66706
+ * @dataProvider data_posts_that_are_not_posts
+ * @since 7.3.0
+ *
+ * @param string $post The post, as a fixture name.
+ */
+ public function test_post_of_another_type_is_not_found( string $post ): void {
+ $post_id = self::$post_ids[ $post ] ?? self::MISSING_ID;
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Wrong type' ),
+ )
+ );
+
+ $this->assert_not_found( $result, 'A post that is not a post' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Called directly, a post of a type that is not exposed is not found, whatever its ID.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_direct_call_for_a_type_that_is_not_exposed_is_not_found(): void {
+ register_post_type( 'cw_hidden', array( 'public' => true ) );
+ $post_id = self::factory()->post->create( array( 'post_type' => 'cw_hidden' ) );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'cw_hidden',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Hidden' ),
+ )
+ );
+
+ $this->assert_not_found( $result, 'A direct call for a type that is not exposed' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A post type whose `show_in_abilities` is turned off after registration cannot be updated.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_type_no_longer_exposed_cannot_be_updated(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'administrator' );
+ $callbacks = $this->get_ability_callbacks();
+
+ get_post_type_object( 'post' )->show_in_abilities = false;
+
+ $input = array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Hidden' ),
+ );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $input );
+
+ $this->assertWPError( $result, 'The regular call should fail.' );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The permission callback should refuse a type that is no longer exposed.' );
+ $this->assert_not_found( $callbacks['execute_callback']( $input ), 'A direct call for a type that is no longer exposed' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns direct-call inputs with a malformed `where`.
+ *
+ * @return array}> The inputs.
+ */
+ public static function data_direct_inputs_with_a_malformed_where(): array {
+ return array(
+ 'no where' => array( array( 'data' => array( 'title' => 'x' ) ) ),
+ 'no type' => array(
+ array(
+ 'where' => array( 'id' => 1 ),
+ 'data' => array( 'title' => 'x' ),
+ ),
+ ),
+ 'no ID' => array(
+ array(
+ 'where' => array( 'type' => 'post' ),
+ 'data' => array( 'title' => 'x' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Called directly, a malformed `where` is the not-found error.
+ *
+ * @ticket 66706
+ * @dataProvider data_direct_inputs_with_a_malformed_where
+ * @since 7.3.0
+ *
+ * @param array $input The input.
+ */
+ public function test_direct_call_with_a_malformed_where_is_not_found( array $input ): void {
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( self::$post_ids['administrator:draft'] );
+
+ $this->assert_not_found( $execute( $input ), 'A direct call with a malformed where' );
+ $this->assertSame( $before, $this->snapshot( self::$post_ids['administrator:draft'] ), 'Nothing should be written for a malformed where.' );
+ }
+
+ /**
+ * The lookup comes before everything else: a missing post with invalid data is not found.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_lookup_comes_before_the_attribute_rules(): void {
+ $this->login_as( 'subscriber' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( self::$post_ids['administrator:draft'] );
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => self::MISSING_ID,
+ ),
+ 'data' => array(
+ 'status' => 'trash',
+ 'parent' => 1,
+ 'title' => array( 'x' ),
+ ),
+ )
+ );
+
+ $this->assert_not_found( $result, 'A missing post with invalid data' );
+ $this->assertSame( $before, $this->snapshot( self::$post_ids['administrator:draft'] ), 'Nothing should be written for a missing post.' );
+ }
+
+ /**
+ * Returns whether each role may edit each matrix post.
+ *
+ * @return array The cases.
+ */
+ public static function data_update_matrix(): array {
+ return array(
+ 'administrator, own, draft' => array( 'administrator', 'administrator', 'draft', true ),
+ 'administrator, own, pending' => array( 'administrator', 'administrator', 'pending', true ),
+ 'administrator, own, publish' => array( 'administrator', 'administrator', 'publish', true ),
+ 'administrator, own, future' => array( 'administrator', 'administrator', 'future', true ),
+ 'administrator, own, private' => array( 'administrator', 'administrator', 'private', true ),
+ 'administrator, own, trash_draft' => array( 'administrator', 'administrator', 'trash_draft', true ),
+ 'administrator, own, trash_publish' => array( 'administrator', 'administrator', 'trash_publish', true ),
+ 'administrator, other, draft' => array( 'administrator', 'other', 'draft', true ),
+ 'administrator, other, pending' => array( 'administrator', 'other', 'pending', true ),
+ 'administrator, other, publish' => array( 'administrator', 'other', 'publish', true ),
+ 'administrator, other, future' => array( 'administrator', 'other', 'future', true ),
+ 'administrator, other, private' => array( 'administrator', 'other', 'private', true ),
+ 'administrator, other, trash_draft' => array( 'administrator', 'other', 'trash_draft', true ),
+ 'administrator, other, trash_publish' => array( 'administrator', 'other', 'trash_publish', true ),
+ 'editor, own, draft' => array( 'editor', 'editor', 'draft', true ),
+ 'editor, own, pending' => array( 'editor', 'editor', 'pending', true ),
+ 'editor, own, publish' => array( 'editor', 'editor', 'publish', true ),
+ 'editor, own, future' => array( 'editor', 'editor', 'future', true ),
+ 'editor, own, private' => array( 'editor', 'editor', 'private', true ),
+ 'editor, own, trash_draft' => array( 'editor', 'editor', 'trash_draft', true ),
+ 'editor, own, trash_publish' => array( 'editor', 'editor', 'trash_publish', true ),
+ 'editor, other, draft' => array( 'editor', 'other', 'draft', true ),
+ 'editor, other, pending' => array( 'editor', 'other', 'pending', true ),
+ 'editor, other, publish' => array( 'editor', 'other', 'publish', true ),
+ 'editor, other, future' => array( 'editor', 'other', 'future', true ),
+ 'editor, other, private' => array( 'editor', 'other', 'private', true ),
+ 'editor, other, trash_draft' => array( 'editor', 'other', 'trash_draft', true ),
+ 'editor, other, trash_publish' => array( 'editor', 'other', 'trash_publish', true ),
+ 'author, own, draft' => array( 'author', 'author', 'draft', true ),
+ 'author, own, pending' => array( 'author', 'author', 'pending', true ),
+ 'author, own, publish' => array( 'author', 'author', 'publish', true ),
+ 'author, own, future' => array( 'author', 'author', 'future', true ),
+ 'author, own, private' => array( 'author', 'author', 'private', true ),
+ 'author, own, trash_draft' => array( 'author', 'author', 'trash_draft', true ),
+ 'author, own, trash_publish' => array( 'author', 'author', 'trash_publish', true ),
+ 'author, other, draft' => array( 'author', 'other', 'draft', false ),
+ 'author, other, pending' => array( 'author', 'other', 'pending', false ),
+ 'author, other, publish' => array( 'author', 'other', 'publish', false ),
+ 'author, other, future' => array( 'author', 'other', 'future', false ),
+ 'author, other, private' => array( 'author', 'other', 'private', false ),
+ 'author, other, trash_draft' => array( 'author', 'other', 'trash_draft', false ),
+ 'author, other, trash_publish' => array( 'author', 'other', 'trash_publish', false ),
+ 'contributor, own, draft' => array( 'contributor', 'contributor', 'draft', true ),
+ 'contributor, own, pending' => array( 'contributor', 'contributor', 'pending', true ),
+ 'contributor, own, publish' => array( 'contributor', 'contributor', 'publish', false ),
+ 'contributor, own, future' => array( 'contributor', 'contributor', 'future', false ),
+ 'contributor, own, private' => array( 'contributor', 'contributor', 'private', true ),
+ 'contributor, own, trash_draft' => array( 'contributor', 'contributor', 'trash_draft', true ),
+ 'contributor, own, trash_publish' => array( 'contributor', 'contributor', 'trash_publish', false ),
+ 'contributor, other, draft' => array( 'contributor', 'other', 'draft', false ),
+ 'contributor, other, pending' => array( 'contributor', 'other', 'pending', false ),
+ 'contributor, other, publish' => array( 'contributor', 'other', 'publish', false ),
+ 'contributor, other, future' => array( 'contributor', 'other', 'future', false ),
+ 'contributor, other, private' => array( 'contributor', 'other', 'private', false ),
+ 'contributor, other, trash_draft' => array( 'contributor', 'other', 'trash_draft', false ),
+ 'contributor, other, trash_publish' => array( 'contributor', 'other', 'trash_publish', false ),
+ 'subscriber, own, draft' => array( 'subscriber', 'subscriber', 'draft', false ),
+ 'subscriber, own, pending' => array( 'subscriber', 'subscriber', 'pending', false ),
+ 'subscriber, own, publish' => array( 'subscriber', 'subscriber', 'publish', false ),
+ 'subscriber, own, future' => array( 'subscriber', 'subscriber', 'future', false ),
+ 'subscriber, own, private' => array( 'subscriber', 'subscriber', 'private', false ),
+ 'subscriber, own, trash_draft' => array( 'subscriber', 'subscriber', 'trash_draft', false ),
+ 'subscriber, own, trash_publish' => array( 'subscriber', 'subscriber', 'trash_publish', false ),
+ 'subscriber, other, draft' => array( 'subscriber', 'other', 'draft', false ),
+ 'subscriber, other, pending' => array( 'subscriber', 'other', 'pending', false ),
+ 'subscriber, other, publish' => array( 'subscriber', 'other', 'publish', false ),
+ 'subscriber, other, future' => array( 'subscriber', 'other', 'future', false ),
+ 'subscriber, other, private' => array( 'subscriber', 'other', 'private', false ),
+ 'subscriber, other, trash_draft' => array( 'subscriber', 'other', 'trash_draft', false ),
+ 'subscriber, other, trash_publish' => array( 'subscriber', 'other', 'trash_publish', false ),
+ );
+ }
+
+ /**
+ * Each role may update the posts it may edit, in any status, and is refused for the others,
+ * whatever their status.
+ *
+ * @ticket 66706
+ * @dataProvider data_update_matrix
+ * @since 7.3.0
+ *
+ * @param string $role The role to update as.
+ * @param string $owner The role of the author of the post, or `other`.
+ * @param string $status The matrix status of the post.
+ * @param bool $allowed Whether the update is allowed.
+ */
+ public function test_update_matrix( string $role, string $owner, string $status, bool $allowed ): void {
+ $post_id = self::$post_ids[ "{$owner}:{$status}" ];
+ $stored_status = get_post_status( $post_id );
+
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'title' => 'Matrix update' ), array( 'status', 'title.rendered' ) );
+
+ if ( ! $allowed ) {
+ $this->assert_refused( $result, 'Updating a post the role may not edit' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ return;
+ }
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'Matrix update', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( $stored_status, $post->post_status, 'The status should not change.' );
+ $this->assertSame( $stored_status, $result['status'], 'The stored status should be returned.' );
+ $this->assertSame( array( 'rendered' => 'Matrix update' ), $result['title'], 'The new title should be returned.' );
+ }
+
+ /**
+ * Returns `data` values that are invalid in some way.
+ *
+ * @return array}> The data.
+ */
+ public static function data_invalid_data(): array {
+ return array(
+ 'parent on a post' => array( array( 'parent' => 1 ) ),
+ 'trash' => array( array( 'status' => 'trash' ) ),
+ 'publish' => array( array( 'status' => 'publish' ) ),
+ 'empty slug' => array( array( 'slug' => '!!!' ) ),
+ 'missing author' => array( array( 'author' => self::MISSING_ID ) ),
+ 'title that is a list' => array( array( 'title' => array( 'x' ) ) ),
+ 'invalid date' => array( array( 'date' => array( 'site' => 'not a date' ) ) ),
+ 'empty data' => array( array() ),
+ );
+ }
+
+ /**
+ * Called directly by a user who may not edit the post, the call fails on the capability before
+ * anything about the attributes is checked.
+ *
+ * @ticket 66706
+ * @dataProvider data_invalid_data
+ * @since 7.3.0
+ *
+ * @param array $data The data.
+ */
+ public function test_direct_call_without_edit_post_fails_before_the_attributes( array $data ): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'contributor' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => $data,
+ )
+ );
+
+ $this->assert_error( $result, 'content_cannot_edit', 403, 'A direct call without edit_post' );
+ $this->assertSame( 'Sorry, you are not allowed to edit this post.', $result->get_error_message(), 'The message should be the edit message.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns keys that are not part of the input, and where they are sent.
+ *
+ * @return array The cases.
+ */
+ public static function data_keys_outside_the_allow_list(): array {
+ return array(
+ 'data ID' => array( 'data', 'ID', 1 ),
+ 'data type' => array( 'data', 'type', 'page' ),
+ 'data post_type' => array( 'data', 'post_type', 'page' ),
+ 'data post_password' => array( 'data', 'post_password', 'secret' ),
+ 'data meta_input' => array( 'data', 'meta_input', array( 'cw_key' => 'value' ) ),
+ 'data tax_input' => array( 'data', 'tax_input', array( 'category' => array( 1 ) ) ),
+ 'data comment_status' => array( 'data', 'comment_status', 'closed' ),
+ 'data post_author' => array( 'data', 'post_author', 1 ),
+ 'data import_id' => array( 'data', 'import_id', 7654321 ),
+ 'data guid' => array( 'data', 'guid', 'https://example.org/forged' ),
+ 'data page_template' => array( 'data', 'page_template', 'cw-template.php' ),
+ 'data modified' => array( 'data', 'modified', '2001-01-01T00:00:00' ),
+ 'data post_modified' => array( 'data', 'post_modified', '2001-01-01 00:00:00' ),
+ 'data post_modified_gmt' => array( 'data', 'post_modified_gmt', '2001-01-01 00:00:00' ),
+ 'data sticky' => array( 'data', 'sticky', true ),
+ 'data tags_input' => array( 'data', 'tags_input', array( 'cw-tag' ) ),
+ 'data post_category' => array( 'data', 'post_category', array( 2 ) ),
+ 'data menu_order' => array( 'data', 'menu_order', 5 ),
+ 'data post_mime_type' => array( 'data', 'post_mime_type', 'image/jpeg' ),
+ 'where status' => array( 'where', 'status', 'draft' ),
+ 'where ID' => array( 'where', 'ID', 1 ),
+ );
+ }
+
+ /**
+ * A key outside the allow-list fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_keys_outside_the_allow_list
+ * @since 7.3.0
+ *
+ * @param string $location Where the key is sent.
+ * @param string $key The key.
+ * @param mixed $value The value.
+ */
+ public function test_key_outside_the_allow_list_fails_input_validation( string $location, string $key, $value ): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $input = array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Extra key' ),
+ );
+
+ $input[ $location ][ $key ] = $value;
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $input );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the key.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * An internal or unregistered status fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_that_can_never_be_set
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_status_that_can_never_be_set_fails_input_validation( string $status ): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'status' => $status ) );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the status.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Called directly, an internal or unregistered status is an invalid status for a post that
+ * is not stored in it.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_that_can_never_be_set
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_direct_call_rejects_a_status_that_can_never_be_set( string $status ): void {
+ $post_id = self::$post_ids['administrator:publish'];
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'status' => $status ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'status', 'A direct call with a status that can never be set' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns status changes that a contributor, and an author denied `publish_posts`, may not
+ * make on their own draft.
+ *
+ * @return array The cases.
+ */
+ public static function data_status_changes_without_publish_posts(): array {
+ $publish_message = 'Sorry, you are not allowed to publish posts in this post type.';
+ $private_message = 'Sorry, you are not allowed to create private posts in this post type.';
+
+ return array(
+ 'publish by a contributor' => array( 'contributor', 'publish', $publish_message ),
+ 'future by a contributor' => array( 'contributor', 'future', $publish_message ),
+ 'private by a contributor' => array( 'contributor', 'private', $private_message ),
+ 'publish by an author denied publish_posts' => array( 'restricted_author', 'publish', $publish_message ),
+ 'future by an author denied publish_posts' => array( 'restricted_author', 'future', $publish_message ),
+ 'private by an author denied publish_posts' => array( 'restricted_author', 'private', $private_message ),
+ );
+ }
+
+ /**
+ * A status that makes a post visible needs `publish_posts`.
+ *
+ * @ticket 66706
+ * @dataProvider data_status_changes_without_publish_posts
+ * @since 7.3.0
+ *
+ * @param string $role The role or fixture name of the user, who owns the draft.
+ * @param string $status The status.
+ * @param string $message The error message.
+ */
+ public function test_status_that_makes_a_post_visible_needs_publish_posts( string $role, string $status, string $message ): void {
+ $post_id = self::$post_ids[ "{$role}:draft" ];
+
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $this->assertFalse( current_user_can( 'publish_posts' ), 'Precondition: the user should not be able to publish posts.' );
+
+ $data = array( 'status' => $status );
+ if ( 'future' === $status ) {
+ $data['date'] = array( 'gmt' => '2099-06-01T12:00:00' );
+ }
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, $data );
+
+ $this->assert_error( $result, 'content_cannot_publish', 403, 'A status that makes a post visible without publish_posts' );
+ $this->assertSame( $message, $result->get_error_message(), 'The message should name what the role may not do.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A status equal to the stored status changes nothing and passes with no check.
+ *
+ * A contributor may edit their own private post, but may not make a post private.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_status_equal_to_the_stored_status_passes_with_no_check(): void {
+ $post_id = self::$post_ids['contributor:private'];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => 'private',
+ 'title' => 'Still private',
+ )
+ );
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'private', $post->post_status, 'The post should stay private.' );
+ $this->assertSame( 'Still private', $post->post_title, 'The title should be stored.' );
+ }
+
+ /**
+ * A draft is scheduled with `future` and a date in the future.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_schedules_a_draft(): void {
+ $post_id = self::$post_ids['author:draft'];
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => 'future',
+ 'date' => array( 'gmt' => '2099-06-01T12:00:00' ),
+ ),
+ array( 'status', 'date' )
+ );
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'future', $post->post_status, 'The post should be scheduled.' );
+ $this->assertSame( '2099-06-01 12:00:00', $post->post_date_gmt, 'The post should be scheduled for the sent date.' );
+ $this->assertSame( 'future', $result['status'], 'The scheduled status should be returned.' );
+ }
+
+ /**
+ * Returns statuses a published post can be moved back to.
+ *
+ * @return array The statuses.
+ */
+ public static function data_unpublished_statuses(): array {
+ return array(
+ 'draft' => array( 'draft' ),
+ 'pending' => array( 'pending' ),
+ );
+ }
+
+ /**
+ * A published post can be unpublished.
+ *
+ * @ticket 66706
+ * @dataProvider data_unpublished_statuses
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_unpublishes_a_post( string $status ): void {
+ $post_id = self::$post_ids['editor:publish'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'status' => $status ), array( 'status' ) );
+
+ $this->assertSame( $status, $this->assert_updated( $result, $post_id )->post_status, 'The post should be unpublished.' );
+ $this->assertSame( $status, $result['status'], 'The new status should be returned.' );
+ }
+
+ /**
+ * Returns dates that change the stored status of a post.
+ *
+ * @return array The cases.
+ */
+ public static function data_statuses_reported_as_stored(): array {
+ return array(
+ 'publish with a future date' => array( 'publish', '2099-06-01T12:00:00', 'future' ),
+ 'future with a past date' => array( 'future', '2016-12-12T19:00:00', 'publish' ),
+ );
+ }
+
+ /**
+ * The regular save rules decide the stored status, and the output reports it.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_reported_as_stored
+ * @since 7.3.0
+ *
+ * @param string $status The requested status.
+ * @param string $gmt The requested GMT date.
+ * @param string $expected The stored status.
+ */
+ public function test_output_reports_the_stored_status( string $status, string $gmt, string $expected ): void {
+ $post_id = self::$post_ids['editor:draft'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => $status,
+ 'date' => array( 'gmt' => $gmt ),
+ ),
+ array( 'status' )
+ );
+
+ $this->assertSame( $expected, $this->assert_updated( $result, $post_id )->post_status, 'The post should be stored in the expected status.' );
+ $this->assertSame( $expected, $result['status'], 'The output should report the stored status.' );
+ }
+
+ /**
+ * A post in the Trash is updated like any other post and stays in the Trash.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_updates_a_post_in_the_trash(): void {
+ $post_id = self::$post_ids['editor:trash_publish'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'title' => 'Trashed and edited' ), array( 'status' ) );
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'Trashed and edited', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( 'trash', $post->post_status, 'The post should stay in the Trash.' );
+ $this->assertSame( 'trash', $result['status'], 'The trash status should be returned.' );
+ }
+
+ /**
+ * Returns status changes that move a post out of the Trash.
+ *
+ * @return array The cases.
+ */
+ public static function data_statuses_that_move_a_post_out_of_the_trash(): array {
+ return array(
+ 'draft by a contributor' => array( 'contributor', 'draft' ),
+ 'pending by an author' => array( 'author', 'pending' ),
+ 'publish by an author' => array( 'author', 'publish' ),
+ );
+ }
+
+ /**
+ * Sending a status moves a post out of the Trash through a plain update.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_that_move_a_post_out_of_the_trash
+ * @since 7.3.0
+ *
+ * @param string $role The role, which owns the post.
+ * @param string $status The status.
+ */
+ public function test_status_moves_a_post_out_of_the_trash( string $role, string $status ): void {
+ $post_id = self::$post_ids[ "{$role}:trash_draft" ];
+
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'status' => $status ), array( 'status' ) );
+
+ $this->assertSame( $status, $this->assert_updated( $result, $post_id )->post_status, 'The post should leave the Trash in the sent status.' );
+ $this->assertSame( $status, $result['status'], 'The new status should be returned.' );
+ }
+
+ /**
+ * Moving a post out of the Trash passes the status gate like any status change.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_publishing_a_post_from_the_trash_needs_publish_posts(): void {
+ $post_id = self::$post_ids['contributor:trash_draft'];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'status' => 'publish' ) );
+
+ $this->assert_error( $result, 'content_cannot_publish', 403, 'Publishing a post from the Trash without publish_posts' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A user without `edit_others_posts` gets the same error for an existing and a missing
+ * author, so the error never tells whether a user exists.
+ *
+ * @ticket 66706
+ * @dataProvider data_authors_named_without_edit_others_posts
+ * @since 7.3.0
+ *
+ * @param string $author The author, as a fixture name.
+ */
+ public function test_naming_another_author_without_edit_others_posts_is_refused( string $author ): void {
+ $post_id = self::$post_ids['author:draft'];
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'author' => self::$user_ids[ $author ] ?? self::MISSING_ID ) );
+
+ $this->assertWPError( $result, 'Naming another author should fail.' );
+ $this->assertSame(
+ array(
+ 'code' => 'content_cannot_edit_others',
+ 'message' => 'Sorry, you are not allowed to update posts as this user.',
+ 'data' => array( 'status' => 403 ),
+ ),
+ array(
+ 'code' => $result->get_error_code(),
+ 'message' => $result->get_error_message(),
+ 'data' => $result->get_error_data(),
+ ),
+ 'The error should be the same whether the user exists or not.'
+ );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A user with `edit_others_posts` may change the author of a post.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_changes_the_author(): void {
+ $post_id = self::$post_ids['editor:draft'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'author' => self::$user_ids['author'] ), array( 'author.id' ) );
+
+ $this->assertSame( self::$user_ids['author'], (int) $this->assert_updated( $result, $post_id )->post_author, 'The new author should be stored.' );
+ $this->assertSame( array( 'id' => self::$user_ids['author'] ), $result['author'], 'The new author should be returned.' );
+ }
+
+ /**
+ * An author equal to the stored author changes nothing and passes with no check, even when
+ * that user no longer exists.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_author_equal_to_the_stored_author_passes_with_no_check(): void {
+ global $wpdb;
+
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_status' => 'draft',
+ )
+ );
+ $wpdb->update( $wpdb->posts, array( 'post_author' => self::MISSING_ID ), array( 'ID' => $post_id ) );
+ clean_post_cache( $post_id );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'author' => self::MISSING_ID,
+ 'title' => 'Orphan',
+ )
+ );
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'Orphan', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( self::MISSING_ID, (int) $post->post_author, 'The stored author should not change.' );
+ }
+
+ /**
+ * A user with `edit_others_posts` who names a missing user gets the invalid author error.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_naming_a_missing_author_with_edit_others_posts_is_an_invalid_author(): void {
+ $post_id = self::$post_ids['editor:draft'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'author' => self::MISSING_ID ) );
+
+ $this->assert_invalid_attribute( $result, 'author', 'A missing author' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * On multisite, a user who is not a member of the site cannot be the author.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_naming_an_author_who_is_not_a_member_of_the_site_is_an_invalid_author(): void {
+ $non_member = self::factory()->user->create( array( 'role' => 'author' ) );
+ remove_user_from_blog( $non_member, get_current_blog_id() );
+
+ $post_id = self::$post_ids['editor:draft'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'author' => $non_member ) );
+
+ $this->assert_invalid_attribute( $result, 'author', 'An author who is not a member of the site' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns parents that a page may not have.
+ *
+ * @return array The parents, as fixture names.
+ */
+ public static function data_parents_that_cannot_be_used(): array {
+ return array(
+ 'missing post' => array( 'missing' ),
+ 'post of another type' => array( 'admin_post' ),
+ 'page the user may not read' => array( 'editor_draft_page' ),
+ 'the page itself' => array( 'writer_page' ),
+ 'a child' => array( 'writer_child' ),
+ 'a grandchild' => array( 'writer_grandchild' ),
+ 'revision' => array( 'revision' ),
+ );
+ }
+
+ /**
+ * A missing parent, a parent of another type, a parent the user may not read and a parent
+ * that would make a loop give one identical error.
+ *
+ * @ticket 66706
+ * @dataProvider data_parents_that_cannot_be_used
+ * @since 7.3.0
+ *
+ * @param string $parent_key The parent, as a fixture name.
+ */
+ public function test_parent_that_cannot_be_used_gives_one_identical_error( string $parent_key ): void {
+ $post_id = self::$post_ids['writer_page'];
+
+ $this->login_as( 'page_writer' );
+ $this->register_abilities();
+
+ $this->assertTrue( current_user_can( 'edit_post', $post_id ), 'Precondition: the user should be able to edit the page.' );
+ $this->assertFalse( current_user_can( 'read_post', self::$post_ids['editor_draft_page'] ), 'Precondition: the user should not be able to read the draft page of the editor.' );
+
+ $before = $this->snapshot( $post_id );
+ $reference = $this->update_post( $post_id, array( 'parent' => self::MISSING_ID ) );
+ $result = $this->update_post( $post_id, array( 'parent' => self::$post_ids[ $parent_key ] ?? self::MISSING_ID ) );
+
+ $this->assert_invalid_attribute( $result, 'parent', 'A parent that cannot be used' );
+ $this->assertSame( $reference->get_error_data(), $result->get_error_data(), 'The error data, with its reason, should be the same as for a missing parent.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A parent equal to the stored parent changes nothing and passes with no check, even when the
+ * user may not read it.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_parent_equal_to_the_stored_parent_passes_with_no_check(): void {
+ $post_id = self::$post_ids['writer_page_with_hidden_parent'];
+
+ $this->login_as( 'page_writer' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'parent' => self::$post_ids['editor_draft_page'],
+ 'title' => 'Same parent',
+ )
+ );
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'Same parent', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( self::$post_ids['editor_draft_page'], $post->post_parent, 'The stored parent should not change.' );
+ }
+
+ /**
+ * Returns parents a page may be moved to.
+ *
+ * @return array The parents, as fixture names, or null for 0.
+ */
+ public static function data_parents_that_can_be_used(): array {
+ return array(
+ 'readable page' => array( 'admin_page' ),
+ 'top level' => array( null ),
+ );
+ }
+
+ /**
+ * A readable page of the same type can be the parent, and `0` makes the page a top-level page.
+ *
+ * @ticket 66706
+ * @dataProvider data_parents_that_can_be_used
+ * @since 7.3.0
+ *
+ * @param string|null $parent_key The parent, as a fixture name, or null for 0.
+ */
+ public function test_moves_a_page_to_another_parent( ?string $parent_key ): void {
+ $post_id = self::$post_ids['writer_page_with_hidden_parent'];
+ $parent_id = null === $parent_key ? 0 : self::$post_ids[ $parent_key ];
+
+ $this->login_as( 'page_writer' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'parent' => $parent_id ), array( 'parent' ) );
+
+ $this->assertSame( $parent_id, $this->assert_updated( $result, $post_id )->post_parent, 'The new parent should be stored.' );
+ $this->assertSame( $parent_id, $result['parent'], 'The new parent should be returned.' );
+ }
+
+ /**
+ * Returns attributes that a post type does not support.
+ *
+ * @return array The cases.
+ */
+ public static function data_unsupported_attributes(): array {
+ return array(
+ 'excerpt of a page' => array( 'admin_page', 'excerpt', 'An excerpt' ),
+ 'parent of a post' => array( 'admin_post', 'parent', 1 ),
+ 'parent 0 of a post' => array( 'admin_post', 'parent', 0 ),
+ );
+ }
+
+ /**
+ * An attribute the post type does not support is rejected, even when it would change nothing.
+ *
+ * @ticket 66706
+ * @dataProvider data_unsupported_attributes
+ * @since 7.3.0
+ *
+ * @param string $post The post, as a fixture name.
+ * @param string $attribute The attribute.
+ * @param mixed $value The value.
+ */
+ public function test_unsupported_attribute_is_rejected( string $post, string $attribute, $value ): void {
+ $post_id = self::$post_ids[ $post ];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( $attribute => $value ) );
+
+ $this->assert_invalid_attribute( $result, $attribute, 'An unsupported attribute' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns attribute values of the wrong type.
+ *
+ * @return array The cases.
+ */
+ public static function data_values_of_the_wrong_type(): array {
+ return array(
+ 'title that is a number' => array( 'title', 123 ),
+ 'content that is null' => array( 'content', null ),
+ 'status that is a list' => array( 'status', array( 'draft' ) ),
+ 'date that is a string' => array( 'date', '2016-12-12T14:00:00' ),
+ 'date that cannot be parsed' => array( 'date', array( 'site' => 'not a date' ) ),
+ 'author that is a fraction' => array( 'author', 1.5 ),
+ 'author that is text' => array( 'author', '1abc' ),
+ );
+ }
+
+ /**
+ * A value of the wrong type fails input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_values_of_the_wrong_type
+ * @since 7.3.0
+ *
+ * @param string $attribute The attribute.
+ * @param mixed $value The value.
+ */
+ public function test_value_of_the_wrong_type_fails_input_validation( string $attribute, $value ): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( $attribute => $value ) );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the value.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Attributes that were not sent keep their stored values.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_attributes_not_sent_keep_their_stored_values(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['author'],
+ 'post_status' => 'publish',
+ 'post_title' => 'Kept title',
+ 'post_content' => 'Kept content.',
+ 'post_excerpt' => 'Kept excerpt.',
+ 'post_name' => 'kept-slug',
+ 'post_date' => '2016-12-12 14:00:00',
+ )
+ );
+ $stored = get_post( $post_id );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'content' => 'New content.' ) ), $post_id );
+
+ $this->assertSame( 'New content.', $post->post_content, 'The content should be stored.' );
+ $this->assertSame( $stored->post_title, $post->post_title, 'The title should be kept.' );
+ $this->assertSame( $stored->post_excerpt, $post->post_excerpt, 'The excerpt should be kept.' );
+ $this->assertSame( $stored->post_name, $post->post_name, 'The slug should be kept.' );
+ $this->assertSame( $stored->post_status, $post->post_status, 'The status should be kept.' );
+ $this->assertSame( $stored->post_author, $post->post_author, 'The author should be kept.' );
+ $this->assertSame( $stored->post_date_gmt, $post->post_date_gmt, 'The date should be kept.' );
+ }
+
+ /**
+ * A slug that sanitizes to nothing is an invalid slug.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_that_sanitizes_to_nothing_is_rejected(): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'slug' => '!!!' ) );
+
+ $this->assert_invalid_attribute( $result, 'slug', 'A slug that sanitizes to nothing' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns updates that send a slug for a post that is, or becomes, pending.
+ *
+ * @return array}> The posts, as fixture names, and the data.
+ */
+ public static function data_slugs_of_pending_posts(): array {
+ return array(
+ 'draft moved to pending' => array(
+ 'contributor:draft',
+ array(
+ 'status' => 'pending',
+ 'slug' => 'pending-slug',
+ ),
+ ),
+ 'pending post' => array( 'contributor:pending', array( 'slug' => 'pending-slug' ) ),
+ );
+ }
+
+ /**
+ * A user who may not publish the post cannot set the slug of a pending post.
+ *
+ * Intentionally strict: the save would drop the slug, so it is an error instead of being
+ * dropped without notice.
+ *
+ * @ticket 66706
+ * @dataProvider data_slugs_of_pending_posts
+ * @since 7.3.0
+ *
+ * @param string $post The post, as a fixture name.
+ * @param array $data The `data` input.
+ */
+ public function test_slug_of_a_pending_post_is_rejected_without_publish_posts( string $post, array $data ): void {
+ $post_id = self::$post_ids[ $post ];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, $data );
+
+ $this->assert_invalid_attribute( $result, 'slug', 'A slug on a pending post without publish_posts' );
+ $this->assertSame( 'The slug of a pending post can only be set by a user who can publish the post.', $result->get_error_message(), 'The message should say who may set the slug.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written for a slug that cannot be stored.' );
+ }
+
+ /**
+ * A user who may publish the post sets the slug of a pending post.
+ *
+ * @ticket 66706
+ * @dataProvider data_slugs_of_pending_posts
+ * @since 7.3.0
+ *
+ * @param string $post The post, as a fixture name.
+ * @param array $data The `data` input.
+ */
+ public function test_slug_of_a_pending_post_is_stored_with_publish_posts( string $post, array $data ): void {
+ $post_id = self::$post_ids[ $post ];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, $data ), $post_id );
+
+ $this->assertSame( 'pending', $post->post_status, 'The post should be pending.' );
+ $this->assertSame( 'pending-slug', $post->post_name, 'The slug of the pending post should be stored.' );
+ }
+
+ /**
+ * Returns posts that take the slug of another post.
+ *
+ * @return array The cases.
+ */
+ public static function data_posts_taking_a_used_slug(): array {
+ return array(
+ 'stored draft' => array( 'administrator:draft', null ),
+ 'stored pending' => array( 'administrator:pending', null ),
+ 'draft from publish' => array( 'administrator:publish', 'draft' ),
+ 'published post' => array( 'administrator:publish', null ),
+ );
+ }
+
+ /**
+ * A post never takes the slug of another post, also as a draft or a pending post.
+ *
+ * @ticket 66706
+ * @dataProvider data_posts_taking_a_used_slug
+ * @since 7.3.0
+ *
+ * @param string $post The post, as a fixture name.
+ * @param string|null $status The status sent next to the slug, or null to send none.
+ */
+ public function test_slug_of_another_post_is_made_unique( string $post, ?string $status ): void {
+ $post_id = self::$post_ids[ $post ];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $data = array( 'slug' => 'Shared Slug' );
+ if ( null !== $status ) {
+ $data['status'] = $status;
+ }
+
+ $result = $this->update_post( $post_id, $data, array( 'slug' ) );
+
+ $this->assertSame( 'shared-slug-2', $this->assert_updated( $result, $post_id )->post_name, 'The sanitized slug should be made unique.' );
+ }
+
+ /**
+ * Returns parents for a draft page that takes the slug of an existing child page.
+ *
+ * @return array The cases.
+ */
+ public static function data_draft_page_slugs_by_parent(): array {
+ return array(
+ 'shared parent sent' => array( 'writer_page', 'writer-child-2' ),
+ 'different parent sent' => array( 'admin_page', 'writer-child' ),
+ );
+ }
+
+ /**
+ * A draft page is made unique among the pages that share the sent parent.
+ *
+ * @ticket 66706
+ * @dataProvider data_draft_page_slugs_by_parent
+ * @since 7.3.0
+ *
+ * @param string $parent_key The parent, as a fixture name.
+ * @param string $expected The stored slug.
+ */
+ public function test_draft_page_slug_is_unique_among_its_siblings( string $parent_key, string $expected ): void {
+ self::factory()->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_parent' => self::$post_ids['writer_page'],
+ 'post_name' => 'writer-child',
+ )
+ );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ 'post_title' => 'Moving page',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'slug' => 'writer-child',
+ 'parent' => self::$post_ids[ $parent_key ],
+ )
+ );
+
+ $this->assertSame( $expected, $this->assert_updated( $result, $post_id )->post_name, 'The slug should be unique among the siblings.' );
+ }
+
+ /**
+ * An update without a date keeps a floating draft floating.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_update_without_a_date_keeps_a_draft_floating(): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'title' => 'Still floating' ) ), $post_id );
+
+ $this->assertSame( 'draft', $post->post_status, 'The post should stay a draft.' );
+ $this->assertSame( '0000-00-00 00:00:00', $post->post_date_gmt, 'The draft should keep floating.' );
+ }
+
+ /**
+ * Returns statuses that do not float, reached from a floating draft without a date.
+ *
+ * @return array The statuses.
+ */
+ public static function data_statuses_that_stamp_the_current_time(): array {
+ return array(
+ 'publish' => array( 'publish' ),
+ 'future' => array( 'future' ),
+ );
+ }
+
+ /**
+ * Publishing a floating draft without a date stamps the current time, also when it is
+ * sent as scheduled, and with a past local date.
+ *
+ * @ticket 66706
+ * @dataProvider data_statuses_that_stamp_the_current_time
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ */
+ public function test_publishing_a_floating_draft_without_a_date_stamps_the_current_time( string $status ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = $this->create_floating_draft( '2020-01-01 10:00:00' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'status' => $status ) ), $post_id );
+
+ $this->assertSame( 'publish', $post->post_status, 'The post should be published.' );
+ $this->assert_is_now( $post->post_date_gmt, 'The GMT date' );
+ }
+
+ /**
+ * Moving a floating draft to pending without a date keeps it floating.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_pending_without_a_date_keeps_a_draft_floating(): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'status' => 'pending' ) ), $post_id );
+
+ $this->assertSame( 'pending', $post->post_status, 'The post should be pending.' );
+ $this->assertSame( '0000-00-00 00:00:00', $post->post_date_gmt, 'The pending post should keep floating.' );
+ }
+
+ /**
+ * Returns dates that differ from the stored ones, in America/New_York.
+ *
+ * @return array}> The dates, each 2017-01-01 10:00 local.
+ */
+ public static function data_new_dates(): array {
+ return array(
+ 'site' => array( array( 'site' => '2017-01-01T10:00:00' ) ),
+ 'gmt' => array( array( 'gmt' => '2017-01-01T15:00:00' ) ),
+ 'site with an offset' => array( array( 'site' => '2017-01-01T16:00:00+01:00' ) ),
+ 'both, the site wins' => array(
+ array(
+ 'site' => '2017-01-01T10:00:00',
+ 'gmt' => '2001-01-01T00:00:00',
+ ),
+ ),
+ );
+ }
+
+ /**
+ * A date that differs from the stored one is stored as sent, local and GMT.
+ *
+ * @ticket 66706
+ * @dataProvider data_new_dates
+ * @since 7.3.0
+ *
+ * @param array $date The sent date.
+ */
+ public function test_new_date_is_stored_local_and_gmt( array $date ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_status' => 'publish',
+ 'post_date' => '2016-12-12 14:00:00',
+ 'post_date_gmt' => '2016-12-12 19:00:00',
+ )
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'date' => $date ) ), $post_id );
+
+ $this->assertSame( '2017-01-01 10:00:00', $post->post_date, 'The local date should be stored.' );
+ $this->assertSame( '2017-01-01 15:00:00', $post->post_date_gmt, 'The GMT date should be stored.' );
+ }
+
+ /**
+ * Returns dates for a floating draft that differ from the date it shows.
+ *
+ * @return array}> The dates, each 2017-01-01 10:00 local.
+ */
+ public static function data_new_dates_for_a_floating_draft(): array {
+ return array(
+ 'site' => array( array( 'site' => '2017-01-01T10:00:00' ) ),
+ 'gmt' => array( array( 'gmt' => '2017-01-01T15:00:00' ) ),
+ );
+ }
+
+ /**
+ * A new date pins a floating draft.
+ *
+ * @ticket 66706
+ * @dataProvider data_new_dates_for_a_floating_draft
+ * @since 7.3.0
+ *
+ * @param array $date The sent date.
+ */
+ public function test_new_date_pins_a_floating_draft( array $date ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'date' => $date ) ), $post_id );
+
+ $this->assertSame( 'draft', $post->post_status, 'The post should stay a draft.' );
+ $this->assertSame( '2017-01-01 10:00:00', $post->post_date, 'The local date should be stored.' );
+ $this->assertSame( '2017-01-01 15:00:00', $post->post_date_gmt, 'The draft should no longer float.' );
+ }
+
+ /**
+ * Returns dates equal to the date a floating draft shows, 2099-01-15 10:00 in America/New_York.
+ *
+ * The date is in winter because PHP versions before 8.1 apply no daylight saving time
+ * after 2037.
+ *
+ * @return array}> The dates.
+ */
+ public static function data_dates_equal_to_the_floating_date(): array {
+ return array(
+ 'site' => array( array( 'site' => '2099-01-15T10:00:00' ) ),
+ 'gmt' => array( array( 'gmt' => '2099-01-15T15:00:00' ) ),
+ );
+ }
+
+ /**
+ * Sending back the date a floating draft shows counts as not sent and never pins it.
+ *
+ * @ticket 66706
+ * @dataProvider data_dates_equal_to_the_floating_date
+ * @since 7.3.0
+ *
+ * @param array $date The sent date.
+ */
+ public function test_date_equal_to_the_floating_date_does_not_pin_the_draft( array $date ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated(
+ $this->update_post(
+ $post_id,
+ array(
+ 'date' => $date,
+ 'title' => 'Same date',
+ )
+ ),
+ $post_id
+ );
+
+ $this->assertSame( 'draft', $post->post_status, 'The post should stay a draft.' );
+ $this->assertSame( '0000-00-00 00:00:00', $post->post_date_gmt, 'The draft should keep floating.' );
+ }
+
+ /**
+ * Returns past dates equal to the date a floating draft shows, 2020-01-01 10:00 in
+ * America/New_York.
+ *
+ * @return array}> The dates.
+ */
+ public static function data_past_dates_equal_to_the_floating_date(): array {
+ return array(
+ 'site' => array( array( 'site' => '2020-01-01T10:00:00' ) ),
+ 'gmt' => array( array( 'gmt' => '2020-01-01T15:00:00' ) ),
+ );
+ }
+
+ /**
+ * Publishing a floating draft with the past date it shows publishes it at the current
+ * time, as if no date was sent.
+ *
+ * @ticket 66706
+ * @dataProvider data_past_dates_equal_to_the_floating_date
+ * @since 7.3.0
+ *
+ * @param array $date The sent date.
+ */
+ public function test_publishing_with_the_past_floating_date_stamps_the_current_time( array $date ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = $this->create_floating_draft( '2020-01-01 10:00:00' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated(
+ $this->update_post(
+ $post_id,
+ array(
+ 'date' => $date,
+ 'status' => 'publish',
+ )
+ ),
+ $post_id
+ );
+
+ $this->assertSame( 'publish', $post->post_status, 'The post should be published.' );
+ $this->assert_is_now( $post->post_date_gmt, 'The GMT date of the published post' );
+ }
+
+ /**
+ * A date equal to the stored date of a post that does not float changes nothing.
+ *
+ * @ticket 66706
+ * @dataProvider data_dates_equal_to_the_floating_date
+ * @since 7.3.0
+ *
+ * @param array $date The sent date.
+ */
+ public function test_date_equal_to_the_stored_date_changes_nothing( array $date ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_status' => 'future',
+ 'post_date' => '2099-01-15 10:00:00',
+ 'post_date_gmt' => '2099-01-15 15:00:00',
+ )
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'date' => $date ) ), $post_id );
+
+ $this->assertSame( 'future', $post->post_status, 'The post should stay scheduled.' );
+ $this->assertSame( '2099-01-15 10:00:00', $post->post_date, 'The local date should not change.' );
+ $this->assertSame( '2099-01-15 15:00:00', $post->post_date_gmt, 'The GMT date should not change.' );
+ }
+
+ /**
+ * Returns statuses that do not float, for scheduling a floating draft for the date it shows.
+ *
+ * @return array}> The cases.
+ */
+ public static function data_schedules_a_floating_draft_for_the_date_it_shows(): array {
+ return array(
+ 'future, site' => array( 'future', array( 'site' => '2099-01-15T10:00:00' ) ),
+ 'future, gmt' => array( 'future', array( 'gmt' => '2099-01-15T15:00:00' ) ),
+ 'publish, site' => array( 'publish', array( 'site' => '2099-01-15T10:00:00' ) ),
+ 'publish, gmt' => array( 'publish', array( 'gmt' => '2099-01-15T15:00:00' ) ),
+ );
+ }
+
+ /**
+ * Scheduling a floating draft for the future date it shows schedules it for that date.
+ *
+ * @ticket 66706
+ * @dataProvider data_schedules_a_floating_draft_for_the_date_it_shows
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ * @param array $date The sent date.
+ */
+ public function test_scheduling_a_floating_draft_for_the_date_it_shows( string $status, array $date ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'date' => $date,
+ 'status' => $status,
+ ),
+ array( 'status' )
+ );
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'future', $post->post_status, 'The post should be scheduled.' );
+ $this->assertSame( '2099-01-15 10:00:00', $post->post_date, 'The local date should be the sent date.' );
+ $this->assertSame( '2099-01-15 15:00:00', $post->post_date_gmt, 'The GMT date should be the sent date.' );
+ $this->assertSame( 'future', $result['status'], 'The scheduled status should be returned.' );
+ }
+
+ /**
+ * A date that is not a date-time fails input validation.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_date_that_is_not_a_date_time_fails_input_validation(): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'date' => array( 'gmt' => '2010-60-01T02:00:00Z' ) ) );
+
+ $this->assertWPError( $result, 'The call should fail.' );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the date.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * The markup of an author is filtered on update.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_markup_of_an_author_is_filtered(): void {
+ $post_id = self::$post_ids['author:draft'];
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $markup = 'link';
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => $markup,
+ 'content' => $markup,
+ ),
+ array( 'title.raw', 'content.raw' )
+ );
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'link', $post->post_title, 'The stored title should be filtered.' );
+ $this->assertSame( 'link', $post->post_content, 'The stored content should be filtered.' );
+ $this->assertSame( 'link', $result['title']['raw'], 'The returned title should be filtered.' );
+ }
+
+ /**
+ * The markup of an administrator with `unfiltered_html` is stored unchanged on update.
+ *
+ * @group ms-excluded
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_markup_of_an_administrator_is_not_filtered(): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $markup = 'div
';
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'content' => $markup ) ), $post_id );
+
+ $this->assertSame( $markup, $post->post_content, 'The stored content should not be filtered.' );
+ }
+
+ /**
+ * On multisite, the markup of a site administrator is filtered on update.
+ *
+ * @group ms-required
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_markup_of_a_site_administrator_is_filtered_on_multisite(): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'content' => 'div
' ) ), $post_id );
+
+ $this->assertSame( 'div
', $post->post_content, 'The stored content should be filtered.' );
+ }
+
+ /**
+ * Quotes, backslashes and non-ASCII text survive a round trip unchanged.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_quotes_backslashes_and_non_ascii_text_survive_a_round_trip(): void {
+ $text = 'He said "it\'s done" \\ C:\\path\\to\\file \\\\server – café, naïve, 日本語, emoji ✓';
+ $post_id = self::$post_ids['editor:draft'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => $text,
+ 'content' => $text,
+ 'excerpt' => $text,
+ ),
+ array( 'title.raw', 'content.raw', 'excerpt.raw' )
+ );
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( $text, $post->post_title, 'The stored title should be unchanged.' );
+ $this->assertSame( $text, $post->post_content, 'The stored content should be unchanged.' );
+ $this->assertSame( $text, $post->post_excerpt, 'The stored excerpt should be unchanged.' );
+ $this->assertSame( $text, $result['title']['raw'], 'The returned title should be unchanged.' );
+ $this->assertSame( $text, $result['content']['raw'], 'The returned content should be unchanged.' );
+ $this->assertSame( $text, $result['excerpt']['raw'], 'The returned excerpt should be unchanged.' );
+ }
+
+ /**
+ * Raw fields are left out when the writer can no longer edit the post after the write.
+ *
+ * The user may publish posts but not edit published posts.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_raw_fields_are_left_out_when_the_writer_can_no_longer_edit_the_post(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['publisher'],
+ 'post_status' => 'draft',
+ 'post_title' => 'Publish once',
+ 'post_content' => 'Body.',
+ )
+ );
+
+ $this->login_as( 'publisher' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'status' => 'publish' ), array( 'title', 'content.raw', 'content.rendered' ) );
+
+ $this->assertSame( 'publish', $this->assert_updated( $result, $post_id )->post_status, 'The post should be published.' );
+ $this->assertFalse( current_user_can( 'edit_post', $post_id ), 'Precondition: the user should not be able to edit the published post.' );
+ $this->assertSame( array( 'rendered' => 'Publish once' ), $result['title'], 'The title should be returned without its raw value.' );
+ $this->assertSame( array( 'rendered' => "Body.
\n" ), $result['content'], 'The content should be returned without its raw value.' );
+ }
+
+ /**
+ * A password-protected post is returned with its protection flag.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_password_protected_post_is_returned_with_its_protection_flag(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_status' => 'publish',
+ 'post_password' => 'secret',
+ )
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'content' => 'Protected body.' ), array( 'content.raw', 'content.protected' ) );
+
+ $this->assert_updated( $result, $post_id );
+
+ $this->assertSame(
+ array(
+ 'raw' => 'Protected body.',
+ 'protected' => true,
+ ),
+ $result['content'],
+ 'The content should be returned raw to the editor and flagged as protected.'
+ );
+ $this->assertSame( 'secret', get_post( $post_id )->post_password, 'The password should be kept.' );
+ }
+
+ /**
+ * The current user is checked at each call, also on the same instance.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_each_call_checks_the_current_user(): void {
+ $post_id = self::$post_ids['author:draft'];
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $this->login_as( 'author' );
+ $first = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'First' ),
+ )
+ );
+
+ $this->login_as( 'contributor' );
+ $before = $this->snapshot( $post_id );
+ $second = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Second' ),
+ )
+ );
+
+ $this->assertSame( 'First', $this->assert_updated( $first, $post_id )->post_title, 'The first call should update the post.' );
+ $this->assert_error( $second, 'content_cannot_edit', 403, 'The second call as a contributor' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'The second call should write nothing.' );
+ }
+
+ /**
+ * The author visibility is checked again at each call.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_each_call_checks_the_author_visibility_again(): void {
+ $writer = self::factory()->user->create( array( 'role' => 'author' ) );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => $writer,
+ 'post_status' => 'draft',
+ )
+ );
+
+ $this->login_as( 'editor' );
+ $this->assertFalse( current_user_can( 'list_users' ), 'Precondition: the editor should not be able to list users.' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $input = array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Visibility' ),
+ 'fields' => array( 'author' ),
+ );
+
+ $hidden = $execute( $input );
+
+ self::factory()->post->create(
+ array(
+ 'post_author' => $writer,
+ 'post_status' => 'publish',
+ )
+ );
+
+ $visible = $execute( $input );
+
+ $this->assertIsArray( $hidden, 'The first call should succeed.' );
+ $this->assertIsArray( $visible, 'The second call should succeed.' );
+ $this->assertSame(
+ array(
+ 'id' => $writer,
+ 'name' => null,
+ 'slug' => null,
+ ),
+ $hidden['author'],
+ 'An author without published posts should not be shown.'
+ );
+ $this->assertSame( get_userdata( $writer )->display_name, $visible['author']['name'], 'The author should be shown once they have a published post.' );
+ }
+
+ /**
+ * A save error keeps its own code and message, with status 400 when the post is empty.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_empty_post_is_the_save_error(): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => '',
+ 'content' => '',
+ 'excerpt' => '',
+ )
+ );
+
+ $this->assert_error( $result, 'empty_content', 400, 'An empty post' );
+ $this->assertSame( 'Content, title, and excerpt are empty.', $result->get_error_message(), 'The message should be the message of the save error.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A database error during the save keeps its own code and message, with status 500.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_database_error_is_the_save_error(): void {
+ global $wpdb;
+
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+
+ $suppress = $wpdb->suppress_errors();
+ add_filter(
+ 'query',
+ static function ( $query ) {
+ return str_starts_with( $query, 'UPDATE' ) ? '],' : $query;
+ }
+ );
+
+ $result = $this->update_post( $post_id, array( 'title' => 'Database error' ) );
+
+ $wpdb->suppress_errors( $suppress );
+
+ $this->assert_error( $result, 'db_update_error', 500, 'A database error' );
+ $this->assertSame( 'Could not update post in the database.', $result->get_error_message(), 'The message should be the message of the save error.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written after a database error.' );
+ }
+
+ /**
+ * A stored page template that no longer exists does not fail an unrelated update and is kept.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_stale_page_template_does_not_fail_an_update(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ );
+ update_post_meta( $post_id, '_wp_page_template', 'cw-missing-template.php' );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated( $this->update_post( $post_id, array( 'title' => 'Template kept' ) ), $post_id );
+
+ $this->assertSame( 'Template kept', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( 'cw-missing-template.php', get_post_meta( $post_id, '_wp_page_template', true ), 'The stored page template should be kept.' );
+ }
+
+ /**
+ * The after-insert hooks fire once for the updated post, as in any regular save.
+ *
+ * A save that stores a revision also fires the hooks for the revision, so only the fires
+ * for the updated post are counted, and a regular save of an identical post is the reference.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_after_insert_hooks_fire_once(): void {
+ $post_id = self::$post_ids['administrator:draft'];
+ $reference_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'draft',
+ )
+ );
+ $fires = array();
+ add_action(
+ 'wp_after_insert_post',
+ static function ( $id ) use ( &$fires ): void {
+ $fires[] = (int) $id;
+ }
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ wp_update_post(
+ array(
+ 'ID' => $reference_id,
+ 'post_title' => 'Hooks',
+ )
+ );
+
+ $this->assertCount( 1, array_keys( $fires, $reference_id, true ), 'Precondition: a regular save should fire wp_after_insert_post once for the post.' );
+
+ $fires = array();
+ $this->assert_updated( $this->update_post( $post_id, array( 'title' => 'Hooks' ) ), $post_id );
+
+ $this->assertCount( 1, array_keys( $fires, $post_id, true ), 'wp_after_insert_post should fire once for the updated post.' );
+ }
+
+ /**
+ * Creates a published post of the administrator and moves it to the Trash.
+ *
+ * @since 7.3.0
+ *
+ * @return int The post ID.
+ */
+ private function create_trashed_post(): int {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ )
+ );
+ wp_trash_post( $post_id );
+
+ $this->assertSame( 'trash', get_post_status( $post_id ), 'Precondition: the post should be in the Trash.' );
+
+ return $post_id;
+ }
+
+ /**
+ * Returns internal statuses that a post can be stored in.
+ *
+ * @return array The statuses.
+ */
+ public static function data_internal_stored_statuses(): array {
+ return array(
+ 'trash' => array( 'trash' ),
+ 'auto-draft' => array( 'auto-draft' ),
+ );
+ }
+
+ /**
+ * Called directly, an internal status is rejected also for a post that is already stored in
+ * it, and the post is found whatever its stored status.
+ *
+ * @ticket 66706
+ * @dataProvider data_internal_stored_statuses
+ * @since 7.3.0
+ *
+ * @param string $status The stored status, which is also sent.
+ */
+ public function test_direct_call_rejects_trash_for_a_post_in_the_trash( string $status ): void {
+ if ( 'trash' === $status ) {
+ $post_id = $this->create_trashed_post();
+ } else {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => $status,
+ )
+ );
+ }
+
+ $this->assertSame( $status, get_post_status( $post_id ), 'Precondition: the post should be stored in the status.' );
+
+ $this->login_as( 'administrator' );
+
+ $this->assertTrue( current_user_can( 'edit_post', $post_id ), 'Precondition: the user should be able to edit the post.' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'status' => $status ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'status', 'A direct call with the internal status the post already has' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Called directly, an empty date or a date that cannot be parsed is an invalid attribute.
+ *
+ * @ticket 66706
+ * @dataProvider data_dates_without_a_usable_value
+ * @since 7.3.0
+ *
+ * @param array $date The date.
+ */
+ public function test_direct_call_rejects_a_date_without_a_usable_value( array $date ): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'date' => $date ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'date', 'A direct call with a date without a usable value' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns direct-call inputs whose `data` holds no supported attribute.
+ *
+ * @return array}> The inputs, without `where`.
+ */
+ public static function data_inputs_without_usable_data(): array {
+ return array(
+ 'data missing' => array( array() ),
+ 'empty data' => array( array( 'data' => array() ) ),
+ 'data with only keys outside the list' => array(
+ array(
+ 'data' => array(
+ 'ID' => 1,
+ 'post_password' => 'secret',
+ 'post_title' => 'Not an attribute',
+ ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Called directly by a user who may edit the post, an update without a supported attribute is
+ * an invalid attribute and writes nothing.
+ *
+ * @ticket 66706
+ * @dataProvider data_inputs_without_usable_data
+ * @since 7.3.0
+ *
+ * @param array $input The input, without `where`.
+ */
+ public function test_direct_call_without_usable_data_is_an_invalid_attribute( array $input ): void {
+ $post_id = self::$post_ids['administrator:draft'];
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $input['where'] = array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ );
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute( $input );
+
+ $this->assert_error( $result, 'content_invalid_attribute', 400, 'A direct call without usable data' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * An empty excerpt and an empty title are stored on a post that keeps its content.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_stores_an_empty_excerpt_and_an_empty_title(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'draft',
+ 'post_title' => 'Title to clear',
+ 'post_content' => 'Content to keep.',
+ 'post_excerpt' => 'Excerpt to clear.',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $post = $this->assert_updated(
+ $this->update_post(
+ $post_id,
+ array(
+ 'excerpt' => '',
+ 'title' => '',
+ )
+ ),
+ $post_id
+ );
+
+ $this->assertSame( '', $post->post_excerpt, 'The empty excerpt should be stored.' );
+ $this->assertSame( '', $post->post_title, 'The empty title should be stored.' );
+ $this->assertSame( 'Content to keep.', $post->post_content, 'The content should be kept.' );
+ }
+
+ /**
+ * An author denied `publish_posts` may still move their own draft to `pending`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_author_denied_publish_posts_may_set_pending(): void {
+ $post_id = self::$post_ids['restricted_author:draft'];
+
+ $this->login_as( 'restricted_author' );
+ $this->register_abilities();
+
+ $this->assertFalse( current_user_can( 'publish_posts' ), 'Precondition: the user should not be able to publish posts.' );
+
+ $result = $this->update_post( $post_id, array( 'status' => 'pending' ) );
+
+ $this->assertSame( 'pending', $this->assert_updated( $result, $post_id )->post_status, 'The draft should be pending.' );
+ }
+
+ /**
+ * Creates a published or scheduled post owned by the author denied `publish_posts`.
+ *
+ * @since 7.3.0
+ *
+ * @param string $status The status, `publish` or `future`.
+ * @return int The post ID.
+ */
+ private function create_post_of_the_restricted_author( string $status ): int {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['restricted_author'],
+ 'post_status' => $status,
+ 'post_date' => 'future' === $status ? '2099-01-01 00:00:00' : '2020-01-01 00:00:00',
+ )
+ );
+
+ $this->assertSame( $status, get_post_status( $post_id ), "Precondition: the post should be stored as {$status}." );
+
+ return $post_id;
+ }
+
+ /**
+ * Returns date changes on a published or scheduled post, with the status the save stores.
+ *
+ * @return array The cases.
+ */
+ public static function data_date_changes_on_a_published_or_scheduled_post(): array {
+ $ahead = '2036-06-01T12:00:00';
+ $past = '2021-06-01T12:00:00';
+
+ return array(
+ 'published post, date ahead' => array( 'publish', false, $ahead, 'future' ),
+ 'published post, date ahead, stored status' => array( 'publish', true, $ahead, 'future' ),
+ 'published post, date in the past' => array( 'publish', false, $past, 'publish' ),
+ 'scheduled post, date in the past' => array( 'future', false, $past, 'publish' ),
+ 'scheduled post, past date, stored status' => array( 'future', true, $past, 'publish' ),
+ 'scheduled post, another date ahead' => array( 'future', false, $ahead, 'future' ),
+ );
+ }
+
+ /**
+ * A date written to a published or scheduled post needs no `publish_posts`.
+ *
+ * The call sets no status. The save stores `future` for a date ahead and `publish`
+ * for any other date, so the date alone can schedule or publish the post.
+ *
+ * @ticket 66706
+ * @dataProvider data_date_changes_on_a_published_or_scheduled_post
+ * @since 7.3.0
+ *
+ * @param string $stored_status The status the post has.
+ * @param bool $send_status Whether the call also sends the stored status.
+ * @param string $date The sent GMT date.
+ * @param string $expected_status The status the save stores.
+ */
+ public function test_date_on_a_published_or_scheduled_post_needs_no_publish_posts( string $stored_status, bool $send_status, string $date, string $expected_status ): void {
+ $post_id = $this->create_post_of_the_restricted_author( $stored_status );
+
+ $this->login_as( 'restricted_author' );
+ $this->register_abilities();
+
+ $this->assertFalse( current_user_can( 'publish_posts' ), 'Precondition: the user should not be able to publish posts.' );
+
+ $data = array( 'date' => array( 'gmt' => $date ) );
+ if ( $send_status ) {
+ $data['status'] = $stored_status;
+ }
+
+ $result = $this->update_post( $post_id, $data, array( 'status' ) );
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( str_replace( 'T', ' ', $date ), $post->post_date_gmt, 'The sent date should be stored.' );
+ $this->assertSame( $expected_status, $post->post_status, 'The stored status should follow the date.' );
+ $this->assertSame( $expected_status, $result['status'], 'The status that follows the date should be returned.' );
+ }
+
+ /**
+ * Returns changes between `publish` and `future` that name the new status.
+ *
+ * @return array The cases.
+ */
+ public static function data_named_status_changes_on_a_published_or_scheduled_post(): array {
+ return array(
+ 'published post to future, date ahead' => array( 'publish', 'future', '2036-06-01T12:00:00' ),
+ 'scheduled post to publish, date in the past' => array( 'future', 'publish', '2021-06-01T12:00:00' ),
+ );
+ }
+
+ /**
+ * A call that names the other status, `future` or `publish`, needs `publish_posts`,
+ * also when the sent date alone would lead to that status.
+ *
+ * @ticket 66706
+ * @dataProvider data_named_status_changes_on_a_published_or_scheduled_post
+ * @since 7.3.0
+ *
+ * @param string $stored_status The status the post has.
+ * @param string $status The sent status.
+ * @param string $date The sent GMT date.
+ */
+ public function test_naming_the_status_a_date_leads_to_needs_publish_posts( string $stored_status, string $status, string $date ): void {
+ $post_id = $this->create_post_of_the_restricted_author( $stored_status );
+
+ $this->login_as( 'restricted_author' );
+ $this->register_abilities();
+
+ $this->assertFalse( current_user_can( 'publish_posts' ), 'Precondition: the user should not be able to publish posts.' );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => $status,
+ 'date' => array( 'gmt' => $date ),
+ )
+ );
+
+ $this->assert_error( $result, 'content_cannot_publish', 403, 'A published or scheduled post moved to the other status without publish_posts' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Grants `edit_post` and `read_post` on one post to one user through `map_meta_cap`.
+ *
+ * @since 7.3.0
+ *
+ * @param int $user_id The user ID.
+ * @param int $post_id The post ID.
+ * @param bool $only_while_draft Whether the grant holds only while the post is a draft.
+ */
+ private function grant_edit_and_read_on_one_post( int $user_id, int $post_id, bool $only_while_draft ): void {
+ add_filter(
+ 'map_meta_cap',
+ static function ( $caps, $cap, $cap_user_id, $args ) use ( $user_id, $post_id, $only_while_draft ) {
+ if (
+ in_array( $cap, array( 'edit_post', 'read_post' ), true )
+ && $user_id === (int) $cap_user_id
+ && isset( $args[0] ) && $post_id === (int) $args[0]
+ && ( ! $only_while_draft || 'draft' === get_post_status( $post_id ) )
+ ) {
+ return array( 'read' );
+ }
+
+ return $caps;
+ },
+ 10,
+ 4
+ );
+ }
+
+ /**
+ * A user with no edit capability for the type who is granted `edit_post` on exactly one post
+ * may update that post's title, and nothing more.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_edit_post_granted_on_one_post_allows_only_editing_that_post(): void {
+ $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['other'],
+ 'post_status' => 'draft',
+ )
+ );
+ $other_id = self::$post_ids['other:draft'];
+
+ $this->grant_edit_and_read_on_one_post( $user_id, $post_id, false );
+ wp_set_current_user( $user_id );
+
+ $this->assertFalse( current_user_can( 'edit_posts' ), 'Precondition: the user should have no edit capability for the type.' );
+ $this->assertTrue( current_user_can( 'edit_post', $post_id ), 'Precondition: the user should be able to edit the granted post.' );
+ $this->assertFalse( current_user_can( 'edit_post', $other_id ), 'Precondition: the user should not be able to edit another post.' );
+
+ $this->register_abilities();
+
+ $updated = $this->update_post( $post_id, array( 'title' => 'Granted title' ) );
+
+ $this->assertSame( 'Granted title', $this->assert_updated( $updated, $post_id )->post_title, 'The title of the granted post should be stored.' );
+
+ $other_before = $this->snapshot( $other_id );
+ $other = $this->update_post( $other_id, array( 'title' => 'Not granted' ) );
+
+ $this->assert_refused( $other, 'Updating a post that is not granted' );
+ $this->assertSame( $other_before, $this->snapshot( $other_id ), 'Nothing should be written for the post that is not granted.' );
+
+ $before = $this->snapshot( $post_id );
+ $publish = $this->update_post( $post_id, array( 'status' => 'publish' ) );
+
+ $this->assert_error( $publish, 'content_cannot_publish', 403, 'Publishing the granted post' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written for the refused publish.' );
+
+ $this->assertTrue( wp_has_ability( 'core/content-delete' ), 'The core/content-delete ability should be registered.' );
+
+ $delete = wp_get_ability( 'core/content-delete' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ )
+ );
+
+ $this->assert_refused( $delete, 'Deleting the granted post' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written for the refused delete.' );
+ }
+
+ /**
+ * Sets the front page, the posts page and the privacy policy page of the site, and returns
+ * their IDs.
+ *
+ * @since 7.3.0
+ *
+ * @return array The page IDs, keyed by fixture name.
+ */
+ private function set_special_pages(): array {
+ $pages = array();
+ foreach ( array( 'front_page', 'posts_page', 'privacy_page' ) as $page ) {
+ $pages[ $page ] = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ );
+ }
+
+ update_option( 'show_on_front', 'page' );
+ update_option( 'page_on_front', $pages['front_page'] );
+ update_option( 'page_for_posts', $pages['posts_page'] );
+ update_option( 'wp_page_for_privacy_policy', $pages['privacy_page'] );
+
+ return $pages;
+ }
+
+ /**
+ * An editor may not update the privacy policy page.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_editor_cannot_update_the_privacy_policy_page(): void {
+ $post_id = $this->set_special_pages()['privacy_page'];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'title' => 'Privacy' ) );
+
+ $this->assert_refused( $result, 'An editor updating the privacy policy page' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns the special pages that an editor may update.
+ *
+ * @return array The pages, as fixture names.
+ */
+ public static function data_special_pages_an_editor_may_update(): array {
+ return array(
+ 'front page' => array( 'front_page' ),
+ 'posts page' => array( 'posts_page' ),
+ );
+ }
+
+ /**
+ * An editor may update the title of the front page and of the posts page.
+ *
+ * @ticket 66706
+ * @dataProvider data_special_pages_an_editor_may_update
+ * @since 7.3.0
+ *
+ * @param string $page The page, as a fixture name.
+ */
+ public function test_editor_may_update_the_title_of_a_special_page( string $page ): void {
+ $post_id = $this->set_special_pages()[ $page ];
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'title' => 'Special page' ) );
+
+ $this->assertSame( 'Special page', $this->assert_updated( $result, $post_id )->post_title, 'The title of the special page should be stored.' );
+ }
+
+ /**
+ * Returns updates of a page whose stored parent no longer exists.
+ *
+ * @return array The cases.
+ */
+ public static function data_updates_of_a_page_with_a_missing_parent(): array {
+ return array(
+ 'parent equal to the stored parent' => array( true ),
+ 'title only' => array( false ),
+ );
+ }
+
+ /**
+ * A page whose stored parent no longer exists can be updated, and keeps that parent.
+ *
+ * @ticket 66706
+ * @dataProvider data_updates_of_a_page_with_a_missing_parent
+ * @since 7.3.0
+ *
+ * @param bool $send_parent Whether the stored parent is sent.
+ */
+ public function test_page_with_a_missing_parent_can_be_updated( bool $send_parent ): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['page_writer'],
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ 'post_parent' => self::MISSING_ID,
+ )
+ );
+
+ $this->assertSame( self::MISSING_ID, get_post( $post_id )->post_parent, 'Precondition: the page should keep the missing parent.' );
+ $this->assertNull( get_post( self::MISSING_ID ), 'Precondition: the parent should not exist.' );
+
+ $this->login_as( 'page_writer' );
+ $this->register_abilities();
+
+ $data = array( 'title' => 'Orphan' );
+ if ( $send_parent ) {
+ $data['parent'] = self::MISSING_ID;
+ }
+
+ $post = $this->assert_updated( $this->update_post( $post_id, $data ), $post_id );
+
+ $this->assertSame( 'Orphan', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( self::MISSING_ID, $post->post_parent, 'The stored parent should not change.' );
+ }
+
+ /**
+ * Registers a custom public, private and hidden status, before the abilities are registered.
+ *
+ * @since 7.3.0
+ */
+ private function register_custom_statuses(): void {
+ register_post_status(
+ 'cw_public',
+ array(
+ 'label' => 'Public',
+ 'public' => true,
+ )
+ );
+ register_post_status(
+ 'cw_private',
+ array(
+ 'label' => 'Private',
+ 'private' => true,
+ )
+ );
+ register_post_status(
+ 'cw_hidden',
+ array(
+ 'label' => 'Hidden',
+ 'public' => false,
+ 'protected' => true,
+ )
+ );
+
+ $this->assertFalse( get_post_status_object( 'cw_hidden' )->internal, 'Precondition: the hidden status should not be internal.' );
+ $this->assertFalse( is_post_status_viewable( 'cw_hidden' ), 'Precondition: the hidden status should not be publicly viewable.' );
+ }
+
+ /**
+ * A contributor may set a hidden custom status on their own draft without `publish_posts`.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_contributor_may_set_a_hidden_custom_status(): void {
+ $this->register_custom_statuses();
+ $post_id = self::$post_ids['contributor:draft'];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'status' => 'cw_hidden' ) );
+
+ $this->assertSame( 'cw_hidden', $this->assert_updated( $result, $post_id )->post_status, 'The hidden status should be stored.' );
+ }
+
+ /**
+ * Returns custom statuses that make a post visible, with the stored status of the post.
+ *
+ * @return array The cases.
+ */
+ public static function data_custom_visible_statuses_by_stored_status(): array {
+ return array(
+ 'public from a draft' => array( 'cw_public', 'draft' ),
+ 'private from a draft' => array( 'cw_private', 'draft' ),
+ 'public from pending' => array( 'cw_public', 'pending' ),
+ 'private from pending' => array( 'cw_private', 'pending' ),
+ 'public from the Trash' => array( 'cw_public', 'trash_draft' ),
+ 'private from the Trash' => array( 'cw_private', 'trash_draft' ),
+ );
+ }
+
+ /**
+ * A contributor may not set a custom public or private status on their own post, and the
+ * refusal uses the general message.
+ *
+ * @ticket 66706
+ * @dataProvider data_custom_visible_statuses_by_stored_status
+ * @since 7.3.0
+ *
+ * @param string $status The status.
+ * @param string $stored The matrix status of the post.
+ */
+ public function test_contributor_cannot_set_a_custom_visible_status( string $status, string $stored ): void {
+ $this->register_custom_statuses();
+ $post_id = self::$post_ids[ "contributor:{$stored}" ];
+
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'status' => $status ) );
+
+ $this->assert_error( $result, 'content_cannot_publish', 403, 'A contributor setting a custom visible status' );
+ $this->assertSame( 'Sorry, you are not allowed to publish posts in this post type.', $result->get_error_message(), 'A custom status, also a private one, should get the general message.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * When the update takes away the caller's read access, the update is stored and the output
+ * is the ID alone, whatever the fields ask for.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_output_is_the_id_alone_when_the_update_takes_away_read_access(): void {
+ $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['other'],
+ 'post_status' => 'draft',
+ )
+ );
+
+ $this->grant_edit_and_read_on_one_post( $user_id, $post_id, true );
+ wp_set_current_user( $user_id );
+
+ $this->assertTrue( current_user_can( 'edit_post', $post_id ), 'Precondition: the user should be able to edit the draft.' );
+
+ $this->register_abilities();
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => 'pending',
+ 'title' => 'Out of reach',
+ ),
+ array( 'title.rendered', 'status', 'content.rendered' )
+ );
+
+ $post = $this->assert_updated( $result, $post_id );
+
+ $this->assertSame( 'pending', $post->post_status, 'The new status should be stored.' );
+ $this->assertSame( 'Out of reach', $post->post_title, 'The new title should be stored.' );
+ $this->assertFalse( current_user_can( 'read_post', $post_id ), 'Precondition: the user should no longer be able to read the post.' );
+ $this->assertSame( array( 'id' => $post_id ), $result, 'The output should be the ID alone.' );
+ }
+
+ /**
+ * When the caller may still read the post after the update, the output holds the requested
+ * fields.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_output_is_complete_when_the_caller_may_still_read_the_post(): void {
+ $user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['other'],
+ 'post_status' => 'draft',
+ )
+ );
+
+ $this->grant_edit_and_read_on_one_post( $user_id, $post_id, true );
+ wp_set_current_user( $user_id );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'title' => 'Still a draft' ), array( 'title.rendered', 'status' ) );
+
+ $this->assert_updated( $result, $post_id );
+ $this->assertTrue( current_user_can( 'read_post', $post_id ), 'Precondition: the user should still be able to read the post.' );
+
+ ksort( $result );
+
+ $this->assertSame(
+ array(
+ 'id' => $post_id,
+ 'status' => 'draft',
+ 'title' => array( 'rendered' => 'Still a draft' ),
+ ),
+ $result,
+ 'The output should hold the ID and the requested fields.'
+ );
+ }
+}
diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php
index 0374d38eb37f4..857f506062871 100644
--- a/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php
+++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php
@@ -3,7 +3,7 @@
declare( strict_types=1 );
/**
- * Tests dispatching the core/content-query ability through the Abilities REST run endpoint.
+ * Tests dispatching the content abilities through the Abilities REST run endpoint.
*
* @covers WP_Abilities_Content
*
@@ -408,4 +408,537 @@ public function test_input_without_where_returns_400(): void {
$this->assertSame( 400, $response->get_status(), 'Input without where should be rejected.' );
$this->assertSame( 'ability_invalid_input', $response->get_data()['code'], 'The error should come from input validation.' );
}
+
+ /**
+ * Builds a run request for a content write ability.
+ *
+ * A POST request carries the input in a JSON body, any other request in the query string.
+ *
+ * @since 7.3.0
+ *
+ * @param string $method The HTTP method.
+ * @param string $ability The ability name.
+ * @param array $input The ability input.
+ * @return WP_REST_Request The request.
+ */
+ private function write_request( string $method, string $ability, array $input ): WP_REST_Request {
+ $request = new WP_REST_Request( $method, "/wp-abilities/v1/abilities/{$ability}/run" );
+
+ if ( 'POST' === $method ) {
+ $request->set_header( 'Content-Type', 'application/json' );
+ $request->set_body( wp_json_encode( array( 'input' => $input ) ) );
+ } else {
+ $request->set_query_params( array( 'input' => $input ) );
+ }
+
+ return $request;
+ }
+
+ /**
+ * Asserts that a response is an error with the given status and code.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_REST_Response $response The response.
+ * @param int $status The expected status.
+ * @param string $code The expected error code.
+ * @param string $context What the request was, for the assertion messages.
+ */
+ private function assert_error_response( WP_REST_Response $response, int $status, string $code, string $context ): void {
+ $this->assertSame( $status, $response->get_status(), "{$context}: the status should be {$status}." );
+ $this->assertSame( $code, $response->get_data()['code'] ?? null, "{$context}: the error code should be {$code}." );
+ }
+
+ /**
+ * Takes a snapshot of the stored content: the number of posts per type and status, the
+ * number of meta rows and, when given, the row and meta of one post.
+ *
+ * @since 7.3.0
+ *
+ * @param int $post_id Optional. The post ID. Default 0.
+ * @return array The snapshot.
+ */
+ private function snapshot( int $post_id = 0 ): array {
+ global $wpdb;
+
+ return array(
+ 'posts' => $wpdb->get_results( "SELECT post_type, post_status, COUNT(*) AS total FROM {$wpdb->posts} GROUP BY post_type, post_status ORDER BY post_type, post_status", ARRAY_A ),
+ 'meta' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->postmeta}" ),
+ 'post' => $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id ), ARRAY_A ),
+ 'post_meta' => $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d ORDER BY meta_id", $post_id ), ARRAY_A ),
+ );
+ }
+
+ /**
+ * Create runs with POST and the input in a JSON body.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_create_runs_with_post_and_a_json_body(): void {
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'POST',
+ 'core/content-create',
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Over the run route',
+ ),
+ 'fields' => array( 'status', 'title.rendered' ),
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The create request should succeed.' );
+
+ $data = $response->get_data();
+
+ $this->assertSameSets( array( 'id', 'status', 'title' ), array_keys( $data ), 'The created post should be returned in the chosen fields.' );
+ $this->assertSame( 'draft', $data['status'], 'The created post should be a draft.' );
+ $this->assertSame( 'Over the run route', get_post( $data['id'] )->post_title, 'The created post should be stored.' );
+ }
+
+ /**
+ * Update runs with POST and the input in a JSON body.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_update_runs_with_post_and_a_json_body(): void {
+ $post_id = self::factory()->post->create( array( 'post_status' => 'draft' ) );
+
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'POST',
+ 'core/content-update',
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Updated over the run route' ),
+ 'fields' => array( 'title.rendered' ),
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The update request should succeed.' );
+ $this->assertSame(
+ array(
+ 'id' => $post_id,
+ 'title' => array( 'rendered' => 'Updated over the run route' ),
+ ),
+ $response->get_data(),
+ 'The updated post should be returned in the chosen fields.'
+ );
+ }
+
+ /**
+ * Delete runs with DELETE and the input in the query string, where the ID is a string.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_delete_runs_with_delete_and_the_input_in_the_query_string(): void {
+ $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) );
+
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'DELETE',
+ 'core/content-delete',
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => (string) $post_id,
+ ),
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The delete request should succeed.' );
+ $this->assertSame( array( 'outcome' => 'trashed' ), $response->get_data(), 'The post should be reported as trashed.' );
+ $this->assertSame( 'trash', get_post_status( $post_id ), 'The post should be in the Trash.' );
+ }
+
+ /**
+ * Returns `permanent` values as they arrive in a query string, and the outcome.
+ *
+ * @return array The cases.
+ */
+ public static function data_permanent_query_string_values(): array {
+ return array(
+ 'true' => array( 'true', 'deleted' ),
+ '1' => array( '1', 'deleted' ),
+ 'false' => array( 'false', 'trashed' ),
+ '0' => array( '0', 'trashed' ),
+ 'upper case' => array( 'TRUE', 'deleted' ),
+ );
+ }
+
+ /**
+ * `permanent` in the query string is read as a boolean.
+ *
+ * @ticket 66706
+ * @dataProvider data_permanent_query_string_values
+ * @since 7.3.0
+ *
+ * @param string $permanent The value in the query string.
+ * @param string $outcome The expected outcome.
+ */
+ public function test_delete_reads_permanent_from_the_query_string( string $permanent, string $outcome ): void {
+ $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) );
+
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'DELETE',
+ 'core/content-delete',
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => (string) $post_id,
+ ),
+ 'permanent' => $permanent,
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The delete request should succeed.' );
+ $this->assertSame( array( 'outcome' => $outcome ), $response->get_data(), 'The outcome should follow the permanent value.' );
+
+ clean_post_cache( $post_id );
+
+ if ( 'deleted' === $outcome ) {
+ $this->assertNull( get_post( $post_id ), 'The post should no longer exist.' );
+ } else {
+ $this->assertSame( 'trash', get_post_status( $post_id ), 'The post should be in the Trash.' );
+ }
+ }
+
+ /**
+ * Returns `permanent` values in a query string that are not booleans.
+ *
+ * @return array The values.
+ */
+ public static function data_permanent_query_string_values_that_are_not_booleans(): array {
+ return array(
+ 'yes' => array( 'yes' ),
+ '2' => array( '2' ),
+ 'on' => array( 'on' ),
+ 'empty string' => array( '' ),
+ );
+ }
+
+ /**
+ * A `permanent` value in the query string that is not a boolean fails input validation, and
+ * the post is unchanged.
+ *
+ * @ticket 66706
+ * @dataProvider data_permanent_query_string_values_that_are_not_booleans
+ * @since 7.3.0
+ *
+ * @param string $permanent The value in the query string.
+ */
+ public function test_delete_with_a_permanent_value_that_is_not_a_boolean_returns_400( string $permanent ): void {
+ $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) );
+
+ $before = $this->snapshot( $post_id );
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'DELETE',
+ 'core/content-delete',
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => (string) $post_id,
+ ),
+ 'permanent' => $permanent,
+ )
+ )
+ );
+
+ $this->assert_error_response( $response, 400, 'ability_invalid_input', 'A permanent value that is not a boolean' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'The post should not change.' );
+ }
+
+ /**
+ * A create sent with POST but with the input in the query string fails input validation.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_create_with_the_input_in_the_query_string_returns_400(): void {
+ $request = new WP_REST_Request( 'POST', '/wp-abilities/v1/abilities/core/content-create/run' );
+ $request->set_query_params(
+ array(
+ 'input' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Misplaced input',
+ ),
+ ),
+ )
+ );
+
+ $before = $this->snapshot();
+ $response = $this->server->dispatch( $request );
+
+ $this->assert_error_response( $response, 400, 'ability_invalid_input', 'A create with the input in the query string' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ }
+
+ /**
+ * A delete sent with DELETE but with the input in a JSON body fails input validation.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_delete_with_the_input_in_a_json_body_returns_400(): void {
+ $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) );
+
+ $request = new WP_REST_Request( 'DELETE', '/wp-abilities/v1/abilities/core/content-delete/run' );
+ $request->set_header( 'Content-Type', 'application/json' );
+ $request->set_body(
+ wp_json_encode(
+ array(
+ 'input' => array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ ),
+ )
+ )
+ );
+
+ $before = $this->snapshot( $post_id );
+ $response = $this->server->dispatch( $request );
+
+ $this->assert_error_response( $response, 400, 'ability_invalid_input', 'A delete with the input in a JSON body' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'The post should not change.' );
+ }
+
+ /**
+ * Returns write abilities with a method they do not take.
+ *
+ * @return array The cases.
+ */
+ public static function data_wrong_methods_for_write_abilities(): array {
+ return array(
+ 'GET to create' => array( 'core/content-create', 'GET' ),
+ 'DELETE to create' => array( 'core/content-create', 'DELETE' ),
+ 'GET to update' => array( 'core/content-update', 'GET' ),
+ 'DELETE to update' => array( 'core/content-update', 'DELETE' ),
+ 'GET to delete' => array( 'core/content-delete', 'GET' ),
+ 'POST to delete' => array( 'core/content-delete', 'POST' ),
+ );
+ }
+
+ /**
+ * A write ability called with a method it does not take is rejected and writes nothing.
+ *
+ * @ticket 66706
+ * @dataProvider data_wrong_methods_for_write_abilities
+ * @since 7.3.0
+ *
+ * @param string $ability The ability name.
+ * @param string $method The HTTP method.
+ */
+ public function test_write_ability_with_a_wrong_method_returns_405( string $ability, string $method ): void {
+ $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) );
+ $inputs = array(
+ 'core/content-create' => array( 'data' => array( 'type' => 'post' ) ),
+ 'core/content-update' => array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Wrong method' ),
+ ),
+ 'core/content-delete' => array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ ),
+ );
+ $before = $this->snapshot( $post_id );
+
+ $response = $this->server->dispatch( $this->write_request( $method, $ability, $inputs[ $ability ] ) );
+
+ $this->assert_error_response( $response, 405, 'rest_ability_invalid_method', 'A wrong method' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * A logged-out user is refused as unauthenticated.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_logged_out_create_receives_401(): void {
+ wp_set_current_user( 0 );
+
+ $before = $this->snapshot();
+ $response = $this->server->dispatch( $this->write_request( 'POST', 'core/content-create', array( 'data' => array( 'type' => 'post' ) ) ) );
+
+ $this->assert_error_response( $response, 401, 'rest_ability_cannot_execute', 'A logged-out create' );
+ $this->assertSame( $before, $this->snapshot(), 'A logged-out create should write nothing.' );
+ }
+
+ /**
+ * A user the permission callback refuses is forbidden.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_subscriber_create_receives_403(): void {
+ wp_set_current_user( self::$subscriber_id );
+
+ $before = $this->snapshot();
+ $response = $this->server->dispatch( $this->write_request( 'POST', 'core/content-create', array( 'data' => array( 'type' => 'post' ) ) ) );
+
+ $this->assert_error_response( $response, 403, 'rest_ability_cannot_execute', 'A subscriber create' );
+ $this->assertSame( $before, $this->snapshot(), 'A subscriber create should write nothing.' );
+ }
+
+ /**
+ * Input that fails the schema is rejected.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_create_with_input_that_fails_the_schema_returns_400(): void {
+ $before = $this->snapshot();
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'POST',
+ 'core/content-create',
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'post_password' => 'secret',
+ ),
+ )
+ )
+ );
+
+ $this->assert_error_response( $response, 400, 'ability_invalid_input', 'A create that fails the schema' );
+ $this->assertSame( $before, $this->snapshot(), 'A create that fails the schema should write nothing.' );
+ }
+
+ /**
+ * The not-found error of an update reaches the response with its status.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_update_of_a_missing_post_returns_404(): void {
+ $before = $this->snapshot();
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'POST',
+ 'core/content-update',
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => 987654321,
+ ),
+ 'data' => array( 'title' => 'Missing' ),
+ )
+ )
+ );
+
+ $this->assert_error_response( $response, 404, 'content_not_found', 'An update of a missing post' );
+ $this->assertSame( $before, $this->snapshot(), 'An update of a missing post should write nothing.' );
+ }
+
+ /**
+ * An update of a post the user cannot edit is refused before the ability runs.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_update_of_a_post_the_user_cannot_edit_returns_403(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$admin_id,
+ 'post_status' => 'publish',
+ )
+ );
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'contributor' ) ) );
+
+ $before = $this->snapshot( $post_id );
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'POST',
+ 'core/content-update',
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'title' => 'Not mine' ),
+ )
+ )
+ );
+
+ $this->assert_error_response( $response, 403, 'rest_ability_cannot_execute', 'An update of a post the user cannot edit' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'The post the user cannot edit should not change.' );
+ }
+
+ /**
+ * The invalid attribute error of a create reaches the response with its status.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_create_with_an_unsupported_attribute_returns_400(): void {
+ $before = $this->snapshot();
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'POST',
+ 'core/content-create',
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'With a parent',
+ 'parent' => 1,
+ ),
+ )
+ )
+ );
+
+ $this->assert_error_response( $response, 400, 'content_invalid_attribute', 'A create with an unsupported attribute' );
+ $this->assertSame( array( 'data[parent]' => 'The parent attribute is only supported for hierarchical post types.' ), $response->get_data()['data']['params'] ?? null, 'The params should reach the response.' );
+ $this->assertSame( $before, $this->snapshot(), 'A create with an unsupported attribute should write nothing.' );
+ }
+
+ /**
+ * The already-trashed error of a delete reaches the response with its status.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_trashing_a_trashed_post_returns_410(): void {
+ $post_id = self::factory()->post->create( array( 'post_status' => 'publish' ) );
+ wp_trash_post( $post_id );
+
+ $before = $this->snapshot( $post_id );
+ $response = $this->server->dispatch(
+ $this->write_request(
+ 'DELETE',
+ 'core/content-delete',
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => (string) $post_id,
+ ),
+ )
+ )
+ );
+
+ $this->assert_error_response( $response, 410, 'content_already_trashed', 'Trashing a trashed post' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'The trashed post should stay as it was.' );
+ }
}