diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php
index 835c19e04f949..4996bbd82d9c2 100644
--- a/src/wp-includes/abilities.php
+++ b/src/wp-includes/abilities.php
@@ -11,6 +11,7 @@
require_once __DIR__ . '/abilities/class-wp-abilities-content.php';
require_once __DIR__ . '/abilities/class-wp-abilities-settings.php';
+require_once __DIR__ . '/abilities/class-wp-abilities-terms.php';
require_once __DIR__ . '/abilities/class-wp-abilities-users.php';
/**
@@ -50,6 +51,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`, `core/content-delete`, `core/terms-query`, `core/term-create`, `core/term-update`, and `core/term-delete` abilities.
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
@@ -377,6 +379,9 @@ 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();
+
+ // Register the term abilities: `core/terms-query`, `core/term-create`, `core/term-update`, and `core/term-delete`.
+ ( new WP_Abilities_Terms() )->register();
}
diff --git a/src/wp-includes/abilities/class-wp-abilities-content.php b/src/wp-includes/abilities/class-wp-abilities-content.php
index f5a7e881b1c95..50cee49ceb2de 100644
--- a/src/wp-includes/abilities/class-wp-abilities-content.php
+++ b/src/wp-includes/abilities/class-wp-abilities-content.php
@@ -17,12 +17,17 @@
* 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. Create and update
+ * return the written post in the same shape as a `core/content-query` item, and delete
+ * returns whether the post was trashed or deleted.
+ *
* 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
- * 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.
+ * self-contained closures, the four content abilities live in one dedicated class because
+ * their callbacks and schemas share helpers as private methods, such as the read check,
+ * the field projection, and the input parsing: 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.
*
* Only register() is public. The ability callbacks are closures that call private
* methods, so callers go through the Abilities API, such as
@@ -32,6 +37,35 @@
* @since 7.2.0
*
* @access private
+ *
+ * @phpstan-type Content_Write_Data array{
+ * type?: string,
+ * title?: string,
+ * content?: string,
+ * excerpt?: string,
+ * status?: string,
+ * slug?: string,
+ * date?: array{ site: string, gmt?: string }|array{ site?: string, gmt: string },
+ * author?: int,
+ * parent?: int,
+ * terms?: array>
+ * }
+ * @phpstan-type Content_Post_Array array{
+ * ID?: int,
+ * post_type?: string,
+ * post_title?: string,
+ * post_content?: string,
+ * post_excerpt?: string,
+ * post_status?: string,
+ * post_author?: int,
+ * post_parent?: int,
+ * post_date?: string,
+ * post_date_gmt?: string,
+ * edit_date?: bool,
+ * post_name?: string,
+ * page_template?: '',
+ * tax_input?: array>
+ * }
*/
final class WP_Abilities_Content {
@@ -67,13 +101,15 @@ final class WP_Abilities_Content {
*
* Requests that include any of these, directly or through their whole object, prime
* the post meta and term caches for the page. Rendered excerpts and content may read
- * either, and permalinks read terms when the permalink structure contains `%category%`.
- * Other fields, such as the rendered title, do not need that cache priming.
+ * either, permalinks read terms when the permalink structure contains `%category%`, and
+ * `terms` reads the terms of each post. Other fields, such as the rendered title, do not
+ * need that cache priming.
*
* @since 7.2.0
+ * @since 7.3.0 Added `terms`.
* @var list
*/
- private const CACHE_PRIMING_FIELDS = array( 'link', 'excerpt.rendered', 'content.rendered' );
+ private const CACHE_PRIMING_FIELDS = array( 'link', 'excerpt.rendered', 'content.rendered', 'terms' );
/**
* Default field paths returned when the caller does not request a field subset.
@@ -93,7 +129,7 @@ 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.
+ * Whether each author seen in the current call has posts the current user may read.
*
* @since 7.2.0
* @var array
@@ -106,38 +142,43 @@ final class WP_Abilities_Content {
* Must run on the `wp_abilities_api_init` hook.
*
* @since 7.2.0
+ * @since 7.3.0 Added 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 that are not internal.
+ $statuses = array_values( get_post_stati( array( 'internal' => false ) ) );
+
+ $this->register_content_query( $post_types, $statuses );
+ $this->register_content_write_abilities( $post_types, $statuses );
}
/**
* Registers the read-only `core/content-query` ability.
*
* @since 7.2.0
+ *
+ * @param list $post_types Exposed post type names.
+ * @param list $statuses Post status slugs that are not internal.
*/
- private function register_content_query(): void {
- /*
- * Post types must be registered with `show_in_abilities` before the ability is
- * registered so they are included in its input schema.
- */
- $post_types = array_values( get_post_types( array( 'show_in_abilities' => true ) ) );
- if ( empty( $post_types ) ) {
- return;
- }
-
+ private function register_content_query( array $post_types, array $statuses ): void {
/*
- * 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
+ * Of the internal statuses, only `trash` can be requested, and only by name: it is never
+ * one of the statuses a query covers by default. The others, such as `inherit`, can never
+ * be queried, 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[] = 'trash';
wp_register_ability(
'core/content-query',
@@ -151,7 +192,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 +206,91 @@ private function register_content_query(): void {
);
}
+ /**
+ * Registers the `core/content-create`, `core/content-update`, and `core/content-delete` abilities.
+ *
+ * @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_write_abilities( 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 ) {
+ return $this->execute_content_create( $input );
+ },
+ 'permission_callback' => function ( $input ): bool {
+ return $this->check_create_permission( $input );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => false,
+ 'destructive' => false,
+ 'idempotent' => false,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+
+ 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 ) {
+ return $this->execute_content_update( $input );
+ },
+ 'permission_callback' => function ( $input ): bool {
+ return $this->check_post_permission( $input, 'edit_post' );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => false,
+ 'destructive' => false,
+ 'idempotent' => true,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+
+ 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 ) {
+ return $this->execute_content_delete( $input );
+ },
+ 'permission_callback' => function ( $input ): 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 +304,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 +329,326 @@ private function check_permission( $input = array() ): bool {
return $this->can_query_statuses( $where, $post_type_object );
}
+ /**
+ * Permission callback for the `core/content-create` ability.
+ *
+ * Requires a logged-in user, a `data.type` that is exposed to abilities, the capability
+ * to create posts of that type, and the capabilities that the sent attributes need,
+ * see {@see self::can_set_attributes()}.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input, which is not prepared when
+ * WP_Ability::check_permissions() is called directly.
+ * @return bool True if the request may proceed, false otherwise.
+ */
+ private function check_create_permission( $input ): bool {
+ if ( ! is_user_logged_in() ) {
+ return false;
+ }
+
+ $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
+ && $this->current_user_can_for_post_type( $post_type_object, 'create_posts' )
+ && $this->can_set_attributes( $data, $post_type_object, null );
+ }
+
+ /**
+ * Checks whether the current user has a capability of a post type, such as `publish_posts`.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_Post_Type $post_type_object The post type.
+ * @param string $capability The name of the capability in the post type's `cap` object.
+ * @return bool Whether the current user has the capability.
+ */
+ private function current_user_can_for_post_type( WP_Post_Type $post_type_object, string $capability ): bool {
+ $cap = $post_type_object->cap->$capability ?? null;
+
+ return is_string( $cap ) && current_user_can( $cap );
+ }
+
+ /**
+ * Checks the capabilities that the sent `status`, `author`, `parent`, `slug`, and `terms` need.
+ *
+ * A value that keeps the stored one needs none, see {@see self::get_unchanged_attributes()},
+ * and neither does a taxonomy in `terms` that keeps its stored terms, see
+ * {@see self::get_changed_terms()}.
+ * The other rules on these attributes are checked by the execute callbacks.
+ *
+ * @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 bool True if the user may set the sent attributes, false otherwise.
+ */
+ private function can_set_attributes( array $data, WP_Post_Type $post_type_object, ?WP_Post $post ): bool {
+ foreach ( $this->get_unchanged_attributes( $data, $post ) as $attribute ) {
+ unset( $data[ $attribute ] );
+ }
+
+ if ( array_key_exists( 'status', $data ) ) {
+ $status = $data['status'];
+ if ( ! is_string( $status ) ) {
+ return false;
+ }
+
+ /*
+ * Intentionally strict: every status that makes a post visible needs the capability
+ * to publish posts of the type, including custom ones.
+ */
+ $status_object = get_post_status_object( $status );
+ $makes_visible = $status_object instanceof stdClass && (
+ 'future' === $status
+ || ! empty( $status_object->public )
+ || ! empty( $status_object->private )
+ || is_post_status_viewable( $status_object )
+ );
+ if ( $makes_visible && ! $this->current_user_can_for_post_type( $post_type_object, 'publish_posts' ) ) {
+ return false;
+ }
+ }
+
+ // An author sent for a post type that does not support authors is refused by the execute callbacks.
+ if ( array_key_exists( 'author', $data ) && post_type_supports( $post_type_object->name, 'author' ) ) {
+ $author_id = $this->parse_filter_int( $data['author'], 1 );
+ if ( null === $author_id ) {
+ return false;
+ }
+
+ if ( get_current_user_id() !== $author_id && ! $this->current_user_can_for_post_type( $post_type_object, 'edit_others_posts' ) ) {
+ return false;
+ }
+ }
+
+ // A parent sent for a post type that is not hierarchical is refused by the execute callbacks.
+ if ( array_key_exists( 'parent', $data ) && $post_type_object->hierarchical ) {
+ $parent_id = $this->parse_filter_int( $data['parent'], 0 );
+ if ( null === $parent_id ) {
+ return false;
+ }
+
+ /*
+ * A parent must be a post the current user can read. A missing post is refused the
+ * same way, so the refusal never tells whether a post exists.
+ */
+ if ( 0 !== $parent_id ) {
+ $parent = get_post( $parent_id );
+ if ( ! $parent instanceof WP_Post || ! $this->check_read_permission( $parent ) ) {
+ return false;
+ }
+ }
+ }
+
+ if ( array_key_exists( 'slug', $data ) ) {
+ // Without a changed status, the save keeps the stored status, or defaults to `draft`.
+ $status = $data['status'] ?? ( $post ? $post->post_status : 'draft' );
+
+ /*
+ * Intentionally strict: the save drops the slug of a pending post when the user
+ * cannot publish it, so a changed slug is refused instead of being dropped without
+ * notice. The stored slug sent back is accepted as unchanged, although the save
+ * still drops it.
+ */
+ if ( 'pending' === $status ) {
+ $can_publish = $post
+ ? current_user_can( 'publish_post', $post->ID )
+ : $this->current_user_can_for_post_type( $post_type_object, 'publish_posts' );
+ if ( ! $can_publish ) {
+ return false;
+ }
+ }
+ }
+
+ if ( array_key_exists( 'terms', $data ) && ! $this->can_set_terms( $data['terms'], $post_type_object->name, $post ) ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Checks the capabilities that the sent `terms` need.
+ *
+ * Assigning terms of a taxonomy, also removing them all, needs the capability to assign
+ * terms of the taxonomy, and each term the capability to assign that term. A taxonomy the
+ * post type does not use, and a term ID that names no term of the taxonomy, are refused by
+ * the execute callbacks.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $terms The sent `terms`.
+ * @param string $post_type The post type name.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return bool True if the user may assign the sent terms, false otherwise.
+ */
+ private function can_set_terms( $terms, string $post_type, ?WP_Post $post ): bool {
+ if ( ! rest_is_object( $terms ) ) {
+ return false;
+ }
+
+ foreach ( $this->get_changed_terms( rest_sanitize_object( $terms ), $post ) as $taxonomy => $term_ids ) {
+ $taxonomy_object = $this->get_post_type_taxonomy( $post_type, $taxonomy );
+ if ( ! $taxonomy_object ) {
+ continue;
+ }
+
+ $term_ids = $this->parse_term_ids( $term_ids );
+ if ( null === $term_ids || ! current_user_can( $taxonomy_object->cap->assign_terms ) ) {
+ return false;
+ }
+
+ foreach ( $term_ids as $term_id ) {
+ $term = get_term( $term_id, $taxonomy_object->name );
+ if ( $term instanceof WP_Term && ! current_user_can( 'assign_term', $term->term_id ) ) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Removes the taxonomies of the sent `terms` that keep their stored terms.
+ *
+ * A taxonomy keeps its stored terms when it lists them, in any order, so it is neither
+ * checked nor saved again. A taxonomy or a list that cannot be read is kept, so that it is
+ * checked. A new post has no terms yet, so on create the terms are returned as sent.
+ *
+ * @since 7.3.0
+ *
+ * @param array $terms The sent `terms`.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return array The sent `terms` without the taxonomies that keep their stored terms.
+ */
+ private function get_changed_terms( array $terms, ?WP_Post $post ): array {
+ if ( ! $post ) {
+ return $terms;
+ }
+
+ foreach ( $terms as $taxonomy => $term_ids ) {
+ $taxonomy_object = $this->get_post_type_taxonomy( $post->post_type, $taxonomy );
+ $term_ids = $this->parse_term_ids( $term_ids );
+ if ( ! $taxonomy_object || null === $term_ids ) {
+ continue;
+ }
+
+ $stored_ids = $this->get_post_term_ids( $post, $taxonomy_object->name );
+ sort( $term_ids );
+ sort( $stored_ids );
+ if ( $stored_ids === $term_ids ) {
+ unset( $terms[ $taxonomy ] );
+ }
+ }
+
+ return $terms;
+ }
+
+ /**
+ * Returns the sent `status`, `author`, `parent`, and `slug` that keep their stored values.
+ *
+ * A stored value sent back, also the empty slug of a draft, changes nothing, so it is
+ * neither checked nor saved again. A new post has no slug yet, so an empty `slug` sent
+ * on create counts as not sent.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return string[] The names of the sent attributes that keep their stored values.
+ *
+ * @phpstan-return list<'status'|'author'|'parent'|'slug'>
+ */
+ private function get_unchanged_attributes( array $data, ?WP_Post $post ): array {
+ $unchanged = array();
+ $stored = array( 'slug' => '' );
+ if ( $post ) {
+ $stored = array(
+ 'status' => $post->post_status,
+ 'author' => (int) $post->post_author,
+ 'parent' => (int) $post->post_parent,
+ 'slug' => $post->post_name,
+ );
+ }
+
+ foreach ( $stored as $attribute => $stored_value ) {
+ if ( ! array_key_exists( $attribute, $data ) ) {
+ continue;
+ }
+
+ $value = $data[ $attribute ];
+ if ( is_int( $stored_value ) ) {
+ // An author ID is at least 1, a parent ID at least 0.
+ $value = $this->parse_filter_int( $value, 'author' === $attribute ? 1 : 0 );
+ }
+
+ if ( $stored_value === $value ) {
+ $unchanged[] = $attribute;
+ }
+ }
+
+ return $unchanged;
+ }
+
+ /**
+ * 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, the given
+ * capability on the post that `where` names and, on update, the capabilities that the sent
+ * attributes need. A `where` that names no post of that type is let through, so that the
+ * execute callback reports it as not found.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input, which is not prepared when
+ * WP_Ability::check_permissions() is called directly.
+ * @param string $capability The capability required on the post: `edit_post` for an
+ * update, or `delete_post` for a delete.
+ * @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;
+ }
+
+ $input = rest_sanitize_object( $input );
+ $where = $this->get_input_object( $input, 'where' ) ?? array();
+ $post_type_object = $this->get_exposed_post_type( $where['type'] ?? null );
+ if ( ! $post_type_object ) {
+ return false;
+ }
+
+ // get_requested_post() only returns a post of the type that `where` names.
+ $post = $this->get_requested_post( $where );
+ if ( ! $post ) {
+ return true;
+ }
+
+ if ( ! current_user_can( $capability, $post->ID ) ) {
+ return false;
+ }
+
+ // Only an update sends attributes.
+ if ( 'edit_post' !== $capability ) {
+ return true;
+ }
+
+ $data = $this->get_input_object( $input, 'data' ) ?? array();
+
+ return $this->can_set_attributes( $data, $post_type_object, $post );
+ }
+
/**
* 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 +749,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 +811,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`: the input schema leaves out every internal status other than `trash`,
+ * and the statuses a query covers by default hold no internal status. A query
+ * filter such as a `pre_get_posts` callback can still add it, though, 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 +829,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.
*
@@ -411,7 +851,7 @@ private function execute_content_query( $input = array() ) {
*/
$where = $this->get_input_object( $input, 'where' );
if ( null === $where ) {
- return $this->invalid_filter_error( 'where', __( 'The where filter must be an object.' ) );
+ return $this->get_invalid_input_error( 'content_invalid_filter', 'where', __( 'The where filter must be an object.' ) );
}
// Pagination that is not an object falls back to the defaults, like page values that cannot be parsed.
@@ -419,19 +859,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->get_not_found_error();
}
$post_type = $post_type_object->name;
@@ -449,12 +885,12 @@ private function execute_content_query( $input = array() ) {
$parent = null;
if ( isset( $where['parent'] ) ) {
if ( ! is_post_type_hierarchical( $post_type ) ) {
- return $this->invalid_filter_error( 'where[parent]', __( 'The parent filter is only supported for hierarchical post types.' ) );
+ return $this->get_invalid_input_error( 'content_invalid_filter', 'where[parent]', __( 'The parent filter is only supported for hierarchical post types.' ) );
}
$parent = $this->parse_filter_int( $where['parent'], 0 );
if ( null === $parent ) {
- return $this->invalid_filter_error( 'where[parent]', __( 'The parent filter must be a non-negative integer.' ) );
+ return $this->get_invalid_input_error( 'content_invalid_filter', 'where[parent]', __( 'The parent filter must be a non-negative integer.' ) );
}
}
@@ -466,7 +902,8 @@ private function execute_content_query( $input = array() ) {
$author_id = null;
if ( array_key_exists( 'author', $where ) ) {
if ( ! post_type_supports( $post_type, 'author' ) ) {
- return $this->invalid_filter_error(
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[author]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter is only supported for post types that support authors.' ), 'author' )
@@ -480,7 +917,8 @@ private function execute_content_query( $input = array() ) {
*/
$author_filter = $this->get_input_object( $where, 'author' );
if ( empty( $author_filter ) || ! empty( array_diff_key( $author_filter, array_flip( array( 'id', 'slug' ) ) ) ) ) {
- return $this->invalid_filter_error(
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[author]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must be an object with an id or a slug.' ), 'author' )
@@ -494,7 +932,8 @@ private function execute_content_query( $input = array() ) {
if ( array_key_exists( 'id', $author_filter ) ) {
$author_id = $this->parse_filter_int( $author_filter['id'], 1 );
if ( null === $author_id ) {
- return $this->invalid_filter_error(
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[author][id]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s ID must be a positive integer.' ), 'author' )
@@ -504,7 +943,8 @@ private function execute_content_query( $input = array() ) {
if ( array_key_exists( 'slug', $author_filter ) ) {
if ( ! is_string( $author_filter['slug'] ) || '' === $author_filter['slug'] ) {
- return $this->invalid_filter_error(
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[author][slug]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s slug must be a non-empty string.' ), 'author' )
@@ -539,7 +979,8 @@ private function execute_content_query( $input = array() ) {
if ( isset( $where['ids'] ) ) {
$ids = $this->normalize_ids( $where );
if ( empty( $ids ) ) {
- return $this->invalid_filter_error(
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[ids]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list one or more valid post IDs.' ), 'ids' )
@@ -551,7 +992,8 @@ private function execute_content_query( $input = array() ) {
if ( isset( $where['slugs'] ) ) {
$slugs = $this->normalize_slugs( $where );
if ( empty( $slugs ) ) {
- return $this->invalid_filter_error(
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[slugs]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list one or more valid post slugs.' ), 'slugs' )
@@ -566,7 +1008,8 @@ private function execute_content_query( $input = array() ) {
*/
$statuses = $this->get_requested_statuses( $where );
if ( isset( $where['status'] ) && empty( $statuses ) ) {
- return $this->invalid_filter_error(
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[status]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list one or more post statuses.' ), 'status' )
@@ -577,10 +1020,11 @@ 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 ) ) ) ) ) {
- return $this->invalid_filter_error(
+ if ( ! empty( array_diff( $statuses, get_post_stati( array( 'internal' => false ) ), array( 'trash' ) ) ) ) {
+ return $this->get_invalid_input_error(
+ 'content_invalid_filter',
'where[status]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list valid post statuses.' ), 'status' )
@@ -654,55 +1098,593 @@ private function execute_content_query( $input = array() ) {
}
/*
- * 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.
+ * 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->get_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 or a trashed post 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 is checked first, then every attribute rule, and only then is the post
+ * saved, so a rejected call writes nothing. The capabilities are checked by
+ * {@see self::check_create_permission()}.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $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( $input ) {
+ /** @var array{ data?: Content_Write_Data } $input */
+ $data = $input['data'] ?? array();
+ $post_type_object = $this->get_exposed_post_type( $data['type'] ?? null );
+ if ( ! $post_type_object ) {
+ return $this->get_not_found_error();
+ }
+
+ $postarr = $this->prepare_post_data( $data, $post_type_object->name, null );
+ if ( is_wp_error( $postarr ) ) {
+ return $postarr;
+ }
+
+ return $this->persist_post( $postarr, $this->normalize_fields( $input ) );
+ }
+
+ /**
+ * Executes the `core/content-update` ability.
+ *
+ * The post is looked up first, then every attribute rule is checked, and only then is
+ * the post saved, so a rejected call writes nothing. The capabilities are checked by
+ * {@see self::check_post_permission()}.
+ *
+ * Known gap: a `data.status` sent for a post in the Trash moves it out of the Trash
+ * through a regular save, not through wp_untrash_post(). The `_wp_trash_meta_status`
+ * and `_wp_trash_meta_time` meta and the comments trashed with the post are left
+ * behind. The cause is in the save path, so the fix belongs there, where it covers
+ * every caller of wp_update_post().
+ *
+ * @since 7.3.0
+ *
+ * @link https://core.trac.wordpress.org/ticket/66809
+ *
+ * @param mixed $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( $input ) {
+ /** @var array{ where?: array, data?: Content_Write_Data } $input */
+ $post = $this->get_requested_post( $input['where'] ?? array() );
+ if ( ! $post ) {
+ return $this->get_not_found_error();
+ }
+
+ $postarr = $this->prepare_post_data( $input['data'] ?? array(), $post->post_type, $post );
+ if ( is_wp_error( $postarr ) ) {
+ return $postarr;
+ }
+
+ return $this->persist_post( $postarr, $this->normalize_fields( $input ) );
+ }
+
+ /**
+ * Executes the `core/content-delete` ability.
+ *
+ * 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. The capability is
+ * checked by {@see self::check_post_permission()}.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $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( $input ) {
+ /** @var array{ where?: array, permanent?: bool } $input */
+ $post = $this->get_requested_post( $input['where'] ?? array() );
+ if ( ! $post ) {
+ return $this->get_not_found_error();
+ }
+
+ if ( ! empty( $input['permanent'] ) ) {
+ $deleted = wp_delete_post( $post->ID, true );
+
+ return $deleted && null === get_post( $post->ID )
+ ? array( 'outcome' => 'deleted' )
+ : $this->get_delete_failed_error( __( 'The post could not be deleted.' ) );
+ }
+
+ /*
+ * Checked before wp_trash_post() is called: without a Trash, it deletes the post
+ * permanently instead.
+ */
+ $can_trash = EMPTY_TRASH_DAYS > 0 && ( 'attachment' !== $post->post_type || MEDIA_TRASH );
+ if ( ! $can_trash ) {
+ return new WP_Error(
+ 'content_trash_not_supported',
+ __( 'The post does not support trashing. Set `permanent` to true 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->get_delete_failed_error( __( 'The post could not be moved to the Trash.' ) );
+ }
+
+ /**
+ * Returns the post that `where` names, when it exists and has the named exposed type.
+ *
+ * The permission callback and the execute callback each call this method, and both read
+ * the ID with {@see self::parse_filter_int()}, so they resolve the same post. An ID that is
+ * not a whole number of at least 1 names no post.
+ *
+ * @since 7.3.0
+ *
+ * @param array $where The `where` input.
+ * @return WP_Post|null The post, or null when `where` names no post of an exposed type.
+ */
+ private function get_requested_post( array $where ): ?WP_Post {
+ $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::get_content_write_properties()} that were sent reach the array, each mapped
+ * to the post fields it sets, 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 string $post_type The post type name 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.
+ *
+ * @phpstan-param Content_Write_Data $data
+ */
+ private function prepare_post_data( array $data, string $post_type, ?WP_Post $post ) {
+ // Checked first, since an attribute that cannot be stored is refused even when unchanged.
+ $error = $this->check_supported_attributes( $data, $post_type );
+ if ( $error ) {
+ return $error;
+ }
+
+ foreach ( $this->get_unchanged_attributes( $data, $post ) as $attribute ) {
+ unset( $data[ $attribute ] );
+ }
+
+ /*
+ * Each step runs only for a sent attribute, takes its value, and returns the post
+ * fields to save, or the error of its first rule that fails. The date and the slug
+ * read the status and the parent that the post will have.
+ */
+ $steps = array(
+ 'title' => fn( string $title ) => array( 'post_title' => $title ),
+ 'content' => fn( string $content ) => array( 'post_content' => $content ),
+ 'excerpt' => fn( string $excerpt ) => array( 'post_excerpt' => $excerpt ),
+ 'status' => fn( string $status ) => array( 'post_status' => $status ),
+ 'author' => fn( int $author_id ) => $this->prepare_author( $author_id ),
+ 'parent' => fn( int $parent_id ) => $this->prepare_parent( $parent_id, $post_type, $post ),
+ 'date' => fn( array $date ) => $this->prepare_date( $date, $post, $data['status'] ?? null ),
+ // Without a changed status, the save keeps the stored status, or defaults to `draft`.
+ 'slug' => fn( string $slug ) => $this->prepare_slug(
+ $slug,
+ $post_type,
+ $post,
+ $data['status'] ?? ( $post ? $post->post_status : 'draft' ),
+ $data['parent'] ?? ( $post ? $post->post_parent : 0 )
+ ),
+ 'terms' => fn( array $terms ) => $this->prepare_terms( $this->get_changed_terms( $terms, $post ) ),
+ );
+
+ $postarr = array();
+ foreach ( $steps as $attribute => $step ) {
+ if ( ! array_key_exists( $attribute, $data ) ) {
+ continue;
+ }
+
+ $fields = $step( $data[ $attribute ] );
+ if ( is_wp_error( $fields ) ) {
+ return $fields;
+ }
+ $postarr = array_merge( $postarr, $fields );
+ }
+
+ if ( $post ) {
+ $postarr['ID'] = $post->ID;
+
+ // A stored page template that no longer exists must not fail an unrelated update.
+ $postarr['page_template'] = '';
+ } else {
+ $postarr['post_type'] = $post_type;
+ }
+
+ return $postarr;
+ }
+
+ /**
+ * Rejects the sent attributes that cannot be stored.
+ *
+ * These are the attributes that the post type does not support, a status that is not
+ * registered or is internal, and the terms of a taxonomy that the post type does not use.
+ *
+ * @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 attribute that cannot be stored, or null.
+ *
+ * @phpstan-param Content_Write_Data $data
+ */
+ 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->get_invalid_input_error(
+ 'content_invalid_attribute',
+ "data[{$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->get_invalid_input_error( 'content_invalid_attribute', 'data[parent]', __( 'The parent attribute is only supported for hierarchical post types.' ) );
+ }
+
+ /*
+ * 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 ( array_key_exists( 'status', $data ) ) {
+ $status_object = get_post_status_object( $data['status'] );
+ if ( ! $status_object instanceof stdClass || ! empty( $status_object->internal ) ) {
+ return $this->get_invalid_input_error( 'content_invalid_attribute', 'data[status]', __( 'The status must be a registered post status that is not internal.' ) );
+ }
+ }
+
+ if ( array_key_exists( 'terms', $data ) ) {
+ foreach ( array_keys( $data['terms'] ) as $taxonomy ) {
+ if ( ! $this->get_post_type_taxonomy( $post_type, $taxonomy ) ) {
+ return $this->get_invalid_input_error(
+ 'content_invalid_attribute',
+ 'data[terms]',
+ /* translators: %s: Taxonomy name, such as "post_tag". */
+ sprintf( __( 'The %s taxonomy is not used by the post type.' ), $taxonomy )
+ );
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Checks the sent `author` and returns the field to save.
+ *
+ * The capability to name another user is checked by the permission callbacks, so only
+ * users who may name any user learn whether a user ID exists.
+ *
+ * @since 7.3.0
+ *
+ * @param int $author_id The sent `author`, which differs from the stored one.
+ * @return array|WP_Error The author field, or a WP_Error.
+ */
+ private function prepare_author( int $author_id ) {
+ // Any other author must be an existing user who belongs to this site.
+ if (
+ get_current_user_id() !== $author_id
+ && ( ! get_userdata( $author_id ) || ( is_multisite() && ! is_user_member_of_blog( $author_id ) ) )
+ ) {
+ return $this->get_invalid_input_error( 'content_invalid_attribute', 'data[author]', __( 'The author must be an existing user of this site.' ) );
+ }
+
+ return array( 'post_author' => $author_id );
+ }
+
+ /**
+ * Checks the sent `parent` and returns the field to save.
+ *
+ * The permission callbacks refuse a parent that is missing or that the current user cannot
+ * read, so the errors here never tell whether a post ID exists.
+ *
+ * @since 7.3.0
+ *
+ * @param int $parent_id The sent `parent`, which differs from the stored one.
+ * @param string $post_type The post type name.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @return array|WP_Error The parent field, or a WP_Error.
+ */
+ private function prepare_parent( int $parent_id, string $post_type, ?WP_Post $post ) {
+ if ( 0 === $parent_id ) {
+ return array( 'post_parent' => 0 );
+ }
+
+ /*
+ * Intentionally strict: a parent must be 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
+ || ( $post && ( $post->ID === $parent->ID || in_array( $post->ID, get_post_ancestors( $parent ), true ) ) )
+ ) {
+ return $this->get_invalid_input_error(
+ 'content_invalid_attribute',
+ 'data[parent]',
+ __( 'The parent must be 0, or a post of the same post type that is neither the post itself nor one of its descendants.' )
+ );
+ }
+
+ return array( 'post_parent' => $parent_id );
+ }
+
+ /**
+ * Returns the date fields to save for the sent `date`.
+ *
+ * `site` wins when both `site` and `gmt` are sent, so the pair that the query returns can
+ * be sent back, also after the site's timezone changed. 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 $date The sent `date`, with `site`, `gmt` or both.
+ * @param WP_Post|null $post The stored post on update, or null on create.
+ * @param string|null $status The status to set, or null when none is sent or it is unchanged.
+ * @return array|WP_Error The date fields to save, empty for none, or a WP_Error.
+ */
+ private function prepare_date( array $date, ?WP_Post $post, ?string $status ) {
+ $is_site = isset( $date['site'] );
+ $value = $is_site ? $date['site'] : ( $date['gmt'] ?? null );
+ $dates = is_string( $value ) ? rest_get_date_with_gmt( $value, ! $is_site ) : null;
+
+ // Only reached by a direct call: the schema only accepts dates that can be read.
+ if ( null === $dates ) {
+ return $this->get_invalid_input_error( 'content_invalid_attribute', 'data[date]', __( 'The date must be a valid date in ISO 8601 format.' ) );
+ }
+
+ $fields = array(
+ 'post_date' => $dates[0],
+ 'post_date_gmt' => $dates[1],
+ );
+
+ if ( ! $post ) {
+ return $fields;
+ }
+
+ $fields['edit_date'] = true;
+
+ $is_floating = '0000-00-00 00:00:00' === $post->post_date_gmt;
+ if ( $is_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];
+ }
+
+ if ( ! $is_unchanged ) {
+ return $fields;
+ }
+
+ /*
+ * 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.
+ */
+ $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 field to save.
+ *
+ * @since 7.3.0
+ *
+ * @param string $slug The sent `slug`, which differs from the stored one.
+ * @param string $post_type The post type name 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 array|WP_Error The slug field, or a WP_Error.
+ */
+ private function prepare_slug( string $slug, string $post_type, ?WP_Post $post, string $status, int $parent_id ) {
+ $slug = sanitize_title( $slug );
+
+ // Intentionally strict: a slug that sanitizes to nothing is an error.
+ if ( '' === $slug ) {
+ return $this->get_invalid_input_error( 'content_invalid_attribute', 'data[slug]', __( 'The slug must contain characters that are valid in a slug.' ) );
+ }
+
+ /*
+ * Intentionally strict: a draft never takes the slug of another post that shares its
+ * parent. The save keeps the slugs of drafts, auto-drafts, and pending posts as given,
+ * so they are made unique here as if the post were published.
*/
- if ( $total > 0 && $page > $total_pages ) {
- return $this->invalid_page_number_error();
+ if ( in_array( $status, array( 'draft', 'pending', 'auto-draft' ), true ) ) {
+ $slug = wp_unique_post_slug( $slug, $post ? $post->ID : 0, 'publish', $post_type, $parent_id );
}
- /*
- * 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 );
+ return array( 'post_name' => $slug );
+ }
- $posts = array();
- foreach ( $query->posts as $post ) {
+ /**
+ * Checks the sent `terms` and returns the field to save.
+ *
+ * The save replaces the terms of each taxonomy listed, and keeps the terms of the others.
+ *
+ * @since 7.3.0
+ *
+ * @param array> $terms The sent `terms` that change, whose taxonomies the
+ * post type uses.
+ * @return array>>|WP_Error The terms field, empty when no
+ * taxonomy changes, or a WP_Error.
+ */
+ private function prepare_terms( array $terms ) {
+ foreach ( $terms as $taxonomy => $term_ids ) {
/*
- * 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.
+ * Intentionally strict: a term ID that names no term of the taxonomy is an error and
+ * is never skipped.
*/
- if ( ! $post instanceof WP_Post || $post_type !== $post->post_type ) {
- continue;
+ foreach ( $term_ids as $term_id ) {
+ if ( ! get_term( $term_id, $taxonomy ) instanceof WP_Term ) {
+ return $this->get_invalid_input_error(
+ 'content_invalid_attribute',
+ 'data[terms]',
+ /* translators: %s: Taxonomy name, such as "post_tag". */
+ sprintf( __( 'The %s terms must be IDs of existing terms of that taxonomy.' ), $taxonomy )
+ );
+ }
}
- if ( ! $this->check_read_permission( $post ) ) {
- continue;
+ }
+
+ return empty( $terms ) ? array() : array( 'tax_input' => $terms );
+ }
+
+ /**
+ * 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 persist_post( array $postarr, array $fields ) {
+ // The author visibility memo is per call; see get_visible_author().
+ $this->visible_authors = array();
+
+ /** @var Content_Post_Array $postarr The array that prepare_post_data() builds. */
+ $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 ) ) {
+ /*
+ * The save refuses a post whose title, content, and excerpt are all empty, and a
+ * date that is not a calendar date, such as one in the year 0. Both are errors of
+ * the sent `data`, so they are returned with their input path, like the errors of
+ * the attribute rules. Any other save error keeps its own code and message.
+ */
+ $code = $post_id->get_error_code();
+ $params = array(
+ 'empty_content' => 'data',
+ 'invalid_date' => 'data[date]',
+ );
+ if ( isset( $params[ $code ] ) ) {
+ return $this->get_invalid_input_error( 'content_invalid_attribute', $params[ $code ], $post_id->get_error_message() );
}
- $posts[] = $this->format_post( $post, $fields );
+
+ $is_database_error = in_array( $code, array( 'db_insert_error', 'db_update_error' ), true );
+ $post_id->add_data( array( 'status' => $is_database_error ? 500 : 400 ) );
+
+ return $post_id;
+ }
+
+ $post = get_post( $post_id );
+ if ( ! $post instanceof WP_Post ) {
+ return $this->get_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 );
}
/**
* 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
*
@@ -829,6 +1811,96 @@ private function get_exposed_post_type( $post_type ): ?WP_Post_Type {
return empty( $post_type_object->show_in_abilities ) ? null : $post_type_object;
}
+ /**
+ * Returns the taxonomies exposed through the Abilities API that an exposed post type uses.
+ *
+ * These are the taxonomies of `terms`, in registration order. Resolved on every call, as
+ * {@see self::get_exposed_post_type()} is.
+ *
+ * @since 7.3.0
+ *
+ * @return list Taxonomy names.
+ */
+ private function get_exposed_taxonomies(): array {
+ $post_types = array_values( get_post_types( array( 'show_in_abilities' => true ) ) );
+ if ( empty( $post_types ) ) {
+ return array();
+ }
+
+ return array_values(
+ array_filter(
+ get_object_taxonomies( $post_types ),
+ fn( $taxonomy ) => ! empty( get_taxonomy( $taxonomy )->show_in_abilities )
+ )
+ );
+ }
+
+ /**
+ * Returns a taxonomy exposed through the Abilities API that a post type uses.
+ *
+ * @since 7.3.0
+ *
+ * @param string $post_type The post type name.
+ * @param mixed $taxonomy The taxonomy name.
+ * @return WP_Taxonomy|null The taxonomy object, or null when the taxonomy is not exposed or
+ * the post type does not use it.
+ */
+ private function get_post_type_taxonomy( string $post_type, $taxonomy ): ?WP_Taxonomy {
+ $taxonomy_object = is_string( $taxonomy ) ? get_taxonomy( $taxonomy ) : false;
+ if ( ! $taxonomy_object instanceof WP_Taxonomy || empty( $taxonomy_object->show_in_abilities ) ) {
+ return null;
+ }
+
+ return is_object_in_taxonomy( $post_type, $taxonomy_object->name ) ? $taxonomy_object : null;
+ }
+
+ /**
+ * Parses a raw list of term IDs, or returns null when it is invalid.
+ *
+ * Like schema validation, it also accepts a single ID or a comma-separated string. Each ID
+ * is read with {@see self::parse_filter_int()}.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $term_ids The raw list.
+ * @return list|null The unique term IDs, or null when the list or one of its IDs is invalid.
+ */
+ private function parse_term_ids( $term_ids ): ?array {
+ if ( is_string( $term_ids ) ) {
+ $term_ids = wp_parse_list( $term_ids );
+ } elseif ( is_int( $term_ids ) || is_float( $term_ids ) ) {
+ $term_ids = array( $term_ids );
+ } elseif ( ! is_array( $term_ids ) ) {
+ return null;
+ }
+
+ $ids = array();
+ foreach ( $term_ids as $term_id ) {
+ $id = $this->parse_filter_int( $term_id, 1 );
+ if ( null === $id ) {
+ return null;
+ }
+ $ids[] = $id;
+ }
+
+ return array_values( array_unique( $ids ) );
+ }
+
+ /**
+ * Returns the IDs of a post's terms in a taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_Post $post The post.
+ * @param string $taxonomy The taxonomy name.
+ * @return list The term IDs.
+ */
+ private function get_post_term_ids( WP_Post $post, string $taxonomy ): array {
+ $terms = get_the_terms( $post, $taxonomy );
+
+ return is_array( $terms ) ? array_values( array_map( static fn( WP_Term $term ): int => $term->term_id, $terms ) ) : array();
+ }
+
/**
* Returns the statuses the `status` filter explicitly requests.
*
@@ -967,11 +2039,12 @@ private function normalize_fields( array $input ): array {
* posts the current user can edit.
*
* @since 7.2.0
+ * @since 7.3.0 Added `terms`.
*
* @return array Post field definitions.
*/
private function get_post_properties(): array {
- return array(
+ $properties = array(
'id' => array(
'type' => 'integer',
'description' => __( 'The post ID.' ),
@@ -1104,6 +2177,28 @@ private function get_post_properties(): array {
'description' => __( 'The parent post ID. Present for hierarchical post types.' ),
),
);
+
+ $taxonomies = $this->get_exposed_taxonomies();
+ if ( ! empty( $taxonomies ) ) {
+ $properties['terms'] = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'properties' => array_fill_keys(
+ $taxonomies,
+ array(
+ 'type' => 'array',
+ 'items' => array( 'type' => 'integer' ),
+ )
+ ),
+ 'description' => __( 'The IDs of the post\'s terms, keyed by taxonomy, as `core/terms-query` returns them. Holds each taxonomy exposed to abilities that the post type uses, with an empty list when the post has no terms in it. Present when the post type uses such a taxonomy.' ),
+ );
+ foreach ( $taxonomies as $taxonomy ) {
+ /* translators: %s: Taxonomy name, such as "post_tag". */
+ $properties['terms']['properties'][ $taxonomy ]['description'] = sprintf( __( 'The IDs of the post\'s terms in the %s taxonomy.' ), $taxonomy );
+ }
+ }
+
+ return $properties;
}
/**
@@ -1132,7 +2227,7 @@ private function get_field_paths(): array {
}
/**
- * Builds the schema of the `fields` input, shared by all content abilities.
+ * Builds the schema of the `fields` input, shared by the query, create, and update abilities.
*
* @since 7.2.0
*
@@ -1216,7 +2311,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',
@@ -1273,7 +2368,233 @@ private function get_content_query_input_schema( array $post_types, array $statu
}
/**
- * Builds the output schema of a single post, shared by all content abilities.
+ * 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 {
+ $properties = 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',
+ '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. A post that has a slug cannot be given an empty one. Setting the slug of a pending post requires the capability to publish it.' ),
+ ),
+ '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.' ),
+ ),
+ );
+
+ $taxonomies = $this->get_exposed_taxonomies();
+ if ( ! empty( $taxonomies ) ) {
+ $properties['terms'] = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'minProperties' => 1,
+ 'properties' => array(),
+ 'description' => __( 'The IDs of the terms to assign, keyed by taxonomy, as `core/terms-query` returns them. Each taxonomy listed replaces the post\'s terms in it, and an empty list removes them; a taxonomy left out keeps its terms. Assigning terms requires the capability to assign terms of the taxonomy. Only supported for the taxonomies the post type uses.' ),
+ );
+ foreach ( $taxonomies as $taxonomy ) {
+ $properties['terms']['properties'][ $taxonomy ] = array(
+ 'type' => 'array',
+ 'uniqueItems' => true,
+ 'items' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ /* translators: %s: Taxonomy name, such as "post_tag". */
+ 'description' => sprintf( __( 'The IDs of existing terms of the %s taxonomy.' ), $taxonomy ),
+ );
+ }
+ }
+
+ return $properties;
+ }
+
+ /**
+ * 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',
+ 'enum' => array( 'trashed', 'deleted' ),
+ '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 the query, create, and update abilities.
*
* Only `id` is required, because it is always returned. The other fields are optional
* because the `fields` input lets the caller request any subset, and a field is only
@@ -1343,7 +2664,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
@@ -1537,6 +2858,18 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit
$data['parent'] = (int) $post->post_parent;
}
+ if ( $this->is_field_requested( 'terms', $fields ) ) {
+ $terms = array();
+ foreach ( $this->get_exposed_taxonomies() as $taxonomy ) {
+ if ( $this->is_field_requested( "terms.{$taxonomy}", $fields ) && is_object_in_taxonomy( $post_type, $taxonomy ) ) {
+ $terms[ $taxonomy ] = $this->get_post_term_ids( $post, $taxonomy );
+ }
+ }
+ if ( ! empty( $terms ) ) {
+ $data['terms'] = $terms;
+ }
+ }
+
return $data;
}
@@ -1803,7 +3136,7 @@ private function prepare_output( array $items, int $total, int $total_pages ): a
*
* @return WP_Error The invalid page number error.
*/
- private function invalid_page_number_error(): WP_Error {
+ private function get_invalid_page_number_error(): WP_Error {
return new WP_Error(
'content_invalid_page_number',
__( 'The page number requested is larger than the number of pages available.' ),
@@ -1812,21 +3145,21 @@ private function invalid_page_number_error(): WP_Error {
}
/**
- * Builds the error for a filter that cannot be honored.
+ * Builds the error for a filter or a `data` attribute that cannot be honored.
*
- * As in the REST API's `rest_invalid_param` errors, the error data maps the filter's
- * input path to the message under `params`, so callers can tell which filter failed
- * without parsing the translated message.
+ * The error data maps the input path to the message under `params`, so callers can tell
+ * which filter or attribute failed without parsing the translated message.
*
* @since 7.2.0
*
- * @param string $param The filter's input path, such as `where[ids]`.
+ * @param string $code The error code: `content_invalid_filter` or `content_invalid_attribute`.
+ * @param string $param The input path, such as `where[ids]` or `data[title]`.
* @param string $message The error message.
- * @return WP_Error The invalid filter error.
+ * @return WP_Error The invalid input error.
*/
- private function invalid_filter_error( string $param, string $message ): WP_Error {
+ private function get_invalid_input_error( string $code, string $param, string $message ): WP_Error {
return new WP_Error(
- 'content_invalid_filter',
+ $code,
$message,
array(
'status' => 400,
@@ -1834,4 +3167,34 @@ 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 get_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 delete or trash call that failed or could not be confirmed.
+ *
+ * @since 7.3.0
+ *
+ * @param string $message The error message, which names the operation that failed.
+ * @return WP_Error The delete failed error.
+ */
+ private function get_delete_failed_error( string $message ): WP_Error {
+ return new WP_Error( 'content_delete_failed', $message, array( 'status' => 500 ) );
+ }
}
diff --git a/src/wp-includes/abilities/class-wp-abilities-terms.php b/src/wp-includes/abilities/class-wp-abilities-terms.php
new file mode 100644
index 0000000000000..e8ec572d06787
--- /dev/null
+++ b/src/wp-includes/abilities/class-wp-abilities-terms.php
@@ -0,0 +1,1533 @@
+execute()`, which validates the input and
+ * checks permissions before running them.
+ *
+ * @since 7.3.0
+ *
+ * @access private
+ */
+final class WP_Abilities_Terms {
+
+ /**
+ * The ability category used for term abilities.
+ *
+ * @since 7.3.0
+ * @var string
+ */
+ private const CATEGORY = 'content';
+
+ /**
+ * Default number of terms returned per page, unless `where` lists terms by ID or slug.
+ *
+ * @since 7.3.0
+ * @var int
+ */
+ private const DEFAULT_PER_PAGE = 10;
+
+ /**
+ * Maximum number of terms returned per page.
+ *
+ * The `ids` and `slugs` lists in `where` each hold at most this many values.
+ *
+ * @since 7.3.0
+ * @var int
+ */
+ private const MAX_PER_PAGE = 100;
+
+ /**
+ * Default fields returned when the caller does not request a field subset.
+ *
+ * @since 7.3.0
+ * @var list
+ */
+ private const DEFAULT_FIELDS = array( 'id', 'taxonomy', 'name', 'slug', 'link' );
+
+ /**
+ * Registers all term abilities.
+ *
+ * Must run on the `wp_abilities_api_init` hook.
+ *
+ * @since 7.3.0
+ */
+ public function register(): void {
+ /*
+ * Taxonomies must be registered with `show_in_abilities` before the abilities are
+ * registered so they are included in the input schemas. Without one, no term
+ * ability is registered.
+ */
+ $taxonomies = array_values( get_taxonomies( array( 'show_in_abilities' => true ) ) );
+ if ( empty( $taxonomies ) ) {
+ return;
+ }
+
+ $this->register_terms_query( $taxonomies );
+ $this->register_term_create( $taxonomies );
+ $this->register_term_update( $taxonomies );
+ $this->register_term_delete( $taxonomies );
+ }
+
+ /**
+ * Registers the read-only `core/terms-query` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ */
+ private function register_terms_query( array $taxonomies ): void {
+ wp_register_ability(
+ 'core/terms-query',
+ array(
+ 'label' => __( 'Query Terms' ),
+ 'description' => __( 'Retrieves a paginated list of the terms of a taxonomy exposed to abilities, filtered by any of term IDs, slugs, parent, post, and whether the term is assigned to any post. Requires an authenticated user. Filters are exact-match only; the ability does not perform full-text search.' ),
+ 'category' => self::CATEGORY,
+ 'input_schema' => $this->get_terms_query_input_schema( $taxonomies ),
+ 'output_schema' => $this->get_terms_query_output_schema(),
+ 'execute_callback' => function ( $input = array() ) {
+ return $this->execute_terms_query( $input );
+ },
+ 'permission_callback' => function ( $input = array() ): bool {
+ return $this->check_query_permission( $input );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => true,
+ 'destructive' => false,
+ 'idempotent' => true,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+ }
+
+ /**
+ * Registers the `core/term-create` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ */
+ private function register_term_create( array $taxonomies ): void {
+ wp_register_ability(
+ 'core/term-create',
+ array(
+ 'label' => __( 'Create Term' ),
+ 'description' => __( 'Creates a term in a taxonomy exposed to abilities and returns it. Requires an authenticated user who can create terms in that taxonomy.' ),
+ 'category' => self::CATEGORY,
+ 'input_schema' => $this->get_term_create_input_schema( $taxonomies ),
+ 'output_schema' => $this->get_term_output_schema(),
+ 'execute_callback' => function ( $input = array() ) {
+ return $this->execute_term_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/term-update` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ */
+ private function register_term_update( array $taxonomies ): void {
+ wp_register_ability(
+ 'core/term-update',
+ array(
+ 'label' => __( 'Update Term' ),
+ 'description' => __( 'Updates the given attributes of a term of a taxonomy exposed to abilities and returns it. Attributes that are left out keep their stored values. Requires an authenticated user who can edit the term.' ),
+ 'category' => self::CATEGORY,
+ 'input_schema' => $this->get_term_update_input_schema( $taxonomies ),
+ 'output_schema' => $this->get_term_output_schema(),
+ 'execute_callback' => function ( $input = array() ) {
+ return $this->execute_term_update( $input );
+ },
+ 'permission_callback' => function ( $input = array() ): bool {
+ return $this->check_term_permission( $input, 'edit' );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => false,
+ 'destructive' => false,
+ 'idempotent' => true,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+ }
+
+ /**
+ * Registers the `core/term-delete` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ */
+ private function register_term_delete( array $taxonomies ): void {
+ wp_register_ability(
+ 'core/term-delete',
+ array(
+ 'label' => __( 'Delete Term' ),
+ 'description' => __( 'Deletes a term of a taxonomy exposed to abilities permanently. Terms cannot be trashed, so `permanent` must be true. The default term of a taxonomy cannot be deleted. Requires an authenticated user who can delete the term.' ),
+ 'category' => self::CATEGORY,
+ 'input_schema' => $this->get_term_delete_input_schema( $taxonomies ),
+ 'output_schema' => $this->get_term_delete_output_schema(),
+ 'execute_callback' => function ( $input = array() ) {
+ return $this->execute_term_delete( $input );
+ },
+ 'permission_callback' => function ( $input = array() ): bool {
+ return $this->check_term_permission( $input, 'delete' );
+ },
+ 'meta' => array(
+ 'annotations' => array(
+ 'readonly' => false,
+ 'destructive' => true,
+ 'idempotent' => true,
+ ),
+ 'public' => true,
+ ),
+ )
+ );
+ }
+
+ /**
+ * Permission callback for the `core/terms-query` ability.
+ *
+ * Requires a logged-in user and a `where.taxonomy` that is exposed to abilities. No
+ * capability is needed to query terms.
+ *
+ * @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_query_permission( $input = array() ): bool {
+ // Intentionally strict: terms can only be queried by a logged-in user.
+ if ( ! is_user_logged_in() ) {
+ return false;
+ }
+
+ // The input is read defensively: WP_Ability::check_permissions() does not prepare it.
+ $where = $this->get_raw_member( $input, 'where' );
+
+ return null !== $where && null !== $this->get_exposed_taxonomy( $where['taxonomy'] ?? null );
+ }
+
+ /**
+ * Permission callback for the `core/term-create` ability.
+ *
+ * Requires a logged-in user, a `data.taxonomy` that is exposed to abilities, and the
+ * capability to create terms in it. {@see self::execute_term_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_raw_member( $input, 'data' );
+ if ( null === $data ) {
+ return false;
+ }
+
+ $taxonomy_object = $this->get_exposed_taxonomy( $data['taxonomy'] ?? null );
+
+ return null !== $taxonomy_object && $this->can_create_terms( $taxonomy_object );
+ }
+
+ /**
+ * Permission callback for the `core/term-update` and `core/term-delete` abilities.
+ *
+ * Requires a logged-in user, a `where.taxonomy` that is exposed to abilities, a valid
+ * `where.id`, and the capability to edit or delete the term it names. A term that does
+ * not exist in the taxonomy 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 $action The operation: `edit` or `delete`.
+ * @return bool True if the request may proceed, false otherwise.
+ */
+ private function check_term_permission( $input, string $action ): bool {
+ if ( ! is_user_logged_in() ) {
+ return false;
+ }
+
+ // The input is read defensively: WP_Ability::check_permissions() does not prepare it.
+ $where = $this->get_raw_member( $input, 'where' );
+ if ( null === $where ) {
+ return false;
+ }
+
+ $taxonomy_object = $this->get_exposed_taxonomy( $where['taxonomy'] ?? null );
+ if ( ! $taxonomy_object ) {
+ return false;
+ }
+
+ $term_id = $this->parse_filter_int( $where['id'] ?? null, 1 );
+ if ( null === $term_id ) {
+ return false;
+ }
+
+ $term = $this->get_term_in_taxonomy( $term_id, $taxonomy_object->name );
+ if ( ! $term ) {
+ return true;
+ }
+
+ return 'delete' === $action
+ ? $this->can_delete_term( $term_id, $taxonomy_object )
+ : current_user_can( 'edit_term', $term_id );
+ }
+
+ /**
+ * Reads an object member of the raw input, such as `where` or `data`.
+ *
+ * Both the input and the member count as objects when they are an array or a `stdClass`.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The raw ability input.
+ * @param string $key The member name.
+ * @return array|null The member as an array, or null when the input or the member
+ * is missing or not an object.
+ */
+ private function get_raw_member( $input, string $key ): ?array {
+ $input = $this->get_raw_object( $input );
+ if ( null === $input || ! array_key_exists( $key, $input ) ) {
+ return null;
+ }
+
+ return $this->get_raw_object( $input[ $key ] );
+ }
+
+ /**
+ * Reads a raw value as an object.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $value The raw value.
+ * @return array|null The value as an array, or null when it is not an array or a `stdClass`.
+ */
+ private function get_raw_object( $value ): ?array {
+ if ( is_array( $value ) ) {
+ return $value;
+ }
+
+ return $value instanceof stdClass ? get_object_vars( $value ) : null;
+ }
+
+ /**
+ * 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".
+ * 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 term.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $value The raw input value.
+ * @param int $min The smallest acceptable value.
+ * @return int|null The parsed integer, or null when the value is not an integer >= $min.
+ */
+ private function parse_filter_int( $value, int $min ): ?int {
+ if ( is_int( $value ) ) {
+ return $value >= $min ? $value : null;
+ }
+
+ if ( is_string( $value ) && '' !== $value && ctype_digit( $value ) ) {
+ $int = (int) $value;
+
+ return $int >= $min ? $int : null;
+ }
+
+ if ( ! rest_is_integer( $value ) ) {
+ return null;
+ }
+
+ /*
+ * Other whole numbers are read as floats, which hold every integer only up to 2 ** 53.
+ * Past that, the value may not be the one that was sent, and casting a float beyond the
+ * integer range wraps it to an arbitrary integer, such as the ID of another term.
+ */
+ $number = (float) $value;
+
+ return $number >= $min && $number <= 2 ** 53 ? (int) $number : null;
+ }
+
+ /**
+ * Returns a taxonomy exposed through the Abilities API.
+ *
+ * Deliberately resolved on every call rather than cached: taxonomies can be
+ * unregistered or re-registered with different arguments between the ability
+ * being registered and the ability being used.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $taxonomy The taxonomy name.
+ * @return WP_Taxonomy|null The taxonomy object, or null when the taxonomy is not exposed.
+ */
+ private function get_exposed_taxonomy( $taxonomy ): ?WP_Taxonomy {
+ $taxonomy_object = is_string( $taxonomy ) ? get_taxonomy( $taxonomy ) : false;
+
+ return $taxonomy_object instanceof WP_Taxonomy && ! empty( $taxonomy_object->show_in_abilities ) ? $taxonomy_object : null;
+ }
+
+ /**
+ * Checks whether the current user can read a post.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_Post $post The post.
+ * @return bool Whether the current user can read the post.
+ */
+ private function can_read_post( WP_Post $post ): bool {
+ if ( is_post_publicly_viewable( $post ) ) {
+ return true;
+ }
+
+ /*
+ * Intentionally strict: a post with a public status that is not publicly viewable, such
+ * as a published post of a post type that is not public, can be read by the users who
+ * can edit it. The capability to read such a post is the plain `read` capability.
+ */
+ $status = get_post_status( $post );
+ $status = is_string( $status ) ? get_post_status_object( $status ) : null;
+ if ( $status instanceof stdClass && $status->public ) {
+ return current_user_can( 'edit_post', $post->ID );
+ }
+
+ return current_user_can( 'read_post', $post->ID );
+ }
+
+ /**
+ * Returns the term of an ID, when it belongs to the given taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @param int $term_id The term ID.
+ * @param string $taxonomy The taxonomy name.
+ * @return WP_Term|null The term, or null when the taxonomy holds no term of that ID.
+ */
+ private function get_term_in_taxonomy( int $term_id, string $taxonomy ): ?WP_Term {
+ $term = get_term( $term_id, $taxonomy );
+
+ return $term instanceof WP_Term && $taxonomy === $term->taxonomy ? $term : null;
+ }
+
+ /**
+ * Checks whether the current user may create terms in a taxonomy.
+ *
+ * Terms of a hierarchical taxonomy need the capability to edit terms; terms of a flat
+ * taxonomy, such as tags, the capability to assign them.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_Taxonomy $taxonomy_object The taxonomy object.
+ * @return bool Whether the current user may create terms in the taxonomy.
+ */
+ private function can_create_terms( WP_Taxonomy $taxonomy_object ): bool {
+ return current_user_can( $taxonomy_object->hierarchical ? $taxonomy_object->cap->edit_terms : $taxonomy_object->cap->assign_terms );
+ }
+
+ /**
+ * Checks whether the current user may delete a term.
+ *
+ * The default term of a taxonomy can never be deleted, and the `delete_term` capability is
+ * denied for it. For a default term, the capability to delete terms of the taxonomy is
+ * checked instead, so that a user who could delete other terms learns that the term is
+ * the default one. Any other term needs the `delete_term` capability on its ID.
+ *
+ * @since 7.3.0
+ *
+ * @param int $term_id The term ID.
+ * @param WP_Taxonomy $taxonomy_object The taxonomy of the term.
+ * @return bool Whether the current user may delete the term.
+ */
+ private function can_delete_term( int $term_id, WP_Taxonomy $taxonomy_object ): bool {
+ if ( $this->is_default_term( $term_id, $taxonomy_object ) ) {
+ return current_user_can( $taxonomy_object->cap->delete_terms );
+ }
+
+ return current_user_can( 'delete_term', $term_id );
+ }
+
+ /**
+ * Checks whether a term is the default term of its taxonomy, which wp_delete_term() refuses to delete.
+ *
+ * The default term is the term of the `default_category` option for categories, and the term
+ * of the `default_term_{$taxonomy}` option for a taxonomy registered with a default term. No
+ * other term is a default term.
+ *
+ * @since 7.3.0
+ *
+ * @param int $term_id The term ID.
+ * @param WP_Taxonomy $taxonomy_object The taxonomy of the term.
+ * @return bool Whether the term is the default term.
+ */
+ private function is_default_term( int $term_id, WP_Taxonomy $taxonomy_object ): bool {
+ if ( 'category' === $taxonomy_object->name && (int) get_option( 'default_category' ) === $term_id ) {
+ return true;
+ }
+
+ return ! empty( $taxonomy_object->default_term ) && (int) get_option( 'default_term_' . $taxonomy_object->name ) === $term_id;
+ }
+
+ /**
+ * Executes the `core/terms-query` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The ability input, as prepared by WP_Ability::execute().
+ * @return array|WP_Error A page of terms, or a WP_Error on failure.
+ */
+ private function execute_terms_query( array $input ) {
+ $where = $input['where'] ?? array();
+ $taxonomy_object = $this->get_exposed_taxonomy( $where['taxonomy'] ?? null );
+ if ( ! $taxonomy_object ) {
+ return $this->taxonomy_not_found_error();
+ }
+
+ $taxonomy = $taxonomy_object->name;
+
+ // Intentionally strict: a parent filter on a flat taxonomy is an error, not ignored.
+ if ( array_key_exists( 'parent', $where ) && ! $taxonomy_object->hierarchical ) {
+ return $this->invalid_filter_error(
+ 'where[parent]',
+ /* translators: %s: Taxonomy name. */
+ sprintf( __( 'The "%s" taxonomy is not hierarchical.' ), $taxonomy )
+ );
+ }
+
+ /*
+ * Intentionally strict: the terms of a post are listed whether or not they are used,
+ * so hiding empty terms cannot be combined with the post filter.
+ */
+ $hide_empty = true === ( $where['hide_empty'] ?? false );
+ if ( $hide_empty && isset( $where['post'] ) ) {
+ return $this->invalid_filter_error(
+ 'where[hide_empty]',
+ /* translators: 1: Parameter, 2: Parameter. */
+ sprintf( __( 'The %1$s filter cannot be combined with the %2$s filter.' ), 'hide_empty', 'post' )
+ );
+ }
+
+ /*
+ * A post that is missing, does not use the taxonomy, or cannot be read gives the same
+ * error, so the filter never tells whether a post ID exists.
+ */
+ $post = null;
+ if ( isset( $where['post'] ) ) {
+ // An ID that is not valid is never handed to get_post(), which reads 0 as the global post.
+ $post_id = $this->parse_filter_int( $where['post'], 1 );
+ $post = null !== $post_id ? get_post( $post_id ) : null;
+
+ // Intentionally strict: a post of a post type that is not exposed to abilities gives that error too.
+ $exposed = $post instanceof WP_Post && ! empty( get_post_type_object( $post->post_type )->show_in_abilities );
+ if (
+ ! $post instanceof WP_Post
+ || ! $exposed
+ || ! is_object_in_taxonomy( $post->post_type, $taxonomy )
+ || ! $this->can_read_post( $post )
+ ) {
+ return $this->invalid_filter_error( 'where[post]', __( 'Invalid post ID.' ) );
+ }
+ }
+
+ /*
+ * The schema bounds the page and the page size. Both are bounded here as well, as a
+ * filter can let input past the schema.
+ */
+ $pagination = $input['pagination'] ?? array();
+ $page = $this->parse_filter_int( $pagination['page'] ?? 1, 1 ) ?? 1;
+ $lists = isset( $where['ids'] ) || isset( $where['slugs'] );
+ $per_page = min( self::MAX_PER_PAGE, $this->parse_filter_int( $pagination['per_page'] ?? null, 1 ) ?? ( $lists ? self::MAX_PER_PAGE : self::DEFAULT_PER_PAGE ) );
+
+ /*
+ * No order is set, so terms are ordered by name, ascending, unless the taxonomy is
+ * registered with another order. Terms with equal names have no defined order.
+ */
+ $args = array(
+ 'taxonomy' => $taxonomy,
+ 'hide_empty' => $hide_empty,
+ );
+ if ( isset( $where['ids'] ) ) {
+ // Entries that are not valid term IDs are left out; the list must keep at least one.
+ $ids = array_values( array_filter( array_map( fn( $id ) => $this->parse_filter_int( $id, 1 ), $where['ids'] ) ) );
+ if ( empty( $ids ) ) {
+ return $this->invalid_filter_error(
+ 'where[ids]',
+ /* translators: %s: Parameter. */
+ sprintf( __( 'The %s filter must list one or more valid term IDs.' ), 'ids' )
+ );
+ }
+ $args['include'] = $ids;
+ }
+ if ( isset( $where['slugs'] ) ) {
+ /*
+ * Intentionally strict: each slug is sanitized as a term slug is when the term is
+ * saved, and one that sanitizes to an empty string, such as `!!!`, names no term
+ * and is left out. A list that keeps no slug is an error, not an empty page.
+ */
+ $slugs = array();
+ foreach ( is_array( $where['slugs'] ) ? $where['slugs'] : array() as $slug ) {
+ $slug = is_string( $slug ) ? sanitize_title( $slug ) : '';
+ if ( '' !== $slug ) {
+ $slugs[] = $slug;
+ }
+ }
+ if ( empty( $slugs ) ) {
+ return $this->invalid_filter_error(
+ 'where[slugs]',
+ /* translators: %s: Parameter. */
+ sprintf( __( 'The %s filter must list one or more valid term slugs.' ), 'slugs' )
+ );
+ }
+ $args['slug'] = array_values( array_unique( $slugs ) );
+ }
+ if ( isset( $where['parent'] ) ) {
+ $parent = $this->parse_filter_int( $where['parent'], 0 );
+ if ( null === $parent ) {
+ return $this->invalid_filter_error( 'where[parent]', __( 'The parent filter must be a non-negative integer.' ) );
+ }
+ $args['parent'] = $parent;
+ }
+
+ /*
+ * The query arguments a taxonomy is registered with apply to its terms, as they do
+ * when the terms of a post are listed, which applies them itself. Paging and the kind
+ * of result are set afterwards, so on this path the page is always the one requested
+ * and the query always returns the terms the items are built from.
+ */
+ if ( ! $post && is_array( $taxonomy_object->args ) ) {
+ $args = array_merge( $args, $taxonomy_object->args );
+ }
+
+ // The total counts every matching term, so no paging reaches the count, even from the taxonomy.
+ $count_args = $args;
+ unset( $count_args['number'], $count_args['offset'] );
+ if ( $post ) {
+ $count_args['object_ids'] = $post->ID;
+ }
+
+ $args['fields'] = 'all';
+ $args['number'] = $per_page;
+ $args['offset'] = ( $page - 1 ) * $per_page;
+
+ /*
+ * With empty terms hidden, a hierarchical taxonomy still lists an empty term that has a
+ * descendant in use, and the count of terms leaves it out. Core already reads every
+ * matching term to build such a list and pages it afterwards, so here the list is read
+ * once without paging, counted, and paged, and every listed term is on a counted page.
+ */
+ if ( ! $post && $taxonomy_object->hierarchical && ! empty( $args['hide_empty'] ) ) {
+ $listed = get_terms(
+ array_merge(
+ $args,
+ array(
+ 'number' => 0,
+ 'offset' => 0,
+ )
+ )
+ );
+ $listed = is_array( $listed ) ? array_values( $listed ) : array();
+ $total = count( $listed );
+ $terms = array_slice( $listed, $args['offset'], $per_page );
+ } else {
+ $terms = $post ? wp_get_object_terms( $post->ID, $taxonomy, $args ) : get_terms( $args );
+ $total = wp_count_terms( $count_args );
+ $total = is_numeric( $total ) ? (int) $total : 0;
+ }
+
+ $fields = $this->normalize_fields( $input );
+ $items = array();
+ foreach ( is_array( $terms ) ? $terms : array() as $term ) {
+ /*
+ * Intentionally strict: anything but a term of the taxonomy, such as a term of another
+ * taxonomy that a query filter adds, is left out of the items.
+ */
+ if ( ! $term instanceof WP_Term || $taxonomy !== $term->taxonomy ) {
+ continue;
+ }
+ $items[] = $this->format_term( $term, $fields );
+ }
+
+ $total_pages = (int) ceil( $total / $per_page );
+
+ /*
+ * Intentionally strict: a page past the last one does not exist, so it is reported as
+ * not found instead of returning a bare empty list. A page that holds terms is always
+ * returned, and a request that matches no term returns zero totals and no error.
+ */
+ if ( empty( $items ) && $total > 0 && $page > $total_pages ) {
+ return new WP_Error(
+ 'terms_invalid_page_number',
+ __( 'The page number requested is larger than the number of pages available.' ),
+ array( 'status' => 404 )
+ );
+ }
+
+ return array(
+ 'items' => $items,
+ 'pagination' => array(
+ 'total' => $total,
+ 'total_pages' => $total_pages,
+ ),
+ );
+ }
+
+ /**
+ * Executes the `core/term-create` ability.
+ *
+ * The taxonomy and the capability to create terms in it are checked first, then every
+ * attribute rule, and only then is the term 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 term, or a WP_Error on failure.
+ */
+ private function execute_term_create( array $input ) {
+ $data = $input['data'] ?? array();
+ $taxonomy_object = $this->get_exposed_taxonomy( $data['taxonomy'] ?? null );
+ if ( ! $taxonomy_object ) {
+ return $this->taxonomy_not_found_error();
+ }
+
+ // Checked again after the permission callback, whose result a filter can change.
+ if ( ! $this->can_create_terms( $taxonomy_object ) ) {
+ return new WP_Error(
+ 'term_cannot_create',
+ __( 'Sorry, you are not allowed to create terms in this taxonomy.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ $error = $this->check_attributes( $data, $taxonomy_object, null );
+ if ( $error ) {
+ return $error;
+ }
+
+ $args = $this->get_save_args( $data, array( 'slug', 'description', 'parent' ) );
+ $name = (string) ( $data['name'] ?? '' );
+
+ $result = wp_insert_term( wp_slash( $name ), $taxonomy_object->name, wp_slash( $args ) );
+
+ return $this->prepare_save_result( $result, $taxonomy_object->name, $this->normalize_fields( $input ) );
+ }
+
+ /**
+ * Executes the `core/term-update` ability.
+ *
+ * The term is looked up first, then the capability to edit it is checked, then every
+ * attribute rule, and only then is the term 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 term, or a WP_Error on failure.
+ */
+ private function execute_term_update( array $input ) {
+ $where = $input['where'] ?? array();
+ $term_id = (int) ( $where['id'] ?? 0 );
+ $taxonomy_object = $this->get_exposed_taxonomy( $where['taxonomy'] ?? null );
+ if ( ! $taxonomy_object || ! $this->get_term_in_taxonomy( $term_id, $taxonomy_object->name ) ) {
+ return $this->term_not_found_error();
+ }
+
+ // Checked again after the permission callback, whose result a filter can change.
+ if ( ! current_user_can( 'edit_term', $term_id ) ) {
+ return new WP_Error(
+ 'term_cannot_edit',
+ __( 'Sorry, you are not allowed to edit this term.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ $data = $input['data'] ?? array();
+ $error = $this->check_attributes( $data, $taxonomy_object, $term_id );
+ if ( $error ) {
+ return $error;
+ }
+
+ $args = $this->get_save_args( $data, array( 'name', 'slug', 'description', 'parent' ) );
+ $result = wp_update_term( $term_id, $taxonomy_object->name, wp_slash( $args ) );
+
+ return $this->prepare_save_result( $result, $taxonomy_object->name, $this->normalize_fields( $input ) );
+ }
+
+ /**
+ * Executes the `core/term-delete` ability.
+ *
+ * The term is looked up first, then the capability to delete it is checked. The outcome
+ * is confirmed against the stored term afterwards.
+ *
+ * `permanent` has to be true, since terms have no Trash and the delete cannot be undone.
+ * False is refused.
+ *
+ * @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_term_delete( array $input ) {
+ $where = $input['where'] ?? array();
+ $term_id = (int) ( $where['id'] ?? 0 );
+ $taxonomy_object = $this->get_exposed_taxonomy( $where['taxonomy'] ?? null );
+ if ( ! $taxonomy_object || ! $this->get_term_in_taxonomy( $term_id, $taxonomy_object->name ) ) {
+ return $this->term_not_found_error();
+ }
+
+ $taxonomy = $taxonomy_object->name;
+
+ // Checked again after the permission callback, whose result a filter can change.
+ if ( ! $this->can_delete_term( $term_id, $taxonomy_object ) ) {
+ return new WP_Error(
+ 'term_cannot_delete',
+ __( 'Sorry, you are not allowed to delete this term.' ),
+ array( 'status' => 403 )
+ );
+ }
+
+ // The caller states that the delete is final, as terms cannot be trashed.
+ if ( empty( $input['permanent'] ) ) {
+ return new WP_Error(
+ 'term_trash_not_supported',
+ __( 'Terms do not support trashing. Set `permanent` to true to delete the term.' ),
+ array( 'status' => 501 )
+ );
+ }
+
+ if ( $this->is_default_term( $term_id, $taxonomy_object ) ) {
+ return new WP_Error(
+ 'term_is_default',
+ 'category' === $taxonomy
+ ? __( 'The default category cannot be deleted.' )
+ : __( 'The default term cannot be deleted.' ),
+ array( 'status' => 400 )
+ );
+ }
+
+ wp_delete_term( $term_id, $taxonomy );
+
+ // The return value of the delete is not trusted: the term is looked up again.
+ if ( $this->get_term_in_taxonomy( $term_id, $taxonomy ) ) {
+ return new WP_Error(
+ 'term_delete_failed',
+ __( 'The term cannot be deleted.' ),
+ array( 'status' => 500 )
+ );
+ }
+
+ return array( 'outcome' => 'deleted' );
+ }
+
+ /**
+ * Checks the `data` attributes of a create or update call.
+ *
+ * The first rule that fails is returned and nothing is written.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param WP_Taxonomy $taxonomy_object The taxonomy of the term being written.
+ * @param int|null $term_id The ID of the term on update, or null on create.
+ * @return WP_Error|null The error for the first attribute that cannot be applied, or null.
+ */
+ private function check_attributes( array $data, WP_Taxonomy $taxonomy_object, ?int $term_id ): ?WP_Error {
+ if ( array_key_exists( 'parent', $data ) ) {
+ if ( ! $taxonomy_object->hierarchical ) {
+ return $this->invalid_attribute_error( 'parent', __( 'Cannot set parent term, taxonomy is not hierarchical.' ) );
+ }
+
+ // Every failure gives the same error, so it never tells whether a term ID exists.
+ $parent_id = (int) $data['parent'];
+ if ( 0 !== $parent_id && ! $this->get_term_in_taxonomy( $parent_id, $taxonomy_object->name ) ) {
+ return $this->invalid_attribute_error( 'parent', __( 'Parent term does not exist.' ) );
+ }
+
+ /*
+ * Intentionally strict: a parent that would make a loop is an error. The save would
+ * store no parent instead, or change the parents of other terms to break the loop.
+ */
+ if (
+ null !== $term_id && $parent_id > 0
+ && ( $term_id === $parent_id || wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent_id, array( $taxonomy_object->name ) ) )
+ ) {
+ return $this->invalid_attribute_error( 'parent', __( 'The parent term cannot be the term itself or one of its descendants.' ) );
+ }
+ }
+
+ /*
+ * Intentionally strict: a slug that sanitizes to nothing or to "0" is an error. The save
+ * would read it as no slug and generate one from the name instead.
+ */
+ if ( array_key_exists( 'slug', $data ) && empty( sanitize_title( (string) $data['slug'] ) ) ) {
+ return $this->invalid_attribute_error( 'slug', __( 'The slug must contain characters that are valid in a slug.' ) );
+ }
+
+ return null;
+ }
+
+ /**
+ * Builds the arguments passed to the save from the allowed `data` attributes.
+ *
+ * Only the given attributes that were sent reach the save, each copied by name.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The `data` input.
+ * @param list $attributes The attributes the save accepts.
+ * @return array The unslashed save arguments.
+ */
+ private function get_save_args( array $data, array $attributes ): array {
+ $args = array();
+ foreach ( $attributes as $attribute ) {
+ if ( array_key_exists( $attribute, $data ) ) {
+ $args[ $attribute ] = $data[ $attribute ];
+ }
+ }
+
+ return $args;
+ }
+
+ /**
+ * Turns the result of a term save into the ability output.
+ *
+ * @since 7.3.0
+ *
+ * @param array|WP_Error $result The result of wp_insert_term() or wp_update_term().
+ * @param string $taxonomy The taxonomy name.
+ * @param list $fields The requested fields.
+ * @return array|WP_Error The saved term, or a WP_Error on failure.
+ */
+ private function prepare_save_result( $result, string $taxonomy, array $fields ) {
+ if ( is_wp_error( $result ) ) {
+ return $this->prepare_save_error( $result );
+ }
+
+ // The save may give the term a new ID, so the term is read back with the returned one.
+ $term = $this->get_term_in_taxonomy( (int) ( $result['term_id'] ?? 0 ), $taxonomy );
+ if ( ! $term ) {
+ return $this->term_not_found_error();
+ }
+
+ return $this->format_term( $term, $fields );
+ }
+
+ /**
+ * Builds the ability error for an error returned by a term save.
+ *
+ * The error keeps the code and message of the save error, and its data only says what
+ * the caller needs: the status, the input path of the attribute at fault, and for an
+ * existing term its ID. Nothing else of the save error, such as a database error, is
+ * passed on.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_Error $error The error returned by wp_insert_term() or wp_update_term().
+ * @return WP_Error The ability error.
+ */
+ private function prepare_save_error( WP_Error $error ): WP_Error {
+ $code = $error->get_error_code();
+ $message = $error->get_error_message( $code );
+
+ switch ( $code ) {
+ case 'term_exists':
+ $data = array(
+ 'status' => 400,
+ 'term_id' => (int) $error->get_error_data( $code ),
+ );
+ break;
+ case 'empty_term_name':
+ case 'invalid_term_name':
+ $data = array(
+ 'status' => 400,
+ 'params' => array( 'data[name]' => $message ),
+ );
+ break;
+ case 'duplicate_term_slug':
+ $data = array(
+ 'status' => 400,
+ 'params' => array( 'data[slug]' => $message ),
+ );
+ break;
+ case 'db_insert_error':
+ case 'db_update_error':
+ $data = array( 'status' => 500 );
+ break;
+ default:
+ $data = array( 'status' => 400 );
+ }
+
+ return new WP_Error( $code, $message, $data );
+ }
+
+ /**
+ * Returns the requested fields, or the default fields when none are given.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The ability input.
+ * @return list The requested fields.
+ */
+ private function normalize_fields( array $input ): array {
+ $fields = $input['fields'] ?? array();
+
+ return empty( $fields ) ? self::DEFAULT_FIELDS : $fields;
+ }
+
+ /**
+ * Formats a term into the ability output shape.
+ *
+ * Shared by all term abilities. The `id` is always included, whether or not it was
+ * requested, and the other fields follow in a fixed order. `parent` is only returned
+ * for hierarchical taxonomies.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_Term $term The term.
+ * @param list $fields The requested fields.
+ * @return array The formatted term.
+ */
+ private function format_term( WP_Term $term, array $fields ): array {
+ $data = array( 'id' => (int) $term->term_id );
+
+ if ( in_array( 'taxonomy', $fields, true ) ) {
+ $data['taxonomy'] = $term->taxonomy;
+ }
+ if ( in_array( 'name', $fields, true ) ) {
+ $data['name'] = $term->name;
+ }
+ if ( in_array( 'slug', $fields, true ) ) {
+ $data['slug'] = $term->slug;
+ }
+ if ( in_array( 'description', $fields, true ) ) {
+ $data['description'] = $term->description;
+ }
+ if ( in_array( 'parent', $fields, true ) && is_taxonomy_hierarchical( $term->taxonomy ) ) {
+ $data['parent'] = (int) $term->parent;
+ }
+ if ( in_array( 'count', $fields, true ) ) {
+ $data['count'] = (int) $term->count;
+ }
+ if ( in_array( 'link', $fields, true ) ) {
+ $link = get_term_link( $term );
+ $data['link'] = is_string( $link ) ? $link : '';
+ }
+
+ return $data;
+ }
+
+ /**
+ * Returns the term field definitions, keyed by field name in output order.
+ *
+ * The output schema uses the definitions directly, and the `fields` input lists their names.
+ *
+ * @since 7.3.0
+ *
+ * @return array Term field definitions.
+ */
+ private function get_term_properties(): array {
+ return array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'The term ID.' ),
+ ),
+ 'taxonomy' => array(
+ 'type' => 'string',
+ 'description' => __( 'The taxonomy of the term.' ),
+ ),
+ 'name' => array(
+ 'type' => 'string',
+ 'description' => __( 'The term name, as stored. A name is plain text: when a term is saved, HTML tags are removed from its name and special characters are encoded as HTML entities, so `Q&A` is returned as `Q&A`.' ),
+ ),
+ 'slug' => array(
+ 'type' => 'string',
+ 'description' => __( 'The term slug.' ),
+ ),
+ 'description' => array(
+ 'type' => 'string',
+ 'description' => __( 'The term description, as stored.' ),
+ ),
+ 'parent' => array(
+ 'type' => 'integer',
+ 'description' => __( 'The parent term ID, or 0 for a top-level term. Present for hierarchical taxonomies.' ),
+ ),
+ 'count' => array(
+ 'type' => 'integer',
+ 'description' => __( 'The number of objects the term is assigned to, as Core counts them.' ),
+ ),
+ 'link' => array(
+ 'type' => 'string',
+ 'format' => 'uri',
+ 'description' => __( 'The URL of the term archive. Empty when the term has none.' ),
+ ),
+ );
+ }
+
+ /**
+ * Builds the schema of the `fields` input, shared by all term abilities that return terms.
+ *
+ * @since 7.3.0
+ *
+ * @return array The `fields` JSON Schema.
+ */
+ private function get_fields_input_schema(): array {
+ return array(
+ 'type' => 'array',
+ 'uniqueItems' => true,
+ 'items' => array(
+ 'type' => 'string',
+ 'enum' => array_keys( $this->get_term_properties() ),
+ ),
+ 'description' => sprintf(
+ /* translators: %s: Comma-separated list of field names. */
+ __( 'Limit each returned term to these fields. The `id` is always included. If omitted or empty, the default fields are returned: %s. `parent` is left out for terms of a taxonomy that is not hierarchical.' ),
+ '`' . implode( '`, `', self::DEFAULT_FIELDS ) . '`'
+ ),
+ );
+ }
+
+ /**
+ * Builds the `taxonomy` schema, shared by all term abilities.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ * @param string $description The description of the property.
+ * @return array The `taxonomy` JSON Schema.
+ */
+ private function get_taxonomy_schema( array $taxonomies, string $description ): array {
+ return array(
+ 'type' => 'string',
+ 'enum' => $taxonomies,
+ 'description' => $description,
+ );
+ }
+
+ /**
+ * Builds the input schema for the `core/terms-query` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ * @return array The input JSON Schema.
+ */
+ private function get_terms_query_input_schema( array $taxonomies ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where' ),
+ 'properties' => array(
+ 'where' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'taxonomy' ),
+ 'properties' => array(
+ 'taxonomy' => $this->get_taxonomy_schema( $taxonomies, __( 'Taxonomy to query for terms.' ) ),
+ 'ids' => array(
+ 'type' => 'array',
+ 'uniqueItems' => true,
+ 'minItems' => 1,
+ 'maxItems' => self::MAX_PER_PAGE,
+ 'items' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ 'description' => __( 'Limit the query to these term IDs. The order of the IDs does not affect the order of the results. If `pagination.per_page` is omitted, every matching term is returned on the first page.' ),
+ ),
+ 'slugs' => array(
+ 'type' => 'array',
+ 'uniqueItems' => true,
+ 'minItems' => 1,
+ 'maxItems' => self::MAX_PER_PAGE,
+ 'items' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ ),
+ 'description' => __( 'Limit the query to terms with these slugs. Each slug is sanitized as a term slug is, so `Hello-World` matches `hello-world`. The order of the slugs does not affect the order of the results. If `pagination.per_page` is omitted, every matching term is returned on the first page.' ),
+ ),
+ 'parent' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ 'description' => __( 'Filter by parent term ID. Only supported for hierarchical taxonomies. Use 0 for top-level terms.' ),
+ ),
+ 'post' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ 'description' => __( 'Limit the query to the terms assigned to this post. The post must be readable, and its post type must be exposed to abilities and use the taxonomy.' ),
+ ),
+ 'hide_empty' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether to leave out terms that are not assigned to any post. Defaults to false. Cannot be combined with `post`.' ),
+ ),
+ ),
+ 'description' => __( 'Selects the terms to return: the terms of a `taxonomy`, filtered by any of `ids`, `slugs`, `parent`, `post`, and `hide_empty`. A term must match every given filter.' ),
+ ),
+ 'fields' => $this->get_fields_input_schema(),
+ 'pagination' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'properties' => array(
+ 'page' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ 'description' => __( 'Page of results to return. Defaults to 1. Requesting a page beyond the last one is an error, unless no term matches the query: then any page returns empty `items` and zero totals.' ),
+ ),
+ 'per_page' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ 'maximum' => self::MAX_PER_PAGE,
+ 'description' => sprintf(
+ /* translators: 1: Default number of terms per page, 2: Maximum number of terms per page. */
+ __( 'Maximum number of terms to return per page. Defaults to %1$d, or to %2$d when `where.ids` or `where.slugs` is given.' ),
+ self::DEFAULT_PER_PAGE,
+ self::MAX_PER_PAGE
+ ),
+ ),
+ ),
+ 'description' => __( 'Selects the page of results to return.' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Returns the `data` attributes shared by the create and update input schemas.
+ *
+ * @since 7.3.0
+ *
+ * @return array The attribute schemas, keyed by attribute name.
+ */
+ private function get_term_write_properties(): array {
+ return array(
+ 'name' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'maxLength' => 200,
+ 'description' => __( 'The term name, as plain text. When it is saved, HTML tags are removed and special characters are encoded as HTML entities, so `Q&A tips` is stored and returned as `Q&A tips`.' ),
+ ),
+ 'slug' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'description' => __( 'The term slug. It is sanitized as a term slug is, and made unique in the taxonomy on create and when the parent changes.' ),
+ ),
+ 'description' => array(
+ 'type' => 'string',
+ 'description' => __( 'The term description.' ),
+ ),
+ 'parent' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ 'description' => __( 'The parent term ID: a term of the same taxonomy, or 0 for a top-level term. Only supported for hierarchical taxonomies.' ),
+ ),
+ );
+ }
+
+ /**
+ * Builds the `where` schema that names one term, shared by the update and delete abilities.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ * @param string $description The description of `where`.
+ * @return array The `where` JSON Schema.
+ */
+ private function get_where_term_schema( array $taxonomies, string $description ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'taxonomy', 'id' ),
+ 'properties' => array(
+ 'taxonomy' => $this->get_taxonomy_schema( $taxonomies, __( 'The taxonomy of the term.' ) ),
+ 'id' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ 'description' => __( 'The term ID.' ),
+ ),
+ ),
+ 'description' => $description,
+ );
+ }
+
+ /**
+ * Builds the input schema for the `core/term-create` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ * @return array The input JSON Schema.
+ */
+ private function get_term_create_input_schema( array $taxonomies ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'data' ),
+ 'properties' => array(
+ 'data' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'taxonomy', 'name' ),
+ 'properties' => array_merge(
+ array(
+ 'taxonomy' => $this->get_taxonomy_schema( $taxonomies, __( 'The taxonomy of the term to create.' ) ),
+ ),
+ $this->get_term_write_properties()
+ ),
+ 'description' => __( 'The term to create.' ),
+ ),
+ 'fields' => $this->get_fields_input_schema(),
+ ),
+ );
+ }
+
+ /**
+ * Builds the input schema for the `core/term-update` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ * @return array The input JSON Schema.
+ */
+ private function get_term_update_input_schema( array $taxonomies ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where', 'data' ),
+ 'properties' => array(
+ 'where' => $this->get_where_term_schema( $taxonomies, __( 'Selects the term to update, by its taxonomy and ID.' ) ),
+ 'data' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'minProperties' => 1,
+ 'properties' => $this->get_term_write_properties(),
+ '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/term-delete` ability.
+ *
+ * @since 7.3.0
+ *
+ * @param list $taxonomies Exposed taxonomy names.
+ * @return array The input JSON Schema.
+ */
+ private function get_term_delete_input_schema( array $taxonomies ): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where', 'permanent' ),
+ 'properties' => array(
+ 'where' => $this->get_where_term_schema( $taxonomies, __( 'Selects the term to delete, by its taxonomy and ID.' ) ),
+ 'permanent' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether the term is deleted permanently. Must be true, since terms have no Trash and the delete cannot be undone.' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Builds the output schema of a single term, shared by all term abilities.
+ *
+ * Only `id` is required, because it is always returned. The other fields are optional
+ * because the `fields` input lets the caller request any subset.
+ *
+ * @since 7.3.0
+ *
+ * @return array The term JSON Schema.
+ */
+ private function get_term_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'id' ),
+ 'properties' => $this->get_term_properties(),
+ );
+ }
+
+ /**
+ * Builds the output schema for the `core/terms-query` ability.
+ *
+ * @since 7.3.0
+ *
+ * @return array The output JSON Schema.
+ */
+ private function get_terms_query_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'items', 'pagination' ),
+ 'properties' => array(
+ 'items' => array(
+ 'type' => 'array',
+ 'description' => __( 'The terms on the requested page, ordered by name unless the taxonomy is registered with another order.' ),
+ 'items' => $this->get_term_output_schema(),
+ ),
+ 'pagination' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'total', 'total_pages' ),
+ 'properties' => array(
+ 'total' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Total number of terms matching the query, across all pages.' ),
+ ),
+ 'total_pages' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Total number of result pages.' ),
+ ),
+ ),
+ 'description' => __( 'The totals of the request, across all pages.' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Builds the output schema for the `core/term-delete` ability.
+ *
+ * @since 7.3.0
+ *
+ * @return array The output JSON Schema.
+ */
+ private function get_term_delete_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'outcome' ),
+ 'properties' => array(
+ 'outcome' => array(
+ 'type' => 'string',
+ 'description' => __( 'What happened to the term: `deleted` when it was deleted permanently.' ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Builds the error for a taxonomy that is not exposed to abilities.
+ *
+ * @since 7.3.0
+ *
+ * @return WP_Error The taxonomy not found error.
+ */
+ private function taxonomy_not_found_error(): WP_Error {
+ return new WP_Error(
+ 'terms_taxonomy_not_found',
+ __( 'The requested taxonomy was not found.' ),
+ array( 'status' => 404 )
+ );
+ }
+
+ /**
+ * Builds the error for a term that cannot be found.
+ *
+ * Returned alike for a missing term, a term of another taxonomy, and a taxonomy that is
+ * not exposed to abilities, so it never tells which one applies.
+ *
+ * @since 7.3.0
+ *
+ * @return WP_Error The term not found error.
+ */
+ private function term_not_found_error(): WP_Error {
+ return new WP_Error(
+ 'term_not_found',
+ __( 'The requested term was not found.' ),
+ array( 'status' => 404 )
+ );
+ }
+
+ /**
+ * Builds the error for a filter that cannot be honored.
+ *
+ * The error data maps the filter's input path to the message under `params`, so callers
+ * can tell which filter failed without parsing the translated message.
+ *
+ * @since 7.3.0
+ *
+ * @param string $param The filter's input path, such as `where[parent]`.
+ * @param string $message The error message.
+ * @return WP_Error The invalid filter error.
+ */
+ private function invalid_filter_error( string $param, string $message ): WP_Error {
+ return new WP_Error(
+ 'terms_invalid_filter',
+ $message,
+ array(
+ 'status' => 400,
+ 'params' => array( $param => $message ),
+ )
+ );
+ }
+
+ /**
+ * Builds the error for a `data` attribute that cannot be applied.
+ *
+ * The error data maps the attribute's input path, such as `data[parent]`, to the message
+ * under `params`.
+ *
+ * @since 7.3.0
+ *
+ * @param string $attribute The attribute name, such as `parent`.
+ * @param string $message The error message.
+ * @return WP_Error The invalid attribute error.
+ */
+ private function invalid_attribute_error( string $attribute, string $message ): WP_Error {
+ return new WP_Error(
+ 'term_invalid_attribute',
+ $message,
+ array(
+ 'status' => 400,
+ 'params' => array( "data[{$attribute}]" => $message ),
+ )
+ );
+ }
+}
diff --git a/src/wp-includes/class-wp-post-type.php b/src/wp-includes/class-wp-post-type.php
index 0767deeb34162..95f86f9a6b4b2 100644
--- a/src/wp-includes/class-wp-post-type.php
+++ b/src/wp-includes/class-wp-post-type.php
@@ -389,8 +389,8 @@ final class WP_Post_Type {
/**
* Whether this post type should be exposed through the Abilities API.
*
- * Default false. If true, the core content abilities can access the post type's
- * posts, subject to the current user's capabilities.
+ * Default false. If true, the core content abilities can query, create, update, and
+ * delete the post type's posts, subject to the current user's capabilities.
*
* @since 7.2.0
* @var bool $show_in_abilities
diff --git a/src/wp-includes/class-wp-taxonomy.php b/src/wp-includes/class-wp-taxonomy.php
index d563a2c4386da..8f8a7a93e69df 100644
--- a/src/wp-includes/class-wp-taxonomy.php
+++ b/src/wp-includes/class-wp-taxonomy.php
@@ -209,6 +209,17 @@ final class WP_Taxonomy {
*/
public $show_in_rest;
+ /**
+ * Whether this taxonomy should be exposed through the Abilities API.
+ *
+ * Default false. If true, the core term abilities can access the taxonomy's
+ * terms, subject to the current user's capabilities.
+ *
+ * @since 7.3.0
+ * @var bool $show_in_abilities
+ */
+ public $show_in_abilities = false;
+
/**
* The base path for this taxonomy's REST API endpoints.
*
@@ -364,6 +375,7 @@ public function set_props( $object_type, $args ) {
'query_var' => $this->name,
'update_count_callback' => '',
'show_in_rest' => false,
+ 'show_in_abilities' => false,
'rest_base' => false,
'rest_namespace' => false,
'rest_controller_class' => false,
@@ -426,6 +438,9 @@ public function set_props( $object_type, $args ) {
$args['rest_namespace'] = 'wp/v2';
}
+ // Only `true` exposes the taxonomy, so other values, such as arrays, can be given a meaning later.
+ $args['show_in_abilities'] = true === $args['show_in_abilities'];
+
$default_caps = array(
'manage_terms' => 'manage_categories',
'edit_terms' => 'manage_categories',
diff --git a/src/wp-includes/post.php b/src/wp-includes/post.php
index 6d42c97836dea..8e0e6e7fa6409 100644
--- a/src/wp-includes/post.php
+++ b/src/wp-includes/post.php
@@ -1706,6 +1706,8 @@ function get_post_types( $args = array(), $output = 'names', $operator = 'and' )
* @since 5.3.0 The `supports` argument will now accept an array of arguments for a feature.
* @since 5.9.0 The `rest_namespace` argument was added.
* @since 7.2.0 The `show_in_abilities` argument was added.
+ * @since 7.3.0 Posts of post types exposed with the `show_in_abilities` argument can be created,
+ * updated, and deleted through the Abilities API.
*
* @global array $wp_post_types List of post types.
*
@@ -1755,8 +1757,8 @@ function get_post_types( $args = array(), $output = 'names', $operator = 'and' )
* @type bool $show_in_rest Whether to include the post type in the REST API. Set this to true
* for the post type to be available in the block editor.
* @type bool $show_in_abilities Whether to expose this post type through the Abilities API, so the
- * core content abilities can access its posts, subject to the current
- * user's capabilities. Default false.
+ * core content abilities can query, create, update, and delete its
+ * posts, subject to the current user's capabilities. Default false.
* @type string $rest_base To change the base URL of REST API route. Default is $post_type.
* @type string $rest_namespace To change the namespace URL of REST API route. Default is wp/v2.
* @type string $rest_controller_class REST API controller class name. Default is 'WP_REST_Posts_Controller'.
diff --git a/src/wp-includes/taxonomy.php b/src/wp-includes/taxonomy.php
index 06d1d3581dd00..ded2b8d884678 100644
--- a/src/wp-includes/taxonomy.php
+++ b/src/wp-includes/taxonomy.php
@@ -78,6 +78,7 @@ function create_initial_taxonomies() {
'assign_terms' => 'assign_categories',
),
'show_in_rest' => true,
+ 'show_in_abilities' => true,
'rest_base' => 'categories',
'rest_controller_class' => 'WP_REST_Terms_Controller',
)
@@ -101,6 +102,7 @@ function create_initial_taxonomies() {
'assign_terms' => 'assign_post_tags',
),
'show_in_rest' => true,
+ 'show_in_abilities' => true,
'rest_base' => 'tags',
'rest_controller_class' => 'WP_REST_Terms_Controller',
)
@@ -434,6 +436,7 @@ function is_taxonomy_hierarchical( $taxonomy ) {
* @since 5.4.0 Added the registered taxonomy object as a return value.
* @since 5.5.0 Introduced `default_term` argument.
* @since 5.9.0 Introduced `rest_namespace` argument.
+ * @since 7.3.0 The `show_in_abilities` argument was added.
*
* @global WP_Taxonomy[] $wp_taxonomies Registered taxonomies.
*
@@ -466,6 +469,9 @@ function is_taxonomy_hierarchical( $taxonomy ) {
* set, the default is inherited from `$public` (default true).
* @type bool $show_in_rest Whether to include the taxonomy in the REST API. Set this to true
* for the taxonomy to be available in the block editor.
+ * @type bool $show_in_abilities Whether to expose this taxonomy through the Abilities API, so the
+ * core term abilities can access its terms, subject to the current
+ * user's capabilities. Default false.
* @type string $rest_base To change the base url of REST API route. Default is $taxonomy.
* @type string $rest_namespace To change the namespace URL of REST API route. Default is wp/v2.
* @type string $rest_controller_class REST API Controller class name. Default is 'WP_REST_Terms_Controller'.
diff --git a/tests/phpunit/tests/abilities-api/testcase-content-ability.php b/tests/phpunit/tests/abilities-api/testcase-content-ability.php
new file mode 100644
index 0000000000000..603b45cdf22f7
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/testcase-content-ability.php
@@ -0,0 +1,80 @@
+
+ */
+ public const CONTENT_ABILITIES = array( 'core/content-query', 'core/content-create', 'core/content-update', 'core/content-delete' );
+
+ /**
+ * 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 and taxonomies.
+ *
+ * @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' );
+ }
+
+ /*
+ * Keep these resets even though the parent set_up() also resets the post types and
+ * taxonomies. A test may turn off `show_in_abilities` on `post` and `page`, or on
+ * `category` and `post_tag`, and the next class's wpSetUpBeforeClass() runs before the
+ * next set_up(). A class that registers the core abilities there, such as
+ * Tests_REST_API_WpRestAbilitiesContentController, would then register no content
+ * ability, or abilities without `terms`, and its tests would fail.
+ */
+ $this->reset_post_types();
+ $this->reset_taxonomies();
+
+ parent::tear_down();
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/testcase-content-existing-post-ability.php b/tests/phpunit/tests/abilities-api/testcase-content-existing-post-ability.php
new file mode 100644
index 0000000000000..d4172c4537371
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/testcase-content-existing-post-ability.php
@@ -0,0 +1,583 @@
+
+ */
+ protected const OTHER_INPUT = array();
+
+ /**
+ * 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' );
+
+ /**
+ * Creates the users and posts shared by the tests that write an existing post: a user per
+ * role and an `other` editor, one post per owner and matrix status, the posts that
+ * data_posts_that_are_not_posts() names, and the pages that data_special_pages() names.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_UnitTest_Factory $factory The unit test factory.
+ */
+ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void {
+ foreach ( self::ROLES as $role ) {
+ self::$user_ids[ $role ] = $factory->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_title' => "Matrix {$owner} {$status}",
+ 'post_date_gmt' => 'future' === $stored_status ? str_replace( 'T', ' ', self::FUTURE_GMT ) : '',
+ )
+ );
+ 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',
+ )
+ );
+
+ // A plain page, and the pages that set_special_pages() makes special.
+ 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'],
+ )
+ );
+
+ self::$post_ids['autosave'] = (int) _wp_put_post_revision( get_post( self::create_revision_fixture( $factory ) ), 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 names a post with the given `where`.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $where The `where`.
+ * @return array The input.
+ */
+ protected function build_input( $where ): array {
+ return array_merge( array( 'where' => $where ), static::OTHER_INPUT );
+ }
+
+ /**
+ * Builds the `where` that names a post by its type and ID.
+ *
+ * @since 7.3.0
+ *
+ * @param int $post_id The post ID.
+ * @param string|null $type Optional. The post type, or null for the type of the post. Default null.
+ * @return array{type: string|false, id: int} The `where`.
+ */
+ protected function build_where( int $post_id, ?string $type = null ): array {
+ return array(
+ 'type' => $type ?? get_post_type( $post_id ),
+ 'id' => $post_id,
+ );
+ }
+
+ /**
+ * Builds the input that names a post by its type and ID.
+ *
+ * @since 7.3.0
+ *
+ * @param int $post_id The post ID.
+ * @param string|null $type Optional. The post type, or null for the type of the post. Default null.
+ * @return array The input.
+ */
+ protected function build_post_input( int $post_id, ?string $type = null ): array {
+ return $this->build_input( $this->build_where( $post_id, $type ) );
+ }
+
+ /**
+ * Returns whether each role may edit and delete each matrix post.
+ *
+ * @return array The cases.
+ */
+ public static function data_capability_matrix(): array {
+ $denied = array(
+ 'author:other' => true,
+ 'contributor:other' => true,
+ 'subscriber:own' => true,
+ 'subscriber:other' => true,
+ );
+
+ // A contributor may only write their own posts that were never published.
+ $denied_to_own_contributor = array( 'publish', 'future', 'trash_publish' );
+
+ $cases = array();
+ foreach ( self::ROLES as $role ) {
+ foreach ( array( 'own', 'other' ) as $owner ) {
+ foreach ( self::MATRIX_STATUSES as $status ) {
+ $allowed = ! isset( $denied[ "{$role}:{$owner}" ] )
+ && ! ( 'contributor' === $role && 'own' === $owner && in_array( $status, $denied_to_own_contributor, true ) );
+
+ $cases[ "{$role}, {$owner}, {$status}" ] = array( $role, 'own' === $owner ? $role : 'other', $status, $allowed );
+ }
+ }
+ }
+
+ return $cases;
+ }
+
+ /**
+ * Returns inputs for which the permission callback returns false, even for an administrator.
+ *
+ * Each input but the missing one holds the OTHER_INPUT of the test class.
+ *
+ * @return array The inputs.
+ */
+ public static function data_inputs_refused_by_the_permission_callback(): array {
+ $cases = array(
+ 'no input' => array( null ),
+ 'no where' => array( static::OTHER_INPUT ),
+ );
+
+ $wheres = array(
+ 'where that is a string' => 'post',
+ 'type that is a list' => array(
+ 'type' => array( 'post' ),
+ 'id' => 1,
+ ),
+ 'unexposed type' => array(
+ 'type' => 'attachment',
+ 'id' => 1,
+ ),
+ );
+ foreach ( $wheres as $label => $where ) {
+ $cases[ $label ] = array( array_merge( array( 'where' => $where ), static::OTHER_INPUT ) );
+ }
+
+ return $cases;
+ }
+
+ /**
+ * 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' ),
+ );
+ }
+
+ /**
+ * Makes the shared pages the front page, the posts page, and the privacy policy page of the site.
+ *
+ * @since 7.3.0
+ */
+ protected 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'] );
+ }
+
+ /**
+ * 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 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( '' ),
+ );
+ }
+
+ /**
+ * 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->assert_refused( $this->run_ability_that_writes_nothing( $this->build_post_input( $post_id ), $post_id ), 'A logged-out user' );
+ }
+
+ /**
+ * The permission callback returns false for a post the user cannot write, 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_write( 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( $this->build_input( $where ) ), 'The permission callback should return false.' );
+ }
+
+ /**
+ * The permission callback returns true for a post the user can write.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_callback_returns_true_for_a_post_the_user_can_write(): void {
+ $this->login_as( 'author' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertTrue( $permission( $this->build_post_input( self::$post_ids['author:draft'] ) ), '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 write 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 = $this->build_post_input( REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, 'post' );
+
+ $this->assertTrue( $permission( $input ), 'The permission callback should return true.' );
+ $this->assert_not_found( $this->run_ability( $input ), 'A missing post' );
+ }
+
+ /**
+ * A permission result that a filter turns into a grant is the final permission decision:
+ * the call runs without a second capability check on the post.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_result_granted_by_a_filter_is_final(): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ $this->login_as( 'contributor' );
+
+ $input = $this->build_post_input( $post_id );
+ $this->assert_refused( $this->run_ability( $input ), 'Precondition: a call without the filter' );
+
+ add_filter( 'wp_ability_permission_result', '__return_true' );
+
+ $before = $this->snapshot( $post_id );
+
+ $this->assertIsArray( $this->run_ability( $input ), 'A call granted by a filter should succeed.' );
+ $this->assertNotSame( $before, $this->snapshot( $post_id ), 'A call granted by a filter should write the post.' );
+ }
+
+ /**
+ * An ID that is not a whole number of at least 1 fails input validation, and called directly,
+ * it is the not-found error.
+ *
+ * @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_of_at_least_1_fails_input_validation( $id ): void {
+ $post_id = self::$post_ids['admin_post'];
+ $input = $this->build_input(
+ array(
+ 'type' => 'post',
+ 'id' => $id,
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+
+ $this->assert_not_found( $execute( $input ), 'A direct call with an ID that is not a whole number of at least 1' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'The direct call should write nothing.' );
+
+ $this->assert_invalid_input( $input, $post_id, 'An ID that is not a whole number of at least 1' );
+ }
+
+ /**
+ * Returns keys that are not part of the input, and where they are sent.
+ *
+ * @return array Where the key is sent, or
+ * null for the top level, the
+ * key, and the value.
+ */
+ abstract public static function data_keys_outside_the_allow_list(): array;
+
+ /**
+ * 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'];
+
+ $input = $this->build_post_input( $post_id );
+ if ( null === $location ) {
+ $input[ $key ] = $value;
+ } else {
+ $input[ $location ][ $key ] = $value;
+ }
+
+ $this->assert_invalid_input( $input, $post_id, 'A key outside the allow-list' );
+ }
+
+ /**
+ * 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 ] ?? REST_TESTS_IMPOSSIBLY_HIGH_NUMBER;
+
+ $this->login_as( 'administrator' );
+
+ $this->assert_not_found( $this->run_ability_that_writes_nothing( $this->build_post_input( $post_id, 'post' ), $post_id ), 'A post that is not a post' );
+ }
+
+ /**
+ * Called directly, a post of a type that is not exposed is not found.
+ *
+ * @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_unexposed', array( 'public' => true ) );
+ $post_id = self::factory()->post->create( array( 'post_type' => 'cw_unexposed' ) );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+
+ $this->assert_not_found( $execute( $this->build_post_input( $post_id ) ), '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 written.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_type_no_longer_exposed_cannot_be_written(): 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->build_post_input( $post_id );
+ $before = $this->snapshot( $post_id );
+
+ $this->assert_refused( $this->run_ability( $input ), 'A regular call for 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 malformed `where` values for a direct call, or null to send none.
+ *
+ * @return array|null}> The values.
+ */
+ public static function data_malformed_where_values(): array {
+ return array(
+ 'no where' => array( null ),
+ 'no type' => array( array( 'id' => 1 ) ),
+ 'no ID' => array( array( 'type' => 'post' ) ),
+ );
+ }
+
+ /**
+ * Called directly, a malformed `where` is the not-found error.
+ *
+ * @ticket 66706
+ * @dataProvider data_malformed_where_values
+ * @since 7.3.0
+ *
+ * @param array|null $where The `where`, or null to send none.
+ */
+ public function test_direct_call_with_a_malformed_where_is_not_found( ?array $where ): void {
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $input = $this->build_input( $where );
+ if ( null === $where ) {
+ unset( $input['where'] );
+ }
+
+ $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 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'];
+
+ $this->login_as( 'author' );
+ $own_before = $this->snapshot( $own_id );
+ $first = $this->run_ability( $this->build_post_input( $own_id ) );
+
+ $this->login_as( 'contributor' );
+ $second = $this->run_ability_that_writes_nothing( $this->build_post_input( $other_id ), $other_id, 'The second call should write nothing.' );
+
+ $this->assertIsArray( $first, 'The first call as the author should succeed.' );
+ $this->assertNotSame( $own_before, $this->snapshot( $own_id ), 'The first call should write the post.' );
+ $this->assert_refused( $second, 'The second call as a contributor' );
+ }
+}
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..b79f206966116
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/testcase-content-write-ability.php
@@ -0,0 +1,487 @@
+
+ */
+ protected const ANNOTATIONS = array();
+
+ /**
+ * The roles of the matrix tests.
+ *
+ * @since 7.3.0
+ *
+ * @var list
+ */
+ protected const ROLES = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
+
+ /**
+ * 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();
+ }
+
+ /**
+ * 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 ability under test with the given input.
+ *
+ * Registers the content abilities unless the test already did.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input.
+ * @return mixed The ability result.
+ */
+ protected function run_ability( $input ) {
+ $ability = static::ABILITY;
+
+ if ( ! wp_has_ability( $ability ) ) {
+ $this->register_abilities();
+ }
+ $this->assertTrue( wp_has_ability( $ability ), "The {$ability} ability should be registered." );
+
+ return wp_get_ability( $ability )->execute( $input );
+ }
+
+ /**
+ * Creates a published post with one revision, keeps the revision as the `revision` fixture,
+ * and returns the ID of the post.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_UnitTest_Factory $factory The unit test factory.
+ * @return int The ID of the post that has the revision.
+ */
+ protected static function create_revision_fixture( WP_UnitTest_Factory $factory ): int {
+ $post_id = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ 'post_content' => 'First version.',
+ )
+ );
+ wp_update_post(
+ array(
+ 'ID' => $post_id,
+ 'post_content' => 'Second version.',
+ )
+ );
+ self::$post_ids['revision'] = (int) array_key_first( wp_get_post_revisions( $post_id ) );
+
+ return $post_id;
+ }
+
+ /**
+ * 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 ] );
+ }
+
+ /**
+ * Registers custom statuses of every visibility, before the abilities are registered.
+ *
+ * @since 7.3.0
+ */
+ protected 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,
+ )
+ );
+ register_post_status(
+ 'cw_hidden',
+ array(
+ 'label' => 'Hidden',
+ 'protected' => 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.' );
+ $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.' );
+ }
+
+ /**
+ * 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.
+ */
+ public static 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;
+ }
+
+ /**
+ * Runs the ability and asserts that the call wrote nothing.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input.
+ * @param int|null $post_id Optional. The ID of the post that should be left as it was.
+ * Default null.
+ * @param string $message Optional. The assertion message. Default 'Nothing should be written.'.
+ * @return mixed The ability result.
+ */
+ protected function run_ability_that_writes_nothing( $input, ?int $post_id = null, string $message = 'Nothing should be written.' ) {
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $input );
+
+ $this->assertSame( $before, $this->snapshot( $post_id ), $message );
+
+ return $result;
+ }
+
+ /**
+ * 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.
+ * @param string|null $expected Optional. The expected message. Default null, which only
+ * requires a message.
+ */
+ protected function assert_invalid_attribute( $result, string $attribute, string $context, ?string $expected = null ): void {
+ $this->assert_error( $result, 'content_invalid_attribute', 400, $context );
+
+ $message = $result->get_error_message();
+ if ( null === $expected ) {
+ $this->assertNotSame( '', $message, "{$context}: the message should give the reason." );
+ } else {
+ $this->assertSame( $expected, $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 input validation rejects an input of an administrator and that nothing is
+ * written.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input.
+ * @param int|null $post_id The ID of the post that should be left as it was, or null when
+ * the call would create a post.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_invalid_input( $input, ?int $post_id, string $context ): void {
+ $this->login_as( 'administrator' );
+
+ $result = $this->run_ability_that_writes_nothing( $input, $post_id, "{$context}: nothing should be written." );
+
+ $this->assertWPError( $result, "{$context}: the call should fail." );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), "{$context}: the schema should reject the input." );
+ }
+
+ /**
+ * 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 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' ),
+ );
+ }
+
+ /**
+ * 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( static::ABILITY );
+
+ $this->assertInstanceOf( WP_Ability::class, $ability, 'The ability should be registered.' );
+ $this->assertSame( static::LABEL, $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.' );
+ $this->assertSameSetsWithIndex( static::ANNOTATIONS, $ability->get_meta_item( 'annotations', array() ), 'The ability should have its annotations.' );
+ }
+
+ /**
+ * 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();
+
+ $ability = static::ABILITY;
+
+ $this->assertFalse( wp_has_ability( $ability ), "The {$ability} ability should not be registered without an exposed post type." );
+ }
+
+ /**
+ * Returns inputs for which the permission callback returns false, even for an administrator.
+ *
+ * @return array The inputs.
+ */
+ abstract public static function data_inputs_refused_by_the_permission_callback(): array;
+
+ /**
+ * The permission callback returns false for missing or malformed input, and for input that
+ * names a post type that is not exposed to abilities.
+ *
+ * @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_or_unexposed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should return false.' );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/testcase-terms-ability.php b/tests/phpunit/tests/abilities-api/testcase-terms-ability.php
new file mode 100644
index 0000000000000..bea24b6a3ef4d
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/testcase-terms-ability.php
@@ -0,0 +1,867 @@
+
+ */
+ protected const TERM_ABILITIES = array( 'core/terms-query', 'core/term-create', 'core/term-update', 'core/term-delete' );
+
+ /**
+ * An ID that no term or post has.
+ *
+ * @since 7.3.0
+ *
+ * @var int
+ */
+ protected const MISSING_ID = 987654321;
+
+ /**
+ * The keys of an item, in their order.
+ *
+ * @since 7.3.0
+ *
+ * @var list
+ */
+ protected const ITEM_KEYS = array( 'id', 'taxonomy', 'name', 'slug', 'description', 'parent', 'count', 'link' );
+
+ /**
+ * The keys of an item when no fields are requested.
+ *
+ * @since 7.3.0
+ *
+ * @var list
+ */
+ protected const DEFAULT_KEYS = array( 'id', 'taxonomy', 'name', 'slug', 'link' );
+
+ /**
+ * The schema of the `fields` input.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected const FIELDS_SCHEMA = array(
+ 'type' => 'array',
+ 'uniqueItems' => true,
+ 'items' => array(
+ 'type' => 'string',
+ 'enum' => array( 'id', 'taxonomy', 'name', 'slug', 'description', 'parent', 'count', 'link' ),
+ ),
+ );
+
+ /**
+ * The schema of an output item.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected const ITEM_SCHEMA = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'id' ),
+ 'properties' => array(
+ 'id' => array( 'type' => 'integer' ),
+ 'taxonomy' => array( 'type' => 'string' ),
+ 'name' => array( 'type' => 'string' ),
+ 'slug' => array( 'type' => 'string' ),
+ 'description' => array( 'type' => 'string' ),
+ 'parent' => array( 'type' => 'integer' ),
+ 'count' => array( 'type' => 'integer' ),
+ 'link' => array(
+ 'type' => 'string',
+ 'format' => 'uri',
+ ),
+ ),
+ );
+
+ /**
+ * Shared user IDs keyed by role or fixture name.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected static $user_ids = array();
+
+ /**
+ * Shared term IDs keyed by fixture name.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected static $term_ids = array();
+
+ /**
+ * Shared post IDs keyed by fixture name.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected static $post_ids = array();
+
+ /**
+ * Creates the shared users, terms and posts.
+ *
+ * Categories: News > Product updates > Roadmap, Empty and the default category.
+ * Tags: alpha and beta. The published post has News and beta, the private post alpha.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_UnitTest_Factory $factory The unit test factory.
+ */
+ public static function wpSetUpBeforeClass( $factory ): void {
+ self::$user_ids = array(
+ 'administrator' => $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' ) ),
+ 'no_role' => self::create_user_without_a_role( $factory ),
+ );
+
+ if ( is_multisite() ) {
+ self::$user_ids['super_admin'] = self::create_user_without_a_role( $factory );
+ grant_super_admin( self::$user_ids['super_admin'] );
+ }
+
+ $news = $factory->term->create(
+ array(
+ 'taxonomy' => 'category',
+ 'name' => 'News',
+ )
+ );
+ $product_updates = $factory->term->create(
+ array(
+ 'taxonomy' => 'category',
+ 'name' => 'Product updates',
+ 'parent' => $news,
+ )
+ );
+
+ self::$term_ids = array(
+ 'uncategorized' => (int) get_option( 'default_category' ),
+ 'news' => $news,
+ 'product_updates' => $product_updates,
+ 'roadmap' => $factory->term->create(
+ array(
+ 'taxonomy' => 'category',
+ 'name' => 'Roadmap',
+ 'parent' => $product_updates,
+ )
+ ),
+ 'empty' => $factory->term->create(
+ array(
+ 'taxonomy' => 'category',
+ 'name' => 'Empty',
+ )
+ ),
+ 'alpha' => $factory->term->create(
+ array(
+ 'taxonomy' => 'post_tag',
+ 'name' => 'alpha',
+ )
+ ),
+ 'beta' => $factory->term->create(
+ array(
+ 'taxonomy' => 'post_tag',
+ 'name' => 'beta',
+ )
+ ),
+ );
+
+ self::$post_ids = array(
+ 'published' => $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ 'post_category' => array( $news ),
+ 'tags_input' => array( 'beta' ),
+ )
+ ),
+ 'private' => $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'private',
+ 'tags_input' => array( 'alpha' ),
+ )
+ ),
+ 'page' => $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ ),
+ );
+ }
+
+ /**
+ * Revokes the super admin and forgets the shared fixtures, so a test class never reads
+ * the ones of another.
+ *
+ * @since 7.3.0
+ */
+ public static function wpTearDownAfterClass(): void {
+ if ( isset( self::$user_ids['super_admin'] ) ) {
+ revoke_super_admin( self::$user_ids['super_admin'] );
+ }
+
+ self::$user_ids = array();
+ self::$term_ids = array();
+ self::$post_ids = array();
+ }
+
+ /**
+ * Creates a user who is logged in but has no role on the site.
+ *
+ * On multisite the user is not a member of the site at all.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_UnitTest_Factory $factory The unit test factory.
+ * @return int The user ID.
+ */
+ private static function create_user_without_a_role( $factory ): int {
+ $user_id = $factory->user->create( array( 'role' => 'subscriber' ) );
+
+ if ( is_multisite() ) {
+ remove_user_from_blog( $user_id, get_current_blog_id() );
+ } else {
+ get_userdata( $user_id )->set_role( '' );
+ }
+
+ return $user_id;
+ }
+
+ /**
+ * Unregisters the term abilities and registers the content category.
+ *
+ * @since 7.3.0
+ */
+ public function set_up(): void {
+ parent::set_up();
+
+ foreach ( self::TERM_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 term abilities and the category, and resets the taxonomies.
+ *
+ * @since 7.3.0
+ */
+ public function tear_down(): void {
+ foreach ( self::TERM_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 `category` and `post_tag`, and the next
+ * class's wpSetUpBeforeClass() runs before the next set_up() resets the taxonomies.
+ */
+ $this->reset_taxonomies();
+
+ parent::tear_down();
+ }
+
+ /**
+ * Registers the term 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_Terms() )->register();
+ }
+
+ /**
+ * Registers the term 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 );
+ }
+
+ /**
+ * Runs the registered core/terms-query ability with the given input.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The ability input.
+ * @return mixed The ability result.
+ */
+ protected function run_query( array $input ) {
+ $this->assertTrue( wp_has_ability( 'core/terms-query' ), 'The core/terms-query ability should be registered.' );
+
+ return wp_get_ability( 'core/terms-query' )->execute( $input );
+ }
+
+ /**
+ * Lets every call of the ability under test past its permission callback.
+ *
+ * @since 7.3.0
+ */
+ protected function open_permission_gate(): void {
+ $ability = static::ABILITY;
+
+ add_filter(
+ 'wp_ability_permission_result',
+ static function ( $permission, string $name ) use ( $ability ) {
+ return $ability === $name ? true : $permission;
+ },
+ 10,
+ 2
+ );
+ }
+
+ /**
+ * Logs in as the shared user with the given role or fixture name, or logs out.
+ *
+ * @since 7.3.0
+ *
+ * @param string $role The role or fixture name, or `logged_out`.
+ */
+ protected function login_as( string $role ): void {
+ wp_set_current_user( 'logged_out' === $role ? 0 : self::$user_ids[ $role ] );
+ }
+
+ /**
+ * Grants or revokes a term capability on one term with a `map_meta_cap` filter.
+ *
+ * @since 7.3.0
+ *
+ * @param string $capability The term capability, such as `edit_term`.
+ * @param int $term_id The term ID.
+ * @param bool $grant True to grant the capability, false to revoke it.
+ */
+ protected function filter_term_capability( string $capability, int $term_id, bool $grant ): void {
+ add_filter(
+ 'map_meta_cap',
+ static function ( array $caps, string $cap, int $user_id, array $args ) use ( $capability, $term_id, $grant ): array {
+ if ( $capability === $cap && isset( $args[0] ) && $term_id === (int) $args[0] ) {
+ return $grant ? array( 'exist' ) : array( 'do_not_allow' );
+ }
+
+ return $caps;
+ },
+ 10,
+ 4
+ );
+ }
+
+ /**
+ * Registers a hierarchical taxonomy with its own capabilities, exposed to abilities.
+ *
+ * @since 7.3.0
+ *
+ * @param bool $hierarchical Optional. Whether the taxonomy is hierarchical. Default true.
+ */
+ protected function register_taxonomy_with_own_capabilities( bool $hierarchical = true ): void {
+ register_taxonomy(
+ 'tt_genre',
+ 'post',
+ array(
+ 'hierarchical' => $hierarchical,
+ 'show_in_abilities' => true,
+ 'capabilities' => array(
+ 'manage_terms' => 'manage_genres',
+ 'edit_terms' => 'edit_genres',
+ 'delete_terms' => 'delete_genres',
+ 'assign_terms' => 'assign_genres',
+ ),
+ )
+ );
+ }
+
+ /**
+ * Stores a term-taxonomy row that belongs to no term, so that the terms created afterwards
+ * have a term-taxonomy ID that differs from their term ID.
+ *
+ * @since 7.3.0
+ */
+ protected function offset_term_taxonomy_ids(): void {
+ global $wpdb;
+
+ $wpdb->insert(
+ $wpdb->term_taxonomy,
+ array(
+ 'term_id' => self::MISSING_ID,
+ 'taxonomy' => 'tt_stray',
+ 'description' => '',
+ 'parent' => 0,
+ 'count' => 0,
+ )
+ );
+ }
+
+ /**
+ * Asserts that the schema refuses input, then runs the ability under test with the same
+ * input let past validation by the `wp_ability_validate_input` filter, and asserts that
+ * nothing stored changed.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input, which the schema refuses.
+ * @param string $context What the call was, for the assertion messages.
+ * @return mixed The ability result.
+ */
+ protected function run_past_validation( $input, string $context ) {
+ $this->assert_invalid_input( $this->run_rejected( $input, "{$context} (validated)" ), "{$context} (validated)" );
+
+ $ability = static::ABILITY;
+ $skip = static function ( $is_valid, $input, string $name ) use ( $ability ) {
+ return $ability === $name ? true : $is_valid;
+ };
+
+ add_filter( 'wp_ability_validate_input', $skip, 10, 3 );
+ $result = $this->run_rejected( $input, $context );
+ remove_filter( 'wp_ability_validate_input', $skip, 10 );
+
+ return $result;
+ }
+
+ /**
+ * Takes a snapshot of the stored terms: the rows of the term tables, the default-term
+ * options of every taxonomy and the `terms` last-changed value.
+ *
+ * @since 7.3.0
+ *
+ * @return array The snapshot.
+ */
+ protected function snapshot(): array {
+ global $wpdb;
+
+ $options = array();
+ foreach ( get_taxonomies() as $taxonomy ) {
+ $options[ "default_{$taxonomy}" ] = get_option( "default_{$taxonomy}" );
+ $options[ "default_term_{$taxonomy}" ] = get_option( "default_term_{$taxonomy}" );
+ }
+
+ return array(
+ 'terms' => $wpdb->get_results( "SELECT * FROM {$wpdb->terms} ORDER BY term_id", ARRAY_A ),
+ 'term_taxonomy' => $wpdb->get_results( "SELECT * FROM {$wpdb->term_taxonomy} ORDER BY term_taxonomy_id", ARRAY_A ),
+ 'termmeta' => $wpdb->get_results( "SELECT * FROM {$wpdb->termmeta} ORDER BY meta_id", ARRAY_A ),
+ 'term_relationships' => $wpdb->get_results( "SELECT * FROM {$wpdb->term_relationships} ORDER BY object_id, term_taxonomy_id", ARRAY_A ),
+ 'options' => $options,
+ 'last_changed' => wp_cache_get_last_changed( 'terms' ),
+ );
+ }
+
+ /**
+ * Runs the ability under test with input that must be rejected, and asserts that nothing
+ * stored changed.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $input The ability input.
+ * @param string $context What the call was, for the assertion messages.
+ * @return mixed The ability result.
+ */
+ protected function run_rejected( $input, string $context ) {
+ $before = $this->snapshot();
+ $result = $this->run_ability( $input );
+
+ $this->assertSame( $before, $this->snapshot(), "{$context}: nothing stored should change." );
+
+ return $result;
+ }
+
+ /**
+ * Calls a callback that must reject the call, and asserts that nothing stored changed.
+ *
+ * @since 7.3.0
+ *
+ * @param callable $callback The callback, such as an execute callback.
+ * @param mixed $input The input passed to the callback.
+ * @param string $context What the call was, for the assertion messages.
+ * @return mixed The callback result.
+ */
+ protected function call_rejected( callable $callback, $input, string $context ) {
+ $before = $this->snapshot();
+ $result = $callback( $input );
+
+ $this->assertSame( $before, $this->snapshot(), "{$context}: nothing stored should change." );
+
+ return $result;
+ }
+
+ /**
+ * Returns a schema without its descriptions, with the keys of every object sorted and
+ * the values of `enum` and `required` sorted, so that two schemas compare by content.
+ *
+ * @since 7.3.0
+ *
+ * @param array $schema The schema.
+ * @return array The normalized schema.
+ */
+ protected function normalize_schema( array $schema ): array {
+ if ( isset( $schema['description'] ) && is_string( $schema['description'] ) ) {
+ unset( $schema['description'] );
+ }
+
+ foreach ( $schema as $key => $value ) {
+ if ( is_array( $value ) ) {
+ $schema[ $key ] = $this->normalize_schema( $value );
+ }
+ }
+
+ foreach ( array( 'enum', 'required' ) as $keyword ) {
+ if ( isset( $schema[ $keyword ] ) && is_array( $schema[ $keyword ] ) && array_is_list( $schema[ $keyword ] ) ) {
+ sort( $schema[ $keyword ] );
+ }
+ }
+
+ if ( ! array_is_list( $schema ) ) {
+ ksort( $schema );
+ }
+
+ return $schema;
+ }
+
+ /**
+ * Asserts that a schema is exactly the expected one, apart from descriptions and order.
+ *
+ * @since 7.3.0
+ *
+ * @param array $expected The expected schema.
+ * @param array $actual The schema of the ability.
+ * @param string $message The assertion message.
+ */
+ protected function assert_schema( array $expected, array $actual, string $message ): void {
+ $this->assertSame( $this->normalize_schema( $expected ), $this->normalize_schema( $actual ), $message );
+ }
+
+ /**
+ * Returns the schema of `where.taxonomy` and `data.taxonomy` with the default exposed taxonomies.
+ *
+ * @since 7.3.0
+ *
+ * @return array The schema.
+ */
+ protected function taxonomy_schema(): array {
+ return array(
+ 'type' => 'string',
+ 'enum' => array( 'category', 'post_tag' ),
+ );
+ }
+
+ /**
+ * Asserts that a result is an error with exactly the given code, message and data.
+ *
+ * @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 $message The expected error message.
+ * @param string $context What the call was, for the assertion messages.
+ * @param array $extra Optional. The expected error data next to the status.
+ * Default empty array.
+ */
+ protected function assert_error( $result, string $code, int $status, string $message, string $context, array $extra = array() ): void {
+ $this->assertWPError( $result, "{$context}: the call should fail." );
+ $this->assertSame( array( $code ), $result->get_error_codes(), "{$context}: the error should hold only the code {$code}." );
+ $this->assertSame( $message, $result->get_error_message(), "{$context}: the error message should match." );
+ $this->assertSameSetsWithIndex( array( 'status' => $status ) + $extra, $result->get_error_data(), "{$context}: the error data should hold the status {$status} and nothing else unexpected." );
+ }
+
+ /**
+ * 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 error of input that fails the schema.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_invalid_input( $result, string $context ): void {
+ $this->assertWPError( $result, "{$context}: the call should fail." );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code(), "{$context}: the input should fail the schema." );
+ }
+
+ /**
+ * Asserts that a result is the not-found error of a term.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_term_not_found( $result, string $context ): void {
+ $this->assert_error( $result, 'term_not_found', 404, 'The requested term was not found.', $context );
+ }
+
+ /**
+ * Asserts that a result is the not-found error of a taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_taxonomy_not_found( $result, string $context ): void {
+ $this->assert_error( $result, 'terms_taxonomy_not_found', 404, 'The requested taxonomy was not found.', $context );
+ }
+
+ /**
+ * 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 $message The expected message.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ protected function assert_invalid_attribute( $result, string $attribute, string $message, string $context ): void {
+ $this->assert_error( $result, 'term_invalid_attribute', 400, $message, $context, array( 'params' => array( "data[{$attribute}]" => $message ) ) );
+ }
+
+ /**
+ * Builds the item that the abilities should return for a stored term.
+ *
+ * @since 7.3.0
+ *
+ * @param int $term_id The term ID.
+ * @param list $keys The requested keys. `id` is always included.
+ * @return array The item, with its keys in their order.
+ */
+ protected function expected_item( int $term_id, array $keys ): array {
+ wp_cache_delete( $term_id, 'terms' );
+
+ $term = get_term( $term_id );
+
+ $this->assertInstanceOf( WP_Term::class, $term, 'Precondition: the term should exist.' );
+
+ $values = array(
+ 'id' => $term->term_id,
+ 'taxonomy' => $term->taxonomy,
+ 'name' => $term->name,
+ 'slug' => $term->slug,
+ 'description' => $term->description,
+ 'parent' => $term->parent,
+ 'count' => $term->count,
+ 'link' => get_term_link( $term ),
+ );
+
+ if ( ! is_taxonomy_hierarchical( $term->taxonomy ) ) {
+ unset( $values['parent'] );
+ }
+
+ $item = array();
+ foreach ( self::ITEM_KEYS as $key ) {
+ if ( array_key_exists( $key, $values ) && ( 'id' === $key || in_array( $key, $keys, true ) ) ) {
+ $item[ $key ] = $values[ $key ];
+ }
+ }
+
+ return $item;
+ }
+
+ /**
+ * Returns the forms the ID of a `where` can take in input that was not prepared, which
+ * the permission callback reads as the ID.
+ *
+ * @since 7.3.0
+ *
+ * @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 ),
+ 'whole float ID' => array( 'float', false ),
+ 'where that is an object' => array( 'integer', true ),
+ );
+ }
+
+ /**
+ * Builds a `where` for a term in one of the forms of unprepared input.
+ *
+ * @since 7.3.0
+ *
+ * @param int $term_id The term 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 $term_id, string $id_type, bool $as_object ) {
+ $id = $term_id;
+ settype( $id, $id_type );
+
+ $where = array(
+ 'taxonomy' => get_term( $term_id )->taxonomy,
+ 'id' => $id,
+ );
+
+ return $as_object ? (object) $where : $where;
+ }
+
+ /**
+ * Returns unprepared `where` values that the update and delete permission callbacks refuse.
+ *
+ * @since 7.3.0
+ *
+ * @return array The inputs.
+ */
+ public static function data_unprepared_where_inputs_that_are_refused(): array {
+ $where = static function ( $id ): array {
+ return array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'id' => $id,
+ ),
+ );
+ };
+
+ return array(
+ 'input that is a string' => array( 'where' ),
+ 'input that is null' => array( null ),
+ 'input that is an integer' => array( 5 ),
+ 'missing where' => array( array() ),
+ 'where that is a string' => array( array( 'where' => 'category' ) ),
+ 'missing taxonomy' => array( array( 'where' => array( 'id' => 5 ) ) ),
+ 'taxonomy that is not a string' => array(
+ array(
+ 'where' => array(
+ 'taxonomy' => array( 'category' ),
+ 'id' => 5,
+ ),
+ ),
+ ),
+ 'taxonomy that is not exposed' => array(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'nav_menu',
+ 'id' => 5,
+ ),
+ ),
+ ),
+ 'taxonomy that does not exist' => array(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'tt_missing',
+ 'id' => 5,
+ ),
+ ),
+ ),
+ 'missing ID' => array( array( 'where' => array( 'taxonomy' => 'category' ) ) ),
+ 'ID of zero' => array( $where( 0 ) ),
+ 'negative ID' => array( $where( -1 ) ),
+ 'fractional ID' => array( $where( 1.5 ) ),
+ 'ID that is not a number' => array( $where( 'abc' ) ),
+ 'ID that starts with a number' => array( $where( '5abc' ) ),
+ 'ID that is an empty string' => array( $where( '' ) ),
+ 'ID that is true' => array( $where( true ) ),
+ 'ID that is null' => array( $where( null ) ),
+ 'ID beyond the exact float range' => array( $where( 2.0 ** 64 ) ),
+ );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/trait-content-data-write-tests.php b/tests/phpunit/tests/abilities-api/trait-content-data-write-tests.php
new file mode 100644
index 0000000000000..8bf2cd499d3b1
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/trait-content-data-write-tests.php
@@ -0,0 +1,1101 @@
+ $data The data, without the type.
+ * @param list|null $fields Optional. The fields, or null for the default. Default null.
+ * @param string $type Optional. The post type of a post that the call creates.
+ * Default 'post'.
+ * @return array The input.
+ */
+ abstract protected function build_write_input( ?int $post_id, array $data, ?array $fields = null, string $type = 'post' ): array;
+
+ /**
+ * Asserts that a result is the post item of a successful write and returns the stored post.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param int|null $post_id The post ID, or null when the call created a post.
+ * @return WP_Post The stored post.
+ */
+ abstract protected function assert_data_written( $result, ?int $post_id ): WP_Post;
+
+ /**
+ * Creates the users and posts that both test classes read: a `page_writer` who may write
+ * pages but not read the drafts of other users, a `publisher` who may publish posts but
+ * not edit published posts, and a draft page of the editor.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_UnitTest_Factory $factory The unit test factory.
+ */
+ protected static function create_data_write_fixtures( WP_UnitTest_Factory $factory ): void {
+ self::$user_ids['page_writer'] = $factory->user->create( array( 'role' => 'subscriber' ) );
+ get_userdata( self::$user_ids['page_writer'] )->add_cap( 'edit_pages' );
+
+ self::$user_ids['publisher'] = $factory->user->create( array( 'role' => 'contributor' ) );
+ get_userdata( self::$user_ids['publisher'] )->add_cap( 'publish_posts' );
+
+ self::$post_ids['editor_draft_page'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ )
+ );
+ }
+
+ /**
+ * Returns `data` values that the input schema rejects: keys outside the allow-list, statuses
+ * that can never be set, and invalid values.
+ *
+ * @return array}> The data, without the type.
+ */
+ public static function data_invalid_data(): array {
+ $cases = array();
+
+ foreach ( array(
+ 'ID' => 1,
+ 'post_password' => 'secret',
+ 'meta_input' => array( 'cw_key' => 'value' ),
+ ) as $key => $value ) {
+ $cases[ "key outside the allow-list: {$key}" ] = array(
+ array(
+ 'title' => 'Invalid',
+ $key => $value,
+ ),
+ );
+ }
+
+ foreach ( self::data_statuses_that_can_never_be_set() as $label => list( $status ) ) {
+ $cases[ "status that can never be set: {$label}" ] = array(
+ array(
+ 'title' => 'Invalid',
+ 'status' => $status,
+ ),
+ );
+ }
+
+ foreach ( array(
+ 'title that is a number' => array( 'title', 123 ),
+ 'title that is a list' => array( 'title', array( 'x' ) ),
+ 'title that is null' => array( 'title', null ),
+ 'content that is a boolean' => array( 'content', true ),
+ 'excerpt that is a number' => array( 'excerpt', 5 ),
+ 'status that is a number' => array( 'status', 1 ),
+ 'slug that is a list' => array( 'slug', array( 'slug' ) ),
+ 'date that is a string' => array( 'date', '2016-12-12T14:00:00' ),
+ 'date with a number' => array( 'date', array( 'site' => 123 ) ),
+ 'date that cannot be parsed' => array( 'date', array( 'site' => 'not a date' ) ),
+ 'GMT date that cannot be parsed' => array( 'date', array( 'gmt' => 'not a date' ) ),
+ 'date that is not a date-time' => array( 'date', array( 'site' => '2010-60-01T02:00:00Z' ) ),
+ 'author that is text' => array( 'author', 'abc' ),
+ 'author with digits and letters' => array( 'author', '1abc' ),
+ 'author 0' => array( 'author', 0 ),
+ 'author that is a fraction' => array( 'author', 1.5 ),
+ 'parent that is negative' => array( 'parent', -1 ),
+ 'parent that is text' => array( 'parent', 'abc' ),
+ 'terms that is a list' => array( 'terms', array( 1 ) ),
+ 'terms with no taxonomy' => array( 'terms', array() ),
+ 'terms of an unknown taxonomy' => array( 'terms', array( 'cw_missing' => array( 1 ) ) ),
+ 'terms of an unexposed taxonomy' => array( 'terms', array( 'post_format' => array( 1 ) ) ),
+ 'terms that are not a list' => array( 'terms', array( 'post_tag' => array( 'id' => 1 ) ) ),
+ 'term ID 0' => array( 'terms', array( 'post_tag' => array( 0 ) ) ),
+ 'term ID that is text' => array( 'terms', array( 'post_tag' => array( 'abc' ) ) ),
+ 'duplicate term IDs' => array( 'terms', array( 'post_tag' => array( 1, 1 ) ) ),
+ ) as $label => list( $attribute, $value ) ) {
+ $cases[ "invalid value: {$label}" ] = array(
+ array(
+ 'title' => 'Invalid',
+ $attribute => $value,
+ ),
+ );
+ }
+
+ return $cases;
+ }
+
+ /**
+ * A key outside the allow-list, a status that can never be set, and an invalid value fail
+ * input validation.
+ *
+ * @ticket 66706
+ * @dataProvider data_invalid_data
+ * @since 7.3.0
+ *
+ * @param array $data The data, without the type.
+ */
+ public function test_invalid_data_fails_input_validation( array $data ): void {
+ $post_id = $this->get_write_post_id( 'administrator' );
+
+ $this->assert_invalid_input( $this->build_write_input( $post_id, $data ), $post_id, 'Invalid data' );
+ }
+
+ /**
+ * Called directly, an internal or unregistered status is an invalid attribute.
+ *
+ * @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 = $this->get_write_post_id( 'administrator' );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Unusable status',
+ 'status' => $status,
+ )
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'status', 'A direct call with a status that can never be set', 'The status must be a registered post status that is not internal.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns `date` values that cannot be read as a date.
+ *
+ * @return array}> The dates.
+ */
+ public static function data_dates_that_cannot_be_read(): array {
+ return array(
+ 'site that is not a date' => array( array( 'site' => 'not a date' ) ),
+ 'gmt that is not a date' => array( array( 'gmt' => 'not a date' ) ),
+ 'site that is not a string' => array( array( 'site' => 20161212 ) ),
+ 'unreadable site, valid gmt' => array(
+ array(
+ 'site' => 'not a date',
+ 'gmt' => '2016-12-12T19:00:00',
+ ),
+ ),
+ 'neither site nor gmt' => array( array() ),
+ );
+ }
+
+ /**
+ * Called directly, a `date` that cannot be read is an invalid attribute.
+ *
+ * @ticket 66706
+ * @dataProvider data_dates_that_cannot_be_read
+ * @since 7.3.0
+ *
+ * @param array $date The `date`.
+ */
+ public function test_direct_call_rejects_a_date_that_cannot_be_read( array $date ): void {
+ $post_id = $this->get_write_post_id( 'administrator' );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Unreadable date',
+ 'date' => $date,
+ )
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'date', 'A direct call with a date that cannot be read', 'The date must be a valid date in ISO 8601 format.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns `data` values with a `status` or an `author` of the wrong type.
+ *
+ * @return array}> The data, without the type.
+ */
+ public static function data_malformed_status_or_author(): array {
+ return array(
+ 'status that is a list' => array( array( 'status' => array( 'draft' ) ) ),
+ 'author that is a word' => array( array( 'author' => 'admin' ) ),
+ );
+ }
+
+ /**
+ * The permission callback returns false for a `status` or an `author` of the wrong type,
+ * which only a direct call can send.
+ *
+ * @ticket 66706
+ * @dataProvider data_malformed_status_or_author
+ * @since 7.3.0
+ *
+ * @param array $data The data, without the type.
+ */
+ public function test_permission_callback_returns_false_for_a_malformed_status_or_author( array $data ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $input = $this->build_write_input( $this->get_write_post_id( 'administrator' ), $data );
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should return false.' );
+ }
+
+ /**
+ * Returns dates that change the stored status: the requested status, the requested GMT date,
+ * and the stored status.
+ *
+ * @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 {
+ $post_id = $this->get_write_post_id( 'editor' );
+
+ $this->login_as( 'editor' );
+
+ $input = $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Scheduled',
+ 'status' => $status,
+ 'date' => array( 'gmt' => $gmt ),
+ ),
+ array( 'status' )
+ );
+ $result = $this->run_ability( $input );
+
+ $this->assertSame( $expected, $this->assert_data_written( $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.' );
+ }
+
+ /**
+ * Returns data that passes the attribute rules and that the save refuses: the data, the
+ * input path the error is about, and the message of the save error.
+ *
+ * @return array, 1: string, 2: string}> The cases.
+ */
+ public static function data_posts_refused_by_the_save(): array {
+ return array(
+ 'post without title, content, and excerpt' => array(
+ array(
+ 'title' => '',
+ 'content' => '',
+ 'excerpt' => '',
+ ),
+ 'data',
+ 'Content, title, and excerpt are empty.',
+ ),
+ 'date in the year 0' => array(
+ array(
+ 'title' => 'Year zero',
+ 'date' => array( 'gmt' => '0000-06-15T12:00:00' ),
+ ),
+ 'data[date]',
+ 'Invalid date.',
+ ),
+ );
+ }
+
+ /**
+ * An empty post and a date that is not a calendar date, both refused by the save, are
+ * invalid attributes: the error has the message of the save error and the input path.
+ *
+ * @ticket 66706
+ * @dataProvider data_posts_refused_by_the_save
+ * @since 7.3.0
+ *
+ * @param array $data The data, without the type.
+ * @param string $param The input path the error is about.
+ * @param string $message The message of the save error.
+ */
+ public function test_post_refused_by_the_save_is_an_invalid_attribute( array $data, string $param, string $message ): void {
+ $post_id = $this->get_write_post_id( 'administrator' );
+
+ $this->login_as( 'administrator' );
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, $data ), $post_id );
+
+ $this->assert_error( $result, 'content_invalid_attribute', 400, 'A post that the save refuses' );
+ $this->assertSame( $message, $result->get_error_message(), 'The message should be the message of the save error.' );
+ $this->assertSame( array( $param => $message ), $result->get_error_data()['params'] ?? array(), 'The params should hold only the input path, with the message.' );
+ }
+
+ /**
+ * 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 = $this->get_write_post_id( 'administrator' );
+
+ // A create inserts the row of the post, and an update updates it.
+ list( $verb, $code, $message ) = null === $post_id
+ ? array( 'INSERT', 'db_insert_error', 'Could not insert post into the database.' )
+ : array( 'UPDATE', 'db_update_error', 'Could not update post in the database.' );
+
+ $this->login_as( 'administrator' );
+
+ $before = $this->snapshot( $post_id );
+
+ $suppress = $wpdb->suppress_errors();
+ add_filter(
+ 'query',
+ static function ( $query ) use ( $verb ) {
+ return str_starts_with( $query, $verb ) ? '],' : $query;
+ }
+ );
+
+ $result = $this->run_ability( $this->build_write_input( $post_id, array( 'title' => 'Database error' ) ) );
+
+ $wpdb->suppress_errors( $suppress );
+
+ $this->assert_error( $result, $code, 500, 'A database error' );
+ $this->assertSame( $message, $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.' );
+ }
+
+ /**
+ * Returns attributes that are invalid for the user or after sanitization: the role, the data,
+ * the invalid attribute, and the expected error message.
+ *
+ * @return array, 2: string, 3: string}> The cases.
+ */
+ public static function data_invalid_attributes(): array {
+ return array(
+ 'missing author named with edit_others_posts' => array(
+ 'editor',
+ array(
+ 'title' => 'Nobody',
+ 'author' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER,
+ ),
+ 'author',
+ 'The author must be an existing user of this site.',
+ ),
+ 'slug that sanitizes to nothing' => array(
+ 'administrator',
+ array(
+ 'title' => 'Slug',
+ 'slug' => '!!!',
+ ),
+ 'slug',
+ 'The slug must contain characters that are valid in a slug.',
+ ),
+ );
+ }
+
+ /**
+ * A missing author named by a user with `edit_others_posts` and a slug that sanitizes to
+ * nothing are invalid attributes.
+ *
+ * @ticket 66706
+ * @dataProvider data_invalid_attributes
+ * @since 7.3.0
+ *
+ * @param string $role The role to write as.
+ * @param array $data The data, without the type.
+ * @param string $attribute The invalid attribute.
+ * @param string $message The expected error message.
+ */
+ public function test_invalid_attribute_is_rejected( string $role, array $data, string $attribute, string $message ): void {
+ $post_id = $this->get_write_post_id( $role );
+
+ $this->login_as( $role );
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, $data ), $post_id );
+
+ $this->assert_invalid_attribute( $result, $attribute, "An invalid {$attribute}", $message );
+ }
+
+ /**
+ * 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 = $this->get_write_post_id( 'editor' );
+
+ $this->login_as( 'editor' );
+
+ $input = $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => $text,
+ 'content' => $text,
+ 'excerpt' => $text,
+ ),
+ array( 'title.raw', 'content.raw', 'excerpt.raw' )
+ );
+ $result = $this->run_ability( $input );
+
+ $post = $this->assert_data_written( $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.' );
+ }
+
+ /**
+ * Returns markup and the values it is stored and rendered as for a user without
+ * `unfiltered_html`: the role, the sent markup, the stored and the rendered title, and the
+ * stored and the rendered content and excerpt.
+ *
+ * @return array The cases.
+ */
+ public static function data_filtered_markup(): array {
+ $script = array(
+ 'div
strong ',
+ 'div strong ',
+ 'div strong',
+ 'div
strong ',
+ "div
\n strong
",
+ );
+
+ return array(
+ 'backslashes and non-ASCII text' => array(
+ 'author',
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯',
+ '\o/ ¯\_(ツ)_/¯
',
+ ),
+ 'entities' => array(
+ 'author',
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <',
+ '\\\&\\\ & &invalid; < < <
',
+ ),
+ 'a script' => array_merge( array( 'author' ), $script ),
+ 'a script of a contributor' => array_merge( array( 'contributor' ), $script ),
+ 'a link with extra attributes' => array(
+ 'author',
+ 'link',
+ 'link',
+ 'link',
+ 'link',
+ 'link
',
+ ),
+ );
+ }
+
+ /**
+ * Writes the same markup to the title, content, and excerpt as the current user, and returns
+ * the raw and rendered values.
+ *
+ * @since 7.3.0
+ *
+ * @param int|null $post_id The post ID, or null when the call creates a post.
+ * @param string $markup The markup.
+ * @return array The ability result.
+ */
+ private function write_markup( ?int $post_id, string $markup ): array {
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => $markup,
+ 'content' => $markup,
+ 'excerpt' => $markup,
+ ),
+ array( 'title', 'content.raw', 'content.rendered', 'excerpt.raw', 'excerpt.rendered' )
+ )
+ );
+
+ $this->assert_data_written( $result, $post_id );
+
+ return $result;
+ }
+
+ /**
+ * The markup of an author or a contributor, who lack `unfiltered_html`, is filtered as on any
+ * other save.
+ *
+ * @ticket 66706
+ * @dataProvider data_filtered_markup
+ * @since 7.3.0
+ *
+ * @param string $role The role to write as.
+ * @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_a_user_without_unfiltered_html_is_filtered( string $role, string $input, string $title_raw, string $title_rendered, string $text_raw, string $text_rendered ): void {
+ $this->login_as( $role );
+
+ $this->assertFalse( current_user_can( 'unfiltered_html' ), 'Precondition: the user should not have unfiltered_html.' );
+
+ $result = $this->write_markup( $this->get_write_post_id( $role ), $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.' );
+ }
+
+ /**
+ * Asserts that the markup of the current user 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->write_markup( $this->get_write_post_id( 'administrator' ), $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();
+ }
+
+ /**
+ * 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 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.' );
+ }
+
+ /**
+ * The permission callback refuses a user without `edit_others_posts` who names another
+ * author, existing or not, so the refusal 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 = $this->get_write_post_id( 'author' );
+
+ $this->login_as( 'author' );
+
+ $input = $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Ghost written',
+ 'author' => self::$user_ids[ $author ] ?? REST_TESTS_IMPOSSIBLY_HIGH_NUMBER,
+ )
+ );
+ $result = $this->run_ability_that_writes_nothing( $input, $post_id );
+
+ $this->assert_refused( $result, 'Naming another author' );
+ }
+
+ /**
+ * 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.' );
+
+ $post_id = $this->get_write_post_id( 'editor' );
+
+ $this->login_as( 'editor' );
+
+ $input = $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Not a member',
+ 'author' => $non_member,
+ )
+ );
+ $result = $this->run_ability_that_writes_nothing( $input, $post_id );
+
+ $this->assert_invalid_attribute( $result, 'author', 'An author who is not a member of the site', 'The author must be an existing user of this site.' );
+ }
+
+ /**
+ * Returns parents that a page may not have.
+ *
+ * @return array The parents, as fixture names.
+ */
+ public static function data_parents_refused_by_the_permission_callback(): array {
+ return array(
+ 'missing post' => array( 'missing' ),
+ 'page the user may not read' => array( 'editor_draft_page' ),
+ 'revision' => array( 'revision' ),
+ );
+ }
+
+ /**
+ * A missing parent, a parent the user may not read, and a revision, whose type is not exposed
+ * to abilities, are refused by the permission callback, so the refusal never tells whether a
+ * post exists.
+ *
+ * @ticket 66706
+ * @dataProvider data_parents_refused_by_the_permission_callback
+ * @since 7.3.0
+ *
+ * @param string $parent_key The parent, as a fixture name.
+ */
+ public function test_parent_that_is_missing_unreadable_or_not_exposed_is_refused( string $parent_key ): void {
+ $post_id = $this->get_write_post_id( 'page_writer' );
+
+ $this->login_as( 'page_writer' );
+
+ $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.' );
+
+ $input = $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Child',
+ 'parent' => self::$post_ids[ $parent_key ] ?? REST_TESTS_IMPOSSIBLY_HIGH_NUMBER,
+ ),
+ null,
+ 'page'
+ );
+ $result = $this->run_ability_that_writes_nothing( $input, $post_id );
+
+ $this->assert_refused( $result, 'A missing, unreadable, or unexposed parent' );
+ }
+
+ /**
+ * A user who may not publish posts cannot set the slug of a post that becomes pending.
+ *
+ * Intentionally strict: the save would drop the slug, so the call is refused instead of the
+ * slug being dropped without notice.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_of_a_pending_post_is_refused_without_publish_posts(): void {
+ $post_id = $this->get_write_post_id( 'contributor' );
+
+ $this->login_as( 'contributor' );
+
+ $input = $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Pending slug',
+ 'status' => 'pending',
+ 'slug' => 'pending-slug',
+ )
+ );
+ $result = $this->run_ability_that_writes_nothing( $input, $post_id, 'Nothing should be written for a slug that cannot be stored.' );
+
+ $this->assert_refused( $result, 'A slug on a pending post without publish_posts' );
+ }
+
+ /**
+ * A user who may publish posts sets the slug of a post that becomes pending.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_of_a_pending_post_is_stored_with_publish_posts(): void {
+ $post_id = $this->get_write_post_id( 'publisher' );
+
+ $this->login_as( 'publisher' );
+
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Pending slug',
+ 'status' => 'pending',
+ 'slug' => 'pending-slug',
+ ),
+ array( 'status', 'slug' )
+ )
+ );
+
+ $post = $this->assert_data_written( $result, $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.' );
+ $this->assertSame( 'pending', $result['status'], 'The pending status should be returned.' );
+ $this->assertSame( 'pending-slug', $result['slug'], 'The slug of the pending post should be returned.' );
+ }
+
+ /**
+ * 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_written_post(): void {
+ $post_id = $this->get_write_post_id( 'publisher' );
+
+ $this->login_as( 'publisher' );
+
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Published once',
+ 'content' => 'Body.',
+ 'status' => 'publish',
+ ),
+ array( 'title', 'content.raw', 'content.rendered' )
+ )
+ );
+
+ $post = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( 'publish', $post->post_status, 'The post should be published.' );
+ $this->assertFalse( current_user_can( 'edit_post', $post->ID ), '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.' );
+ }
+
+ /**
+ * Registers a flat taxonomy for posts, exposed to abilities, whose terms need the
+ * `manage_categories` capability to be assigned, and returns a term of it.
+ *
+ * Editors have the capability, authors do not.
+ *
+ * @since 7.3.0
+ *
+ * @return int The term ID.
+ */
+ protected function register_restricted_taxonomy(): int {
+ register_taxonomy(
+ 'cw_restricted',
+ 'post',
+ array(
+ 'show_in_abilities' => true,
+ 'capabilities' => array( 'assign_terms' => 'manage_categories' ),
+ )
+ );
+
+ return self::factory()->term->create( array( 'taxonomy' => 'cw_restricted' ) );
+ }
+
+ /**
+ * Returns the IDs of a post's terms in a taxonomy, sorted.
+ *
+ * @since 7.3.0
+ *
+ * @param int $post_id The post ID.
+ * @param string $taxonomy The taxonomy name.
+ * @return list The sorted term IDs.
+ */
+ protected function get_stored_term_ids( int $post_id, string $taxonomy ): array {
+ $term_ids = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
+ sort( $term_ids );
+
+ return $term_ids;
+ }
+
+ /**
+ * The terms of each taxonomy sent are stored and returned.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_are_stored_and_returned(): void {
+ $categories = self::factory()->category->create_many( 2 );
+ $tag = self::factory()->tag->create();
+ $post_id = $this->get_write_post_id( 'editor' );
+
+ sort( $categories );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Tagged',
+ 'terms' => array(
+ 'category' => $categories,
+ 'post_tag' => array( $tag ),
+ ),
+ ),
+ array( 'terms' )
+ )
+ );
+
+ $post = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( $categories, $this->get_stored_term_ids( $post->ID, 'category' ), 'The categories should be stored.' );
+ $this->assertSame( array( $tag ), $this->get_stored_term_ids( $post->ID, 'post_tag' ), 'The tag should be stored.' );
+ $this->assertSame( array( 'category', 'post_tag' ), array_keys( $result['terms'] ), 'The output should hold the terms of each taxonomy of the post type.' );
+ $this->assertEqualsCanonicalizing( $categories, $result['terms']['category'], 'The output should hold the categories.' );
+ $this->assertSame( array( $tag ), $result['terms']['post_tag'], 'The output should hold the tag.' );
+ }
+
+ /**
+ * The terms of a taxonomy that the post type does not use are an invalid attribute, also
+ * when the taxonomy is exposed for another post type.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_of_a_taxonomy_the_post_type_does_not_use_are_an_invalid_attribute(): void {
+ register_taxonomy( 'cw_genre', 'page', array( 'show_in_abilities' => true ) );
+ $term_id = self::factory()->term->create( array( 'taxonomy' => 'cw_genre' ) );
+ $post_id = $this->get_write_post_id( 'administrator' );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Wrong taxonomy',
+ 'terms' => array( 'cw_genre' => array( $term_id ) ),
+ )
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'terms', 'Terms of a taxonomy the post type does not use', 'The cw_genre taxonomy is not used by the post type.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns term IDs that name no term of the `post_tag` taxonomy.
+ *
+ * @return array The cases, as `missing` or a taxonomy whose term is sent.
+ */
+ public static function data_term_ids_that_name_no_tag(): array {
+ return array(
+ 'missing term' => array( 'missing' ),
+ 'term of category' => array( 'category' ),
+ );
+ }
+
+ /**
+ * A term ID that names no term of the taxonomy is an invalid attribute.
+ *
+ * @ticket 66904
+ * @dataProvider data_term_ids_that_name_no_tag
+ * @since 7.3.0
+ *
+ * @param string $term `missing`, or the taxonomy of the term to send.
+ */
+ public function test_term_id_that_names_no_term_of_the_taxonomy_is_an_invalid_attribute( string $term ): void {
+ $term_id = 'missing' === $term ? REST_TESTS_IMPOSSIBLY_HIGH_NUMBER : self::factory()->term->create( array( 'taxonomy' => $term ) );
+ $post_id = $this->get_write_post_id( 'administrator' );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Unknown tag',
+ 'terms' => array( 'post_tag' => array( self::factory()->tag->create(), $term_id ) ),
+ )
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'terms', 'A term ID that names no tag', 'The post_tag terms must be IDs of existing terms of that taxonomy.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * The permission callback refuses terms of a taxonomy whose terms the user may not assign.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_the_user_may_not_assign_are_refused(): void {
+ $term_id = $this->register_restricted_taxonomy();
+ $post_id = $this->get_write_post_id( 'author' );
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Restricted',
+ 'terms' => array( 'cw_restricted' => array( $term_id ) ),
+ )
+ )
+ );
+
+ $this->assert_refused( $result, 'Terms the user may not assign' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * The permission callback refuses a term whose `assign_term` capability the user lacks,
+ * although the user may assign the other terms of the taxonomy.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_term_the_user_may_not_assign_is_refused(): void {
+ $allowed = self::factory()->tag->create();
+ $denied = self::factory()->tag->create();
+ $post_id = $this->get_write_post_id( 'editor' );
+
+ add_filter(
+ 'map_meta_cap',
+ static function ( $caps, $cap, $user_id, $args ) use ( $denied ) {
+ return 'assign_term' === $cap && isset( $args[0] ) && $args[0] === $denied ? array( 'do_not_allow' ) : $caps;
+ },
+ 10,
+ 4
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assertTrue( current_user_can( 'assign_term', $allowed ), 'Precondition: the user should be able to assign the other tag.' );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'One tag denied',
+ 'terms' => array( 'post_tag' => array( $allowed, $denied ) ),
+ )
+ )
+ );
+
+ $this->assert_refused( $result, 'A term the user may not assign' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Terms of a taxonomy that needs a capability the user has are stored.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_the_user_may_assign_are_stored(): void {
+ $term_id = $this->register_restricted_taxonomy();
+ $post_id = $this->get_write_post_id( 'editor' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->build_write_input(
+ $post_id,
+ array(
+ 'title' => 'Restricted',
+ 'terms' => array( 'cw_restricted' => array( $term_id ) ),
+ ),
+ array( 'terms.cw_restricted' )
+ )
+ );
+
+ $post = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( array( $term_id ), $this->get_stored_term_ids( $post->ID, 'cw_restricted' ), 'The term should be stored.' );
+ $this->assertSame( array( 'cw_restricted' => array( $term_id ) ), $result['terms'], 'The output should hold only the requested taxonomy.' );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php
index d2795c803730f..b7cf088d1b85a 100644
--- a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentAbility.php
@@ -2,6 +2,8 @@
declare( strict_types=1 );
+require_once __DIR__ . '/testcase-content-ability.php';
+
/**
* Tests for the core/content-query ability shipped with the Abilities API.
*
@@ -9,7 +11,7 @@
*
* @group abilities-api
*/
-class Tests_Abilities_API_WpRegisterCoreContentAbility extends WP_UnitTestCase {
+class Tests_Abilities_API_WpRegisterCoreContentAbility extends WP_Abilities_Content_UnitTestCase {
/**
* Globals that rendering a post changes: the global post and the globals that
@@ -135,58 +137,7 @@ public static function wpSetUpBeforeClass( $factory ): void {
}
/**
- * Sets up the content ability category for each test.
- *
- * @since 7.2.0
- */
- public function set_up(): void {
- parent::set_up();
-
- if ( wp_has_ability( 'core/content-query' ) ) {
- wp_unregister_ability( 'core/content-query' );
- }
-
- 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.',
- )
- );
- }
- }
-
- /**
- * Removes the ability and its 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' );
- }
-
- if ( wp_has_ability_category( 'content' ) ) {
- wp_unregister_ability_category( 'content' );
- }
-
- /*
- * Keep this reset even though the parent set_up() also resets the post types. A test
- * may turn off `show_in_abilities` on `post` and `page`, and the next class's
- * wpSetUpBeforeClass() runs before the next set_up(). A class that registers the core
- * abilities there, such as Tests_REST_API_WpRestAbilitiesContentController, would then
- * register no content ability, and all of its tests would fail.
- */
- $this->reset_post_types();
-
- parent::tear_down();
- }
-
- /**
- * Registers the core/content-query ability inside a faked init action.
+ * Registers the content abilities inside a faked init action.
*
* @since 7.2.0
*/
@@ -197,7 +148,8 @@ private function register_ability(): void {
}
/**
- * Registers the core/content-query ability and returns the callbacks it was registered with.
+ * Registers the content abilities and returns the callbacks core/content-query was
+ * registered with.
*
* The callbacks call private methods, so tests that skip input validation or the
* permission check capture them from the registration arguments.
@@ -356,7 +308,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'];
@@ -407,6 +359,9 @@ public function test_input_schema_models_a_flat_where(): void {
'author.name',
'author.slug',
'parent',
+ 'terms',
+ 'terms.category',
+ 'terms.post_tag',
),
$fields['items']['enum'],
'The fields enum should list every field, each followed by the paths of its sub-fields.'
@@ -732,6 +687,7 @@ public function test_output_schema_describes_query_responses(): void {
'content' => 'object',
'author' => 'object',
'parent' => 'integer',
+ 'terms' => 'object',
),
wp_list_pluck( $post_schema['properties'], 'type' ),
'The post schema should describe each post property with its type, in order.'
@@ -766,6 +722,10 @@ public function test_output_schema_describes_query_responses(): void {
'name' => $nullable_string,
'slug' => $nullable_string,
),
+ 'terms' => array(
+ 'category' => 'array',
+ 'post_tag' => 'array',
+ ),
);
foreach ( $object_types as $name => $types ) {
$object = $post_schema['properties'][ $name ];
@@ -2103,6 +2063,9 @@ public static function data_sub_field_paths(): array {
'content.protected' => array(
'field' => 'content.protected',
),
+ 'terms.post_tag' => array(
+ 'field' => 'terms.post_tag',
+ ),
);
}
@@ -2167,6 +2130,10 @@ public static function data_object_fields(): array {
'field' => 'author',
'keys' => array( 'id', 'name', 'slug' ),
),
+ 'terms' => array(
+ 'field' => 'terms',
+ 'keys' => array( 'category', 'post_tag' ),
+ ),
);
}
@@ -2817,6 +2784,7 @@ public function test_objects_that_do_not_apply_are_left_out(): void {
$this->assertFalse( post_type_supports( 'untitled_cpt', 'title' ), 'Precondition: the post type should not support titles.' );
$this->assertFalse( post_type_supports( 'untitled_cpt', 'author' ), 'Precondition: the post type should not support authors.' );
+ $this->assertSame( array(), get_object_taxonomies( 'untitled_cpt' ), 'Precondition: the post type should use no taxonomy.' );
$post_id = self::factory()->post->create(
array(
@@ -2834,7 +2802,7 @@ public function test_objects_that_do_not_apply_are_left_out(): void {
'type' => 'untitled_cpt',
'ids' => array( $post_id ),
),
- 'fields' => array( 'title', 'author' ),
+ 'fields' => array( 'title', 'author', 'terms' ),
)
);
@@ -2860,6 +2828,7 @@ public function test_returned_keys_follow_the_fields_order(): void {
'hierarchical' => true,
'show_in_abilities' => true,
'supports' => array( 'title', 'editor', 'author', 'excerpt' ),
+ 'taxonomies' => array( 'category' ),
)
);
@@ -2889,7 +2858,7 @@ public function test_returned_keys_follow_the_fields_order(): void {
$this->assertSame( array( 'raw', 'protected' ), array_keys( $result['items'][0]['content'] ), 'Keys inside an object should follow the fields order.' );
// Every top-level field of the fields enum, in its order.
- $top_level_fields = array( 'id', 'type', 'status', 'date', 'modified', 'slug', 'link', 'title', 'excerpt', 'content', 'author', 'parent' );
+ $top_level_fields = array( 'id', 'type', 'status', 'date', 'modified', 'slug', 'link', 'title', 'excerpt', 'content', 'author', 'parent', 'terms' );
$every_field = wp_get_ability( 'core/content-query' )->execute(
array(
@@ -2990,9 +2959,9 @@ public function test_raw_field_requests_omit_raw_values_for_roles_without_edit_a
}
/**
- * Returns statuses that are neither publicly viewable nor `private`: a draft, a public status
- * that is not viewable, and a custom status flagged private, which WP_Query does not narrow
- * to the current user's own posts as it does `private`.
+ * Returns statuses that are neither publicly viewable nor `private`: a draft, the Trash, a
+ * public status that is not viewable, and a custom status flagged private, which WP_Query does
+ * not narrow to the current user's own posts as it does `private`.
*
* @return array Status test cases.
*/
@@ -3001,6 +2970,9 @@ public static function data_statuses_that_require_edit_access(): array {
'draft' => array(
'status' => 'draft',
),
+ 'trash' => array(
+ 'status' => 'trash',
+ ),
'public status, not viewable' => array(
'status' => 'public_hidden',
),
@@ -3014,6 +2986,7 @@ public static function data_statuses_that_require_edit_access(): array {
* Subscribers cannot request posts in a status that requires edit access.
*
* @ticket 66268
+ * @ticket 66706
* @dataProvider data_statuses_that_require_edit_access
* @since 7.2.0
*
@@ -3564,46 +3537,71 @@ public static function data_roles_with_edit_access_to_other_users_posts(): array
}
/**
- * A query by ID without a status does not cover the internal `trash` status, even for a
- * role that can edit the trashed post.
+ * Returns how a query without a status names a trashed post, by ID or by slug, and a role
+ * that can edit that post.
*
- * The default statuses with IDs are the statuses that are not internal, so the query
- * neither returns nor counts the trashed post. The post is named by ID, since trashing a
- * post renames its slug.
+ * @return array Query test cases.
+ */
+ public static function data_queries_without_a_status(): array {
+ return array(
+ 'IDs, administrator' => array(
+ 'filter' => 'ids',
+ 'role' => 'administrator',
+ ),
+ 'IDs, editor' => array(
+ 'filter' => 'ids',
+ 'role' => 'editor',
+ ),
+ 'slugs, administrator' => array(
+ 'filter' => 'slugs',
+ 'role' => 'administrator',
+ ),
+ 'slugs, editor' => array(
+ 'filter' => 'slugs',
+ 'role' => 'editor',
+ ),
+ );
+ }
+
+ /**
+ * A query without a status that lists IDs or slugs does not cover the internal `trash`
+ * status, even for a role that can edit the trashed post.
+ *
+ * The default statuses with IDs or slugs are the statuses that are not internal, so the query
+ * neither returns nor counts the trashed post.
*
* @ticket 66268
- * @dataProvider data_roles_with_edit_access_to_other_users_posts
+ * @ticket 66706
+ * @dataProvider data_queries_without_a_status
* @since 7.2.0
+ * @since 7.3.0 Covers queries by slug.
*
- * @param string $role The role to query as.
+ * @param string $filter The filter that names the trashed post, `ids` or `slugs`.
+ * @param string $role The role to query as.
*/
- public function test_ids_without_a_status_do_not_cover_trashed_posts( string $role ): void {
- $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.' );
+ public function test_query_without_a_status_does_not_cover_trashed_posts( string $filter, string $role ): void {
+ $post_id = $this->create_trashed_post();
$this->login_as( $role );
$this->register_ability();
$this->assertTrue( current_user_can( 'edit_post', $post_id ), 'Precondition: the role should be able to edit the trashed post.' );
+ $where = array( 'type' => 'post' );
+ if ( 'ids' === $filter ) {
+ $where['ids'] = array( $post_id );
+ } else {
+ $where['slugs'] = array( get_post( $post_id )->post_name );
+ }
+
$result = wp_get_ability( 'core/content-query' )->execute(
array(
- 'where' => array(
- 'type' => 'post',
- 'ids' => array( $post_id ),
- ),
+ 'where' => $where,
'fields' => array( 'id' ),
)
);
- $this->assertSame( self::EMPTY_RESULT, $result, 'A query by ID without a status should neither return nor count a trashed post.' );
+ $this->assertSame( self::EMPTY_RESULT, $result, "A query by {$filter} without a status should neither return nor count a trashed post." );
}
/**
@@ -6218,76 +6216,6 @@ public function test_execute_callback_rejects_non_integer_parent_filter(): void
);
}
- /**
- * Returns `where.ids` values that hold no valid ID: no item is a whole number of at least
- * 1 within the integer range.
- *
- * @return array The `where.ids` values.
- */
- public static function data_ids_with_no_valid_ids(): array {
- return array(
- 'zero' => array(
- 'ids' => array( 0 ),
- ),
- 'fraction' => array(
- 'ids' => array( 2.5 ),
- ),
- 'negative number' => array(
- 'ids' => array( -5 ),
- ),
- 'non-numeric string' => array(
- 'ids' => 'abc',
- ),
- 'beyond the integer range' => array(
- 'ids' => array( 2 ** 64 + self::ALIASED_POST_ID ),
- ),
- );
- }
-
- /**
- * An ids filter that parses to no valid IDs is rejected rather than returning an
- * unrestricted result set.
- *
- * WP_Query ignores an empty `post__in`, so an ids list with no valid IDs would otherwise
- * return every post of the type — the opposite of the caller's intent. The filter must
- * fail closed instead, and an ID beyond the integer range must not wrap around onto the
- * published post whose ID it aliases.
- *
- * @ticket 66268
- * @dataProvider data_ids_with_no_valid_ids
- * @since 7.2.0
- *
- * @param mixed $ids The `where.ids` value to send.
- */
- public function test_execute_callback_rejects_ids_with_no_valid_ids( $ids ): void {
- $this->login_as( 'administrator' );
-
- self::factory()->post->create(
- array(
- 'import_id' => self::ALIASED_POST_ID,
- 'post_status' => 'publish',
- )
- );
- $execute = $this->get_ability_callbacks()['execute_callback'];
-
- $result = $execute(
- array(
- 'where' => array(
- 'type' => 'post',
- 'ids' => $ids,
- ),
- )
- );
-
- $this->assertWPError( $result, 'An ids filter with no valid IDs must not fall through to an unrestricted query.' );
- $this->assertSame( 'content_invalid_filter', $result->get_error_code(), 'An empty-after-parsing ids filter should fail closed as an invalid filter.' );
- $this->assertSame(
- array( 'where[ids]' => $result->get_error_message() ),
- $result->get_error_data()['params'],
- 'The error data should map the ids filter to the error message.'
- );
- }
-
/**
* Called directly, an item of `where.ids` that is not a valid ID is dropped, while the
* other IDs still apply.
@@ -6394,9 +6322,9 @@ public function test_execute_callback_rejects_slugs_with_no_slug_left( $slugs ):
}
/**
- * Returns `where` filters with a status that is not registered, or is internal, which reach
- * the execute callback when it is called directly, or when the input schema lists a status
- * that is not registered when the query runs.
+ * Returns `where` filters with a status that is not registered, or is internal and not
+ * `trash`, which reach the execute callback when it is called directly, or when the input
+ * schema lists a status that is not registered when the query runs.
*
* @return array}> The `where` filters.
*/
@@ -6433,12 +6361,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',
@@ -6449,8 +6371,8 @@ public static function data_where_filters_with_statuses_that_cannot_be_queried()
}
/**
- * Called directly, a status filter with a status that is not registered, or is internal, or
- * with no status left in it, is rejected rather than queried.
+ * Called directly, a status filter with a status that is not registered, or is internal and
+ * not `trash`, or with no status left in it, is rejected rather than queried.
*
* WP_Query ignores a status that is not registered, and with no status left it covers every
* status, including `trash`. A list that is given but empty would fall through to the default
@@ -6864,4 +6786,326 @@ 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 of the shared author in 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['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();
+
+ $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();
+
+ $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.'
+ );
+ }
+
+ /**
+ * 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(
+ 'secondary author' => array( 'role' => 'author_secondary' ),
+ 'contributor' => array( 'role' => '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();
+ 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.'
+ );
+ }
+
+ /**
+ * Returns `where.ids` values that hold no valid ID: no item is a whole number of at least
+ * 1 within the integer range.
+ *
+ * @return array The `where.ids` values.
+ */
+ public static function data_ids_with_no_valid_ids(): array {
+ return array(
+ 'zero' => array(
+ 'ids' => array( 0 ),
+ ),
+ 'fraction' => array(
+ 'ids' => array( 2.5 ),
+ ),
+ 'negative number' => array(
+ 'ids' => array( -5 ),
+ ),
+ 'non-numeric string' => array(
+ 'ids' => 'abc',
+ ),
+ 'beyond the integer range' => array(
+ 'ids' => array( 2 ** 64 + self::ALIASED_POST_ID ),
+ ),
+ );
+ }
+
+ /**
+ * An ids filter that parses to no valid IDs is rejected rather than returning an
+ * unrestricted result set.
+ *
+ * WP_Query ignores an empty `post__in`, so an ids list with no valid IDs would otherwise
+ * return every post of the type — the opposite of the caller's intent. The filter must
+ * fail closed instead, and an ID beyond the integer range must not wrap around onto the
+ * published post whose ID it aliases.
+ *
+ * Keep this test last in the class: the post it creates sets the next post ID above
+ * ALIASED_POST_ID, so the fewer tests run after it, the fewer post IDs later test classes
+ * see shifted.
+ *
+ * @ticket 66268
+ * @dataProvider data_ids_with_no_valid_ids
+ * @since 7.2.0
+ *
+ * @param mixed $ids The `where.ids` value to send.
+ */
+ public function test_execute_callback_rejects_ids_with_no_valid_ids( $ids ): void {
+ $this->login_as( 'administrator' );
+
+ self::factory()->post->create(
+ array(
+ 'import_id' => self::ALIASED_POST_ID,
+ 'post_status' => 'publish',
+ )
+ );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $result = $execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'ids' => $ids,
+ ),
+ )
+ );
+
+ $this->assertWPError( $result, 'An ids filter with no valid IDs must not fall through to an unrestricted query.' );
+ $this->assertSame( 'content_invalid_filter', $result->get_error_code(), 'An empty-after-parsing ids filter should fail closed as an invalid filter.' );
+ $this->assertSame(
+ array( 'where[ids]' => $result->get_error_message() ),
+ $result->get_error_data()['params'],
+ 'The error data should map the ids filter to the error message.'
+ );
+ }
+
+ /**
+ * The `terms` field holds the term IDs of each exposed taxonomy that the post type uses,
+ * with an empty list for a taxonomy in which the post has no terms.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_hold_the_term_ids_by_taxonomy(): void {
+ $category = self::factory()->category->create();
+ $tags = self::factory()->tag->create_many( 2 );
+ $tagged = self::factory()->post->create(
+ array(
+ 'post_status' => 'publish',
+ 'post_category' => array( $category ),
+ 'tags_input' => $tags,
+ )
+ );
+ $untagged = self::factory()->post->create(
+ array(
+ 'post_status' => 'publish',
+ 'post_category' => array( $category ),
+ )
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_ability();
+
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'ids' => array( $tagged, $untagged ),
+ ),
+ 'fields' => array( 'terms' ),
+ )
+ );
+
+ $this->assertIsArray( $result, 'The query should succeed.' );
+
+ $items = array_column( $result['items'], 'terms', 'id' );
+
+ $this->assertSame( array( 'category', 'post_tag' ), array_keys( $items[ $tagged ] ), 'The terms should hold each taxonomy of the post type, in registration order.' );
+ $this->assertSame( array( $category ), $items[ $tagged ]['category'], 'The category should be returned.' );
+ $this->assertEqualsCanonicalizing( $tags, $items[ $tagged ]['post_tag'], 'The tags should be returned.' );
+ $this->assertSame(
+ array(
+ 'category' => array( $category ),
+ 'post_tag' => array(),
+ ),
+ $items[ $untagged ],
+ 'A taxonomy without terms should hold an empty list.'
+ );
+ }
+
+ /**
+ * A query for `terms` primes the term cache of the page, so the terms of every post are
+ * read with one query.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_of_a_page_are_read_with_one_query(): void {
+ $tag = self::factory()->tag->create();
+ $post_ids = array_merge(
+ self::factory()->post->create_many(
+ 3,
+ array(
+ 'post_status' => 'publish',
+ 'tags_input' => array( $tag ),
+ )
+ ),
+ self::factory()->post->create_many( 3, array( 'post_status' => 'publish' ) )
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_ability();
+
+ $term_queries = 0;
+ add_filter(
+ 'query',
+ static function ( $query ) use ( &$term_queries ) {
+ if ( str_contains( $query, 'term_relationships' ) ) {
+ ++$term_queries;
+ }
+
+ return $query;
+ }
+ );
+
+ wp_cache_flush();
+
+ $result = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'ids' => $post_ids,
+ ),
+ 'fields' => array( 'terms.post_tag' ),
+ )
+ );
+
+ $this->assertIsArray( $result, 'The query should succeed.' );
+ $this->assertCount( 6, $result['items'], 'Every post should be returned.' );
+ $this->assertSame( 1, $term_queries, 'The terms of every post should be read with one query.' );
+ }
}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentCreateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentCreateAbility.php
new file mode 100644
index 0000000000000..bbec71fad850d
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentCreateAbility.php
@@ -0,0 +1,1404 @@
+
+ */
+ protected const ANNOTATIONS = array(
+ 'readonly' => false,
+ 'destructive' => false,
+ 'idempotent' => false,
+ );
+
+ /**
+ * Creates shared users and posts.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_UnitTest_Factory $factory The unit test factory.
+ */
+ public static function wpSetUpBeforeClass( $factory ): void {
+ foreach ( self::ROLES as $role ) {
+ self::$user_ids[ $role ] = $factory->user->create( array( 'role' => $role ) );
+ }
+
+ self::create_data_write_fixtures( $factory );
+
+ self::$post_ids['published_post'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'publish',
+ 'post_name' => 'shared-slug',
+ )
+ );
+
+ foreach ( array( 'published_page', 'other_parent_page', 'trashed_page' ) as $key ) {
+ self::$post_ids[ $key ] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ )
+ );
+ }
+ wp_trash_post( self::$post_ids['trashed_page'] );
+
+ // A child page whose `child` slug data_draft_page_slugs_by_parent() reads.
+ $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',
+ )
+ );
+
+ self::create_revision_fixture( $factory );
+ }
+
+ /**
+ * Returns null: the shared tests create a post.
+ *
+ * @since 7.3.0
+ *
+ * @param string $role The role, as a fixture name.
+ * @return null No post ID.
+ */
+ protected function get_write_post_id( string $role ): ?int {
+ return null;
+ }
+
+ /**
+ * Builds the input that creates a post with the given data.
+ *
+ * @since 7.3.0
+ *
+ * @param int|null $post_id Unused: the call creates a post.
+ * @param array $data The data. A type in the data takes the place of `$type`.
+ * @param list|null $fields Optional. The fields, or null for the default. Default null.
+ * @param string $type Optional. The post type. Default 'post'.
+ * @return array The input.
+ */
+ protected function build_write_input( ?int $post_id, array $data, ?array $fields = null, string $type = 'post' ): array {
+ $input = array( 'data' => array_merge( array( 'type' => $type ), $data ) );
+ if ( null !== $fields ) {
+ $input['fields'] = $fields;
+ }
+
+ return $input;
+ }
+
+ /**
+ * Runs the create ability with the given data.
+ *
+ * @since 7.3.0
+ *
+ * @param array $data The data. The type is `post` unless the data names another.
+ * @param list|null $fields Optional. The fields, or null for the default. Default null.
+ * @return mixed The ability result.
+ */
+ private function create_post( array $data, ?array $fields = null ) {
+ return $this->run_ability( $this->build_write_input( null, $data, $fields ) );
+ }
+
+ /**
+ * Asserts that a result is the post item of a successful create and returns the stored post.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param int|null $post_id Optional. Unused: the call created a post. Default null.
+ * @param string $context Optional. What the call was, for the assertion messages. Default 'The create call'.
+ * @return WP_Post The post with the returned ID.
+ */
+ protected function assert_data_written( $result, ?int $post_id = null, string $context = 'The create call' ): WP_Post {
+ $this->assertIsArray( $result, "{$context} should succeed." );
+ $this->assertArrayHasKey( 'id', $result, "{$context} should return the created post with its ID." );
+ $this->assertIsInt( $result['id'], "{$context} should return the ID as an integer." );
+
+ $post = get_post( $result['id'] );
+ $this->assertInstanceOf( WP_Post::class, $post, "{$context} should return the ID of a stored post." );
+
+ return $post;
+ }
+
+ /**
+ * 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 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', 'terms' ), 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->assertSameSets( 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->assertArrayNotHasKey( 'minLength', $properties['slug'], 'The slug should take an empty string, since the update ability shares the data schema and takes the empty slug of a draft back.' );
+ $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.' );
+
+ $terms = $properties['terms'];
+
+ $this->assertSame( 'object', $terms['type'], 'The terms should be an object.' );
+ $this->assertFalse( $terms['additionalProperties'], 'The terms should reject unknown taxonomies.' );
+ $this->assertSame( 1, $terms['minProperties'], 'The terms should hold at least one taxonomy.' );
+ $this->assertSame( array( 'category', 'post_tag' ), array_keys( $terms['properties'] ), 'The terms should take the exposed taxonomies of the exposed post types.' );
+ foreach ( $terms['properties'] as $taxonomy => $term_ids ) {
+ $this->assertSame( 'array', $term_ids['type'], "The {$taxonomy} terms should be a list." );
+ $this->assertTrue( $term_ids['uniqueItems'], "The {$taxonomy} terms should reject duplicate IDs." );
+ $this->assertArrayNotHasKey( 'minItems', $term_ids, "The {$taxonomy} terms should take an empty list, which removes the terms." );
+ $this->assertSame( 'integer', $term_ids['items']['type'], "The {$taxonomy} term IDs should be integers." );
+ $this->assertSame( 1, $term_ids['items']['minimum'], "The {$taxonomy} term IDs should be at least 1." );
+ }
+
+ $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 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_unexposed', 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->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' );
+
+ $result = $this->create_post( array( 'title' => 'Launch notes' ) );
+
+ $post = $this->assert_data_written( $result );
+
+ $this->assertSameSets( array( 'id', 'type', 'status', 'date', 'slug', 'title' ), array_keys( $result ), 'The default fields should be returned.' );
+ $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->create_post(
+ array(
+ 'type' => 'page',
+ 'title' => 'Pricing',
+ 'content' => "\nPlans start at 9 euro per month.
\n",
+ 'status' => 'publish',
+ 'parent' => $parent_id,
+ 'slug' => 'pricing',
+ ),
+ array( 'status', 'link', 'title.rendered', 'content.rendered', 'parent', 'author' )
+ );
+
+ $user = wp_get_current_user();
+ $post = $this->assert_data_written( $result );
+
+ $this->assertSameSets( array( 'id', 'status', 'link', 'title', 'content', 'parent', 'author' ), array_keys( $result ), 'The chosen fields should be returned.' );
+ $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.' );
+ $this->assertSame(
+ array(
+ 'id' => $user->ID,
+ 'name' => $user->display_name,
+ 'slug' => $user->user_nicename,
+ ),
+ $result['author'],
+ 'The current user should be returned as the author.'
+ );
+
+ // The rendered markup comes from the regular content filters, as for any query item.
+ $query = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'page',
+ 'ids' => array( $post->ID ),
+ ),
+ 'fields' => array( 'content.rendered' ),
+ )
+ );
+
+ $this->assertSame( $query['items'][0]['content'] ?? null, $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 users that the permission callback refuses.
+ *
+ * @return array The role, or null to stay logged out.
+ */
+ public static function data_users_refused_by_the_permission_callback(): array {
+ return array(
+ 'logged out' => array( null ),
+ 'subscriber' => array( '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 );
+ }
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( null, array( 'title' => 'Refused' ) ) );
+
+ $this->assert_refused( $result, 'A user who cannot create posts' );
+ }
+
+ /**
+ * 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 data' => array( array() ),
+ 'data that is a string' => array( array( 'data' => 'post' ) ),
+ 'no type' => array( array( 'data' => array( 'title' => 'x' ) ) ),
+ 'type that is a list' => array( array( 'data' => array( 'type' => array( 'post' ) ) ) ),
+ 'type that is a number' => array( array( 'data' => array( 'type' => 1 ) ) ),
+ 'attachment type' => array( array( 'data' => array( 'type' => 'attachment' ) ) ),
+ 'unregistered type' => array( array( 'data' => array( 'type' => 'cw_missing' ) ) ),
+ 'parent that is a word' => array(
+ array(
+ 'data' => array(
+ 'type' => 'page',
+ 'parent' => 'top',
+ ),
+ ),
+ ),
+ 'terms that is a word' => array(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'terms' => 'news',
+ ),
+ ),
+ ),
+ 'tag ID that is a word' => array(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'terms' => array( 'post_tag' => array( 'news' ) ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /**
+ * 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: the role, the
+ * requested status or null to send none, and the stored status or null when the permission
+ * callback refuses the call.
+ *
+ * @return array The cases.
+ */
+ public static function data_create_by_role_and_status(): array {
+ $cases = array();
+ foreach ( array( 'administrator', 'editor', 'author', 'contributor' ) as $role ) {
+ $cases[ "{$role}, no status" ] = array( $role, null, 'draft' );
+ foreach ( array( 'draft', 'pending', 'publish', 'future', 'private' ) as $status ) {
+ // A contributor may only create drafts and pending posts.
+ $cases[ "{$role}, {$status}" ] = array( $role, $status, 'contributor' !== $role || in_array( $status, array( 'draft', 'pending' ), true ) ? $status : null );
+ }
+ }
+
+ return $cases + array(
+ // A custom status that makes a post visible needs `publish_posts`.
+ 'author, cw_public' => array( 'author', 'cw_public', 'cw_public' ),
+ 'author, cw_private' => array( 'author', 'cw_private', 'cw_private' ),
+ 'author, cw_viewable' => array( 'author', 'cw_viewable', 'cw_viewable' ),
+ 'contributor, cw_public' => array( 'contributor', 'cw_public', null ),
+ 'contributor, cw_private' => array( 'contributor', 'cw_private', null ),
+ 'contributor, cw_viewable' => array( 'contributor', 'cw_viewable', null ),
+ // A custom status that is neither public, private, nor publicly viewable needs nothing beyond `create_posts`.
+ 'contributor, cw_hidden' => array( 'contributor', 'cw_hidden', 'cw_hidden' ),
+ );
+ }
+
+ /**
+ * Each role may create posts in the statuses it may set, as their own author.
+ *
+ * `future`, `publish`, `private`, and custom statuses that make a post visible need
+ * `publish_posts`. A scheduled post is sent with a date in the future, and a draft or a
+ * pending post sent without a date has a floating date.
+ *
+ * @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|null $expected The stored status, or null when the call is refused.
+ */
+ public function test_create_by_role_and_status( string $role, ?string $status, ?string $expected ): void {
+ $this->register_custom_statuses();
+
+ $this->login_as( $role );
+
+ $data = array( 'title' => 'Matrix post' );
+ if ( null !== $status ) {
+ $data['status'] = $status;
+ }
+ if ( 'future' === $status ) {
+ $data['date'] = array( 'gmt' => self::FUTURE_GMT );
+ }
+
+ $before = $this->snapshot();
+ $result = $this->create_post( $data, array( 'status' ) );
+
+ if ( null === $expected ) {
+ $this->assert_refused( $result, 'Creating a post in a status the role may not set' );
+ $this->assertSame( $before, $this->snapshot(), 'Nothing should be written.' );
+ return;
+ }
+
+ $post = $this->assert_data_written( $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.' );
+ if ( in_array( $expected, array( 'draft', 'pending' ), true ) ) {
+ $this->assertSame( '0000-00-00 00:00:00', $post->post_date_gmt, 'A draft or a pending post sent without a date should have no GMT date.' );
+ }
+ }
+
+ /**
+ * A permission result that a filter turns into a grant is the final permission decision:
+ * the call runs without a second capability check.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_permission_result_granted_by_a_filter_is_final(): void {
+ $this->login_as( 'contributor' );
+
+ $input = $this->build_write_input(
+ null,
+ array(
+ 'title' => 'Granted by a filter',
+ 'status' => 'publish',
+ )
+ );
+ $this->assert_refused( $this->run_ability( $input ), 'Precondition: a call without the filter' );
+
+ add_filter( 'wp_ability_permission_result', '__return_true' );
+
+ $post = $this->assert_data_written( $this->run_ability( $input ), null, 'A call granted by a filter' );
+
+ $this->assertSame( 'publish', $post->post_status, 'A call granted by a filter should create the post in the sent status.' );
+ }
+
+ /**
+ * 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;
+
+ $input = $this->build_write_input( null, array( 'title' => 'Hidden' ) );
+ $before = $this->snapshot();
+
+ $this->assert_refused( $this->run_ability( $input ), 'The regular call for 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(), '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( array() ),
+ 'no type' => array( array( 'data' => array( 'title' => 'x' ) ) ),
+ 'attachment' => array( array( 'data' => array( 'type' => 'attachment' ) ) ),
+ 'revision' => array( array( 'data' => array( 'type' => 'revision' ) ) ),
+ 'unexposed type' => array( array( 'data' => array( 'type' => 'cw_unexposed' ) ) ),
+ );
+ }
+
+ /**
+ * 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_unexposed', array( 'public' => true ) );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot();
+ $result = $execute( $input );
+
+ $this->assert_not_found( $result, 'A direct call without an exposed type' );
+ $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' );
+
+ $result = $this->run_ability_that_writes_nothing(
+ $this->build_write_input(
+ null,
+ array(
+ 'title' => 'Temporary',
+ 'status' => 'cw_temporary',
+ )
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'status', 'A status that is no longer registered', 'The status must be a registered post status that is not internal.' );
+ }
+
+ /**
+ * Returns authors that a role may name: the role and the author, as fixture names.
+ *
+ * @return array The cases.
+ */
+ public static function data_authors_a_role_may_name(): array {
+ return array(
+ 'oneself without edit_others_posts' => array( 'contributor', 'contributor' ),
+ 'another user with edit_others_posts' => array( 'editor', 'author' ),
+ );
+ }
+
+ /**
+ * A user without `edit_others_posts` may name themselves as the author, and a user with
+ * `edit_others_posts` may name another existing user.
+ *
+ * @ticket 66706
+ * @dataProvider data_authors_a_role_may_name
+ * @since 7.3.0
+ *
+ * @param string $role The role to create as.
+ * @param string $author The author, as a fixture name.
+ */
+ public function test_naming_an_author_the_role_may_name( string $role, string $author ): void {
+ $this->login_as( $role );
+
+ $result = $this->create_post(
+ array(
+ 'title' => 'Named author',
+ 'author' => self::$user_ids[ $author ],
+ )
+ );
+
+ $this->assertSame( self::$user_ids[ $author ], (int) $this->assert_data_written( $result )->post_author, 'The named user should be the author.' );
+ }
+
+ /**
+ * Returns new posts sent with an empty slug: the role to create as, the status, and the
+ * slug the post gets.
+ *
+ * @return array The role, the status, and the stored slug.
+ */
+ public static function data_new_posts_with_an_empty_slug(): array {
+ return array(
+ 'draft' => array( 'author', 'draft', '' ),
+ 'pending post' => array( 'contributor', 'pending', '' ),
+ 'published post' => array( 'author', 'publish', 'empty-slug' ),
+ );
+ }
+
+ /**
+ * An empty slug counts as not sent, since a new post has no slug yet: a draft or a pending
+ * post gets none, also from a user who may not publish posts, and a published post gets its
+ * slug from the title.
+ *
+ * @ticket 66706
+ * @dataProvider data_new_posts_with_an_empty_slug
+ * @since 7.3.0
+ *
+ * @param string $role The role to create as.
+ * @param string $status The status of the new post.
+ * @param string $expected The stored slug.
+ */
+ public function test_empty_slug_counts_as_not_sent( string $role, string $status, string $expected ): void {
+ $this->login_as( $role );
+
+ $result = $this->create_post(
+ array(
+ 'title' => 'Empty slug',
+ 'status' => $status,
+ 'slug' => '',
+ ),
+ array( 'slug' )
+ );
+
+ $this->assertSame( $expected, $this->assert_data_written( $result )->post_name, 'The post should get the slug of a post created without one.' );
+ $this->assertSame( $expected, $result['slug'], 'The stored slug should be returned.' );
+ }
+
+ /**
+ * A readable parent of another type is an invalid parent.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_parent_of_another_type_is_an_invalid_parent(): void {
+ $parent_id = self::$post_ids['published_post'];
+
+ $this->login_as( 'page_writer' );
+
+ $this->assertTrue( current_user_can( 'read_post', $parent_id ), 'Precondition: the user should be able to read the parent.' );
+
+ $result = $this->run_ability_that_writes_nothing(
+ $this->build_write_input(
+ null,
+ array(
+ 'type' => 'page',
+ 'title' => 'Child',
+ 'parent' => $parent_id,
+ )
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'parent', 'A parent of another type', 'The parent must be 0, or a post of the same post type that is neither the post itself nor one of its descendants.' );
+ }
+
+ /**
+ * Returns parents a new page may have: the role to create as, and the parent as a fixture
+ * name, or null for 0.
+ *
+ * @return array The cases.
+ */
+ public static function data_parents_that_can_be_used(): array {
+ return array(
+ 'readable page' => array( 'page_writer', 'published_page' ),
+ 'page in the Trash the user may read' => array( 'editor', 'trashed_page' ),
+ 'top level' => array( 'page_writer', null ),
+ );
+ }
+
+ /**
+ * A readable page of the same type can be the parent, also from the Trash, and a parent of
+ * `0` is accepted.
+ *
+ * @ticket 66706
+ * @dataProvider data_parents_that_can_be_used
+ * @since 7.3.0
+ *
+ * @param string $role The role to create as.
+ * @param string|null $parent_key The parent, as a fixture name, or null for 0.
+ */
+ public function test_parent_is_stored( string $role, ?string $parent_key ): void {
+ $parent_id = null === $parent_key ? 0 : self::$post_ids[ $parent_key ];
+
+ $this->login_as( $role );
+
+ $result = $this->create_post(
+ array(
+ 'type' => 'page',
+ 'title' => 'Child',
+ 'parent' => $parent_id,
+ ),
+ array( 'parent' )
+ );
+
+ $this->assertSame( $parent_id, $this->assert_data_written( $result )->post_parent, 'The parent should be stored.' );
+ $this->assertSame( $parent_id, $result['parent'], 'The parent should be returned.' );
+ }
+
+ /**
+ * Returns attributes that a post type does not support: the post type, the attribute, the
+ * value, the expected error message and, when it is not an administrator, the role of the
+ * current user. An author value is a user and a string parent value is a post, as fixture names.
+ *
+ * @return array The cases.
+ */
+ public static function data_unsupported_attributes(): array {
+ $no_parent = 'The parent attribute is only supported for hierarchical post types.';
+ $no_title = 'The title attribute is only supported for post types that support the title feature.';
+ $no_excerpt = 'The excerpt attribute is only supported for post types that support the excerpt feature.';
+ $no_author = 'The author attribute is only supported for post types that support the author feature.';
+
+ return array(
+ 'excerpt of a page' => array( 'page', 'excerpt', 'An excerpt', $no_excerpt ),
+ 'parent of a post' => array( 'post', 'parent', 1, $no_parent ),
+ 'existing parent of a post' => array( 'post', 'parent', 'published_post', $no_parent ),
+ 'parent 0 of a post' => array( 'post', 'parent', 0, $no_parent ),
+ 'title without title support' => array( 'cw_no_title', 'title', 'A title', $no_title ),
+ 'content without editor support' => array( 'cw_title_only', 'content', 'Some content', 'The content attribute is only supported for post types that support the editor feature.' ),
+ 'excerpt without excerpt support' => array( 'cw_title_only', 'excerpt', 'An excerpt', $no_excerpt ),
+ 'author without author support' => array( 'cw_title_only', 'author', 'administrator', $no_author ),
+ 'another author as an author' => array( 'cw_title_only', 'author', 'editor', $no_author, 'author' ),
+ 'empty title without title support' => array( 'cw_no_title', 'title', '', $no_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.
+ * @param string $message The expected error message.
+ * @param string $role Optional. The role of the current user. Default 'administrator'.
+ */
+ public function test_unsupported_attribute_is_rejected( string $type, string $attribute, $value, string $message, string $role = 'administrator' ): void {
+ $this->register_exposed_post_type( 'cw_no_title', array( 'editor' ) );
+ $this->register_exposed_post_type( 'cw_title_only', array( 'title' ) );
+
+ $this->login_as( $role );
+
+ // The fixtures do not exist yet when the provider runs.
+ if ( 'author' === $attribute ) {
+ $value = self::$user_ids[ $value ];
+ } elseif ( 'parent' === $attribute && is_string( $value ) ) {
+ $value = self::$post_ids[ $value ];
+ }
+
+ $data = array(
+ 'type' => $type,
+ $attribute => $value,
+ );
+ $data[ 'cw_no_title' === $type ? 'content' : 'title' ] = 'Unsupported';
+
+ $result = $this->run_ability_that_writes_nothing( array( 'data' => $data ) );
+
+ $this->assert_invalid_attribute( $result, $attribute, 'An unsupported attribute', $message );
+ }
+
+ /**
+ * 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' );
+
+ $result = $this->create_post(
+ array(
+ 'title' => '',
+ 'content' => 'Only content.',
+ )
+ );
+
+ $post = $this->assert_data_written( $result );
+
+ $this->assertSame( '', $post->post_title, 'The empty title should be stored.' );
+ $this->assertSame( 'Only content.', $post->post_content, 'The content should be stored.' );
+ }
+
+ /**
+ * The `wp_after_insert_post` action fires once, as in any regular save.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_wp_after_insert_post_fires_once(): void {
+ $this->login_as( 'administrator' );
+
+ $before = did_action( 'wp_after_insert_post' );
+
+ $this->assert_data_written( $this->create_post( array( '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 sent and the stored slugs.
+ */
+ 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' );
+
+ $result = $this->create_post(
+ array(
+ 'title' => 'Slug',
+ 'slug' => $slug,
+ ),
+ array( 'slug' )
+ );
+
+ $this->assertSame( $expected, $this->assert_data_written( $result )->post_name, 'The sanitized slug should be stored.' );
+ $this->assertSame( $expected, $result['slug'], 'The stored slug should be returned.' );
+ }
+
+ /**
+ * Returns statuses for which the slug of a new post is made unique against another post.
+ *
+ * @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' );
+
+ $data = array(
+ 'title' => 'Shared',
+ 'slug' => 'shared-slug',
+ );
+ if ( null !== $status ) {
+ $data['status'] = $status;
+ }
+
+ $result = $this->create_post( $data );
+
+ $this->assertSame( 'shared-slug-2', $this->assert_data_written( $result )->post_name, 'The slug should be made unique.' );
+ }
+
+ /**
+ * Returns parents for a draft page with the slug of an existing child page, and the slug the
+ * page is stored with.
+ *
+ * @return array The parents, as fixture names, and the slugs.
+ */
+ 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' ),
+ );
+ }
+
+ /**
+ * The slug of 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' );
+
+ $result = $this->create_post(
+ array(
+ 'type' => 'page',
+ 'title' => 'Child',
+ 'slug' => 'child',
+ 'parent' => self::$post_ids[ $parent_key ],
+ )
+ );
+
+ $this->assertSame( $expected, $this->assert_data_written( $result )->post_name, 'The slug should be unique among the siblings.' );
+ }
+
+ /**
+ * Returns sent dates that all name 2016-12-12 14:00 in America/New_York.
+ *
+ * @return array}> The sent dates.
+ */
+ public static function data_dates(): array {
+ return array(
+ 'site without offset' => array( array( 'site' => '2016-12-12T14:00:00' ) ),
+ 'GMT without offset' => array( array( 'gmt' => '2016-12-12T19:00:00' ) ),
+ 'site with an offset' => array( array( 'site' => '2016-12-12T18:00:00-01:00' ) ),
+ 'GMT with an offset' => array( array( 'gmt' => '2016-12-12T18:00:00-01:00' ) ),
+ 'both, the site wins' => array(
+ array(
+ 'site' => '2016-12-12T14:00:00',
+ 'gmt' => '2001-01-01T00: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.
+ */
+ public function test_date_is_stored_local_and_gmt( array $date ): void {
+ update_option( 'timezone_string', 'America/New_York' );
+
+ $this->login_as( 'administrator' );
+
+ $result = $this->create_post(
+ array(
+ 'title' => 'Dated',
+ 'date' => $date,
+ )
+ );
+
+ $post = $this->assert_data_written( $result );
+
+ $this->assertSame( 'draft', $post->post_status, 'The post should be a draft.' );
+ $this->assertSame( '2016-12-12 14:00:00', $post->post_date, 'The local date should be stored.' );
+ $this->assertSame( '2016-12-12 19:00:00', $post->post_date_gmt, 'The GMT date should be stored.' );
+ }
+
+ /**
+ * 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 {
+ $input = $this->build_write_input( null, array( 'title' => 'Twice' ) );
+
+ $this->login_as( 'author' );
+ $first = $this->run_ability( $input );
+
+ $this->login_as( 'subscriber' );
+ $second = $this->run_ability_that_writes_nothing( $input, null, 'The second call should write nothing.' );
+
+ $this->assertSame( self::$user_ids['author'], (int) $this->assert_data_written( $first )->post_author, 'The first call should create a post for the author.' );
+ $this->assert_refused( $second, 'The second call as a subscriber' );
+ }
+
+ /**
+ * 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->register_abilities();
+
+ get_post_type_object( 'cw_late' )->show_in_abilities = true;
+
+ $this->assert_invalid_input( $this->build_write_input( null, array( 'title' => 'Exposed too late' ), null, 'cw_late' ), null, '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.' );
+
+ $draft = $this->create_post(
+ array(
+ 'type' => 'cw_book',
+ 'title' => 'Draft book',
+ )
+ );
+
+ $post = $this->assert_data_written( $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.' );
+
+ $published = $this->run_ability_that_writes_nothing(
+ $this->build_write_input(
+ null,
+ array(
+ 'type' => 'cw_book',
+ 'title' => 'Published book',
+ 'status' => 'publish',
+ )
+ ),
+ null,
+ 'Nothing should be written for the refused publish.'
+ );
+
+ $this->assert_refused( $published, 'Publishing with only the create capability' );
+ }
+
+ /**
+ * 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_user_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.' );
+
+ $result = $this->run_ability_that_writes_nothing(
+ $this->build_write_input(
+ null,
+ array(
+ 'type' => 'cw_book',
+ 'title' => 'Book',
+ )
+ )
+ );
+
+ $this->assert_refused( $result, 'A user with only the edit capability' );
+ }
+
+ /**
+ * 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 );
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( null, array( 'title' => 'Second site' ) ), null, 'Nothing should be written on the second site.' );
+
+ restore_current_blog();
+
+ $this->assert_refused( $result, 'A call 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 );
+
+ $result = $this->run_ability_that_writes_nothing(
+ $this->build_write_input(
+ null,
+ array(
+ 'title' => 'Second site',
+ 'author' => self::$user_ids['author'],
+ )
+ )
+ );
+
+ restore_current_blog();
+
+ $this->assert_invalid_attribute( $result, 'author', 'An author who is a member of the first site only', 'The author must be an existing user of this site.' );
+ }
+
+ /**
+ * The `terms` attribute and the `terms` output list the taxonomies exposed to abilities
+ * that an exposed post type uses, in registration order.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_list_the_exposed_taxonomies_of_the_exposed_post_types(): void {
+ register_post_type( 'cw_unexposed', array( 'public' => true ) );
+ register_taxonomy( 'cw_genre', 'page', array( 'show_in_abilities' => true ) );
+ register_taxonomy( 'cw_hidden', 'post' );
+ register_taxonomy( 'cw_elsewhere', 'cw_unexposed', array( 'show_in_abilities' => true ) );
+
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The create ability should be registered.' );
+
+ $ability = wp_get_ability( self::ABILITY );
+ $expected = array( 'category', 'post_tag', 'cw_genre' );
+
+ $this->assertSame( $expected, array_keys( $ability->get_input_schema()['properties']['data']['properties']['terms']['properties'] ), 'The terms attribute should take each exposed taxonomy of an exposed post type and no other.' );
+ $this->assertSame( $expected, array_keys( $ability->get_output_schema()['properties']['terms']['properties'] ), 'The terms output should hold each exposed taxonomy of an exposed post type and no other.' );
+
+ $field_paths = $ability->get_input_schema()['properties']['fields']['items']['enum'];
+
+ $this->assertSame( array( 'terms', 'terms.category', 'terms.post_tag', 'terms.cw_genre' ), array_values( preg_grep( '/^terms/', $field_paths ) ), 'The fields should list the terms and the path of each taxonomy.' );
+ }
+
+ /**
+ * Without a taxonomy exposed to abilities, there is no `terms` attribute or output.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_are_left_out_without_an_exposed_taxonomy(): void {
+ foreach ( array( 'category', 'post_tag' ) as $taxonomy ) {
+ get_taxonomy( $taxonomy )->show_in_abilities = false;
+ }
+
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The create ability should be registered.' );
+
+ $ability = wp_get_ability( self::ABILITY );
+
+ $this->assertArrayNotHasKey( 'terms', $ability->get_input_schema()['properties']['data']['properties'], 'The data should not take terms.' );
+ $this->assertArrayNotHasKey( 'terms', $ability->get_output_schema()['properties'], 'The output should not hold terms.' );
+ $this->assertNotContains( 'terms', $ability->get_input_schema()['properties']['fields']['items']['enum'], 'The fields should not list the terms.' );
+ }
+
+ /**
+ * A post created with terms and only some fields returns them, as in the shape's example.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_creates_a_published_post_with_terms(): void {
+ $categories = self::factory()->category->create_many( 2 );
+ $tag = self::factory()->tag->create();
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Beta opens today',
+ 'status' => 'publish',
+ 'terms' => array(
+ 'category' => $categories,
+ 'post_tag' => array( $tag ),
+ ),
+ ),
+ 'fields' => array( 'status', 'slug', 'terms' ),
+ )
+ );
+
+ $post = $this->assert_data_written( $result );
+
+ $this->assertSame( array( 'id', 'status', 'slug', 'terms' ), array_keys( $result ), 'The output should hold the ID and the requested fields.' );
+ $this->assertSame( 'publish', $result['status'], 'The post should be published.' );
+ $this->assertSame( 'beta-opens-today', $result['slug'], 'The slug should come from the title.' );
+ $this->assertEqualsCanonicalizing( $categories, $result['terms']['category'], 'The categories should be returned.' );
+ $this->assertSame( array( $tag ), $result['terms']['post_tag'], 'The tag should be returned.' );
+
+ $query = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'ids' => array( $post->ID ),
+ ),
+ 'fields' => array( 'terms' ),
+ )
+ );
+
+ $this->assertSame( $query['items'][0]['terms'] ?? null, $result['terms'], 'The terms should be the ones the query returns.' );
+ }
+
+ /**
+ * A post created without categories gets the default category, as any saved post does.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_post_created_without_categories_gets_the_default_category(): void {
+ $tag = self::factory()->tag->create();
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'Only tagged',
+ 'terms' => array( 'post_tag' => array( $tag ) ),
+ ),
+ 'fields' => array( 'terms' ),
+ )
+ );
+
+ $this->assert_data_written( $result );
+
+ $this->assertSame(
+ array(
+ 'category' => array( (int) get_option( 'default_category' ) ),
+ 'post_tag' => array( $tag ),
+ ),
+ $result['terms'],
+ 'The post should be in the default category, with the tag.'
+ );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentDeleteAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentDeleteAbility.php
new file mode 100644
index 0000000000000..c82f2670f1f0b
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentDeleteAbility.php
@@ -0,0 +1,406 @@
+
+ */
+ protected const ANNOTATIONS = array(
+ 'readonly' => false,
+ 'destructive' => true,
+ 'idempotent' => true,
+ );
+
+ /**
+ * The input that the shared tests send next to `where`.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected const OTHER_INPUT = array( 'permanent' => true );
+
+ /**
+ * 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' => $this->build_where( $post_id ) );
+ if ( null !== $permanent ) {
+ $input['permanent'] = $permanent;
+ }
+
+ return $input;
+ }
+
+ /**
+ * 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." );
+ $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." );
+ $this->assertNull( get_post( $post_id ), "{$context}: the post should no longer exist." );
+ }
+
+ /**
+ * 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.' );
+ }
+
+ /**
+ * 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.' );
+ $this->assertSame( array( 'trashed', 'deleted' ), $schema['properties']['outcome']['enum'], 'The outcome should be one of trashed and deleted.' );
+ }
+
+ /**
+ * 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->assert_deleted( $this->run_ability( $this->delete_input( $post_id, true ) ), $post_id, 'Deleting a page permanently' );
+ }
+
+ /**
+ * Returns the cases of the capability matrix, each as a trash and as a permanent delete, plus
+ * one that sends `permanent` set to false.
+ *
+ * @return array The cases.
+ */
+ public static function data_delete_matrix(): array {
+ $cases = array(
+ 'administrator, own, publish, permanent false' => array( 'administrator', 'administrator', 'publish', true, false ),
+ );
+ foreach ( self::data_capability_matrix() as $label => $case ) {
+ $cases[ "{$label}, trash" ] = array_merge( $case, array( null ) );
+ $cases[ "{$label}, permanent" ] = array_merge( $case, array( true ) );
+ }
+
+ return $cases;
+ }
+
+ /**
+ * Each role may trash or delete permanently the posts it may delete, and is refused for the
+ * others, whatever their status. A post already in the Trash can be deleted permanently, and
+ * trashing it again is the 410 error. `permanent` set to false also moves the post to the
+ * Trash.
+ *
+ * @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.
+ * @param bool|null $permanent The `permanent` value, or null to send none.
+ */
+ public function test_delete_matrix( string $role, string $owner, string $status, bool $may_delete, ?bool $permanent ): void {
+ $post_id = self::$post_ids[ "{$owner}:{$status}" ];
+ $input = $this->delete_input( $post_id, $permanent );
+
+ $this->login_as( $role );
+
+ if ( $may_delete && $permanent ) {
+ $this->assert_deleted( $this->run_ability( $input ), $post_id, 'Deleting a post the role may delete' );
+ return;
+ }
+
+ if ( $may_delete && ! str_starts_with( $status, 'trash_' ) ) {
+ $this->assert_trashed( $this->run_ability( $input ), $post_id, 'Trashing a post the role may delete' );
+ return;
+ }
+
+ $result = $this->run_ability_that_writes_nothing( $input, $post_id );
+
+ if ( $may_delete ) {
+ $this->assert_error( $result, 'content_already_trashed', 410, 'Trashing a trashed post the role may delete' );
+ $this->assertSame( 'The post has already been trashed.', $result->get_error_message(), 'The message should be the already-trashed message.' );
+ } else {
+ $this->assert_refused( $result, ( $permanent ? 'Deleting' : 'Trashing' ) . ' a post the role may not delete' );
+ }
+ }
+
+ /**
+ * 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->assertFalse( MEDIA_TRASH, 'Precondition: attachments should not support the Trash.' );
+
+ $result = $this->run_ability_that_writes_nothing( $this->delete_input( $post_id ), $post_id, 'A post without Trash support should be left as it was.' );
+
+ $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 true to delete it.', $result->get_error_message(), 'The message should ask for a permanent delete.' );
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( $post_id, true ) ), $post_id, 'Deleting a post without Trash support permanently' );
+ }
+
+ /**
+ * 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' );
+
+ $trash = $this->run_ability_that_writes_nothing( $this->delete_input( $post_id ), $post_id, 'A refused trash should write nothing.' );
+ $permanent = $this->run_ability_that_writes_nothing( $this->delete_input( $post_id, true ), $post_id, 'A refused permanent delete should write nothing.' );
+
+ $this->assert_refused( $trash, 'An editor trashing a special page' );
+ $this->assert_refused( $permanent, 'An editor deleting a special page' );
+ }
+
+ /**
+ * Returns the special pages of the site, each with a trash and a permanent delete.
+ *
+ * @return array The cases.
+ */
+ public static function data_special_page_deletes(): array {
+ return array(
+ 'front page, trash' => array( 'front_page', false ),
+ 'front page, permanent' => array( 'front_page', true ),
+ 'posts page, trash' => array( 'posts_page', false ),
+ 'posts page, permanent' => array( 'posts_page', true ),
+ 'privacy policy page, trash' => array( 'privacy_page', false ),
+ 'privacy policy page, permanent' => array( 'privacy_page', true ),
+ );
+ }
+
+ /**
+ * On a single site an administrator, and on multisite a super admin, may trash the special
+ * pages and delete them permanently.
+ *
+ * The page is not trashed before the permanent delete: trashing the front page or the posts
+ * page clears the option that makes it special.
+ *
+ * @ticket 66706
+ * @dataProvider data_special_page_deletes
+ * @since 7.3.0
+ *
+ * @param string $page The page, as a fixture name.
+ * @param bool $permanent Whether the delete is permanent.
+ */
+ public function test_administrator_or_super_admin_can_delete_a_special_page( string $page, bool $permanent ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $user = 'An administrator';
+ if ( is_multisite() ) {
+ grant_super_admin( self::$user_ids['administrator'] );
+ $user = 'A super admin';
+ }
+
+ $this->login_as( 'administrator' );
+
+ $result = $this->run_ability( $this->delete_input( $post_id, $permanent ) );
+
+ if ( $permanent ) {
+ $this->assert_deleted( $result, $post_id, "{$user} deleting a special page" );
+ } else {
+ $this->assert_trashed( $result, $post_id, "{$user} trashing a special page" );
+ }
+ }
+
+ /**
+ * On multisite, a site administrator may trash the front page and the posts page, but not
+ * the privacy policy page.
+ *
+ * @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_site_administrator_can_trash_special_pages_except_the_privacy_policy_page_on_multisite( string $page ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $this->login_as( 'administrator' );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability( $this->delete_input( $post_id ) );
+
+ if ( 'privacy_page' !== $page ) {
+ $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.' );
+ }
+
+ /**
+ * 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, false ),
+ 'trash, truthy without trashing' => array( false, true ),
+ 'delete, false' => array( true, false ),
+ 'delete, truthy without deleting' => array( true, true ),
+ );
+ }
+
+ /**
+ * When the trash or delete call fails or does not act, the result is the 500 error, which
+ * names the operation that failed, 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 mixed $value The value that the pre-trash or pre-delete filter returns.
+ */
+ public function test_operation_that_does_not_act_is_an_error( bool $permanent, $value ): void {
+ $post_id = self::$post_ids['admin_post'];
+
+ add_filter(
+ $permanent ? 'pre_delete_post' : 'pre_trash_post',
+ static function () use ( $value ) {
+ return $value;
+ }
+ );
+
+ $this->login_as( 'administrator' );
+
+ $result = $this->run_ability_that_writes_nothing( $this->delete_input( $post_id, $permanent ), $post_id );
+
+ $this->assert_error( $result, 'content_delete_failed', 500, 'An operation that does not act' );
+ $this->assertSame( $permanent ? 'The post could not be deleted.' : 'The post could not be moved to the Trash.', $result->get_error_message(), 'The message should name the operation that failed.' );
+ }
+
+ /**
+ * 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 ),
+ );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreContentUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentUpdateAbility.php
new file mode 100644
index 0000000000000..3150c7f82103b
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreContentUpdateAbility.php
@@ -0,0 +1,1996 @@
+
+ */
+ protected const ANNOTATIONS = array(
+ 'readonly' => false,
+ 'destructive' => false,
+ 'idempotent' => true,
+ );
+
+ /**
+ * The input that the shared tests send next to `where`.
+ *
+ * @since 7.3.0
+ *
+ * @var array
+ */
+ protected const OTHER_INPUT = array( 'data' => array( 'title' => 'x' ) );
+
+ /**
+ * Creates shared users and posts.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_UnitTest_Factory $factory The unit test factory.
+ */
+ public static function wpSetUpBeforeClass( $factory ): void {
+ parent::wpSetUpBeforeClass( $factory );
+ self::create_data_write_fixtures( $factory );
+
+ self::$post_ids['publisher:draft'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['publisher'],
+ 'post_status' => 'draft',
+ 'post_title' => 'Publisher draft',
+ 'post_content' => 'Draft body.',
+ )
+ );
+
+ self::$post_ids['page_writer:draft'] = $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['page_writer:draft'],
+ 'post_name' => 'writer-child',
+ )
+ );
+
+ 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'],
+ )
+ );
+
+ // 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',
+ )
+ );
+
+ self::$post_ids['administrator:auto-draft'] = $factory->post->create(
+ array(
+ 'post_author' => self::$user_ids['administrator'],
+ 'post_status' => 'auto-draft',
+ )
+ );
+ }
+
+ /**
+ * Returns the draft of the role, which the shared tests update.
+ *
+ * @since 7.3.0
+ *
+ * @param string $role The role, as a fixture name.
+ * @return int The post ID.
+ */
+ protected function get_write_post_id( string $role ): int {
+ return self::$post_ids[ "{$role}:draft" ];
+ }
+
+ /**
+ * Builds the input that updates a post with the given data.
+ *
+ * @since 7.3.0
+ *
+ * @param int|null $post_id The post ID.
+ * @param array $data The data.
+ * @param list|null $fields Optional. The fields, or null for the default. Default null.
+ * @param string $type Unused: the post keeps its type.
+ * @return array The input.
+ */
+ protected function build_write_input( ?int $post_id, array $data, ?array $fields = null, string $type = 'post' ): array {
+ $input = array(
+ 'where' => $this->build_where( (int) $post_id ),
+ 'data' => $data,
+ );
+ if ( null !== $fields ) {
+ $input['fields'] = $fields;
+ }
+
+ return $input;
+ }
+
+ /**
+ * 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 Optional. The fields, or null for the default. Default null.
+ * @return mixed The ability result.
+ */
+ private function update_post( int $post_id, array $data, ?array $fields = null ) {
+ return $this->run_ability( $this->build_write_input( $post_id, $data, $fields ) );
+ }
+
+ /**
+ * 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|null $post_id The ID of the updated post.
+ * @return WP_Post The stored post.
+ */
+ protected function assert_data_written( $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.' );
+
+ return get_post( $post_id );
+ }
+
+ /**
+ * Sets the timezone of the site to America/New_York and creates a draft with a floating
+ * date, stored in that 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 {
+ update_option( 'timezone_string', 'America/New_York' );
+
+ $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;
+ }
+
+ /**
+ * 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.' );
+
+ $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.'
+ );
+ }
+
+ /**
+ * 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' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => 'Launch notes, updated',
+ 'excerpt' => 'What shipped and what is next.',
+ ),
+ array( 'modified', 'title', 'excerpt' )
+ );
+
+ $this->assert_data_written( $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' );
+
+ $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.'
+ );
+ }
+
+ /**
+ * 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'];
+
+ $input = $this->build_post_input( REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, 'post' );
+ $input['data'] = array(
+ 'status' => 'trash',
+ 'parent' => 1,
+ 'title' => array( 'x' ),
+ );
+
+ $before = $this->snapshot( self::$post_ids['administrator:draft'] );
+ $result = $execute( $input );
+
+ $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.' );
+ }
+
+ /**
+ * 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_capability_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 );
+
+ $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_data_written( $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 keys that are not part of the input, and where they are sent. The shared tests send
+ * the `data` keys that the create ability rejects too.
+ *
+ * @return array The cases.
+ */
+ public static function data_keys_outside_the_allow_list(): array {
+ return array(
+ 'data type' => array( 'data', 'type', 'page' ),
+ 'where status' => array( 'where', 'status', 'draft' ),
+ 'where ID' => array( 'where', 'ID', 1 ),
+ );
+ }
+
+ /**
+ * Returns status changes that a contributor, and an author denied `publish_posts`, may not
+ * make on their own draft, pending post, or post in the Trash, custom public and private
+ * statuses included.
+ *
+ * @return array The cases.
+ */
+ public static function data_status_changes_without_publish_posts(): array {
+ return array(
+ 'publish by a contributor' => array( 'contributor', 'publish' ),
+ 'future by a contributor' => array( 'contributor', 'future' ),
+ 'private by a contributor' => array( 'contributor', 'private' ),
+ 'publish by an author denied publish_posts' => array( 'restricted_author', 'publish' ),
+ 'future by an author denied publish_posts' => array( 'restricted_author', 'future' ),
+ 'private by an author denied publish_posts' => array( 'restricted_author', 'private' ),
+ 'publish from the Trash by a contributor' => array( 'contributor', 'publish', 'trash_draft' ),
+ 'cw_public by a contributor' => array( 'contributor', 'cw_public', 'draft', true ),
+ 'cw_private by a contributor' => array( 'contributor', 'cw_private', 'draft', true ),
+ 'cw_public from pending by a contributor' => array( 'contributor', 'cw_public', 'pending', true ),
+ 'cw_private from pending by a contributor' => array( 'contributor', 'cw_private', 'pending', true ),
+ 'cw_public from the Trash by a contributor' => array( 'contributor', 'cw_public', 'trash_draft', true ),
+ 'cw_private from the Trash by a contributor' => array( 'contributor', 'cw_private', 'trash_draft', true ),
+ );
+ }
+
+ /**
+ * A status that makes a post visible, a custom public or private status included, needs
+ * `publish_posts`, also to move a post out of the Trash.
+ *
+ * @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 post.
+ * @param string $status The status.
+ * @param string $stored Optional. The matrix status of the post. Default 'draft'.
+ * @param bool $custom_statuses Optional. Whether to register the custom statuses first. Default false.
+ */
+ public function test_status_that_makes_a_post_visible_needs_publish_posts( string $role, string $status, string $stored = 'draft', bool $custom_statuses = false ): void {
+ if ( $custom_statuses ) {
+ $this->register_custom_statuses();
+ }
+
+ $post_id = self::$post_ids[ "{$role}:{$stored}" ];
+
+ $this->login_as( $role );
+
+ $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' => self::FUTURE_GMT );
+ }
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, $data ), $post_id );
+
+ $this->assert_refused( $result, 'A status that makes a post visible without publish_posts' );
+ }
+
+ /**
+ * 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' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => 'private',
+ 'title' => 'Still private',
+ )
+ );
+
+ $post = $this->assert_data_written( $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' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => 'future',
+ 'date' => array( 'gmt' => self::FUTURE_GMT ),
+ ),
+ array( 'status', 'date' )
+ );
+
+ $post = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( 'future', $post->post_status, 'The post should be scheduled.' );
+ $this->assertSame( str_replace( 'T', ' ', self::FUTURE_GMT ), $post->post_date_gmt, 'The post should be scheduled for the sent date.' );
+ $this->assertSame( 'future', $result['status'], 'The scheduled status should be returned.' );
+ $this->assertSame( self::FUTURE_GMT . '+00:00', $result['date']['gmt'], 'The sent date should be returned.' );
+ }
+
+ /**
+ * Returns status changes that unpublish a post, move a post out of the Trash, or move a draft
+ * to `pending` or to a hidden custom status without `publish_posts`.
+ *
+ * @return array The cases.
+ */
+ public static function data_status_changes(): array {
+ return array(
+ 'draft from publish by an editor' => array( 'editor', 'publish', 'draft' ),
+ 'pending from publish by an editor' => array( 'editor', 'publish', 'pending' ),
+ 'draft from the Trash by a contributor' => array( 'contributor', 'trash_draft', 'draft' ),
+ 'pending from the Trash by an author' => array( 'author', 'trash_draft', 'pending' ),
+ 'publish from the Trash by an author' => array( 'author', 'trash_draft', 'publish' ),
+ 'pending from a draft without publish_posts' => array( 'restricted_author', 'draft', 'pending' ),
+ 'cw_hidden from a draft by a contributor' => array( 'contributor', 'draft', 'cw_hidden', true ),
+ );
+ }
+
+ /**
+ * A published post can be unpublished, sending a status moves a post out of the Trash
+ * through a plain update, and a user without `publish_posts` may still move their own
+ * draft to `pending` or to a hidden custom status.
+ *
+ * @ticket 66706
+ * @dataProvider data_status_changes
+ * @since 7.3.0
+ *
+ * @param string $role The user, who owns the post, as a fixture name.
+ * @param string $stored The matrix status of the post.
+ * @param string $status The sent status.
+ * @param bool $custom_statuses Optional. Whether to register the custom statuses first. Default false.
+ */
+ public function test_status_change_is_stored( string $role, string $stored, string $status, bool $custom_statuses = false ): void {
+ if ( $custom_statuses ) {
+ $this->register_custom_statuses();
+ }
+
+ $post_id = self::$post_ids[ "{$role}:{$stored}" ];
+
+ $this->login_as( $role );
+
+ $result = $this->update_post( $post_id, array( 'status' => $status ), array( 'status' ) );
+
+ $this->assertSame( $status, $this->assert_data_written( $result, $post_id )->post_status, 'The post should be stored in the sent status.' );
+ $this->assertSame( $status, $result['status'], 'The new status should be returned.' );
+ }
+
+ /**
+ * 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' );
+
+ $result = $this->update_post( $post_id, array( 'author' => self::$user_ids['author'] ), array( 'author.id' ) );
+
+ $this->assertSame( self::$user_ids['author'], (int) $this->assert_data_written( $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' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER ), array( 'ID' => $post_id ) );
+ clean_post_cache( $post_id );
+
+ $this->login_as( 'editor' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'author' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER,
+ 'title' => 'Orphan',
+ )
+ );
+
+ $post = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( 'Orphan', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, (int) $post->post_author, 'The stored author should not change.' );
+ }
+
+ /**
+ * Returns readable 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(
+ 'post of another type' => array( 'admin_post' ),
+ 'the page itself' => array( 'page_writer:draft' ),
+ 'a child' => array( 'writer_child' ),
+ 'a grandchild' => array( 'writer_grandchild' ),
+ );
+ }
+
+ /**
+ * A readable parent of another type and a parent that would make a loop are invalid parents
+ * with 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_is_an_invalid_parent( string $parent_key ): void {
+ $post_id = self::$post_ids['page_writer:draft'];
+
+ $this->login_as( 'page_writer' );
+
+ $this->assertTrue( current_user_can( 'edit_post', $post_id ), 'Precondition: the user should be able to edit the page.' );
+ $this->assertTrue( current_user_can( 'read_post', self::$post_ids[ $parent_key ] ), 'Precondition: the user should be able to read the parent.' );
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, array( 'parent' => self::$post_ids[ $parent_key ] ) ), $post_id );
+
+ $this->assert_invalid_attribute( $result, 'parent', 'A parent that cannot be used', 'The parent must be 0, or a post of the same post type that is neither the post itself nor one of its descendants.' );
+ }
+
+ /**
+ * 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' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'parent' => self::$post_ids['editor_draft_page'],
+ 'title' => 'Same parent',
+ )
+ );
+
+ $post = $this->assert_data_written( $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' );
+
+ $result = $this->update_post( $post_id, array( 'parent' => $parent_id ), array( 'parent' ) );
+
+ $this->assertSame( $parent_id, $this->assert_data_written( $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' );
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, array( $attribute => $value ) ), $post_id );
+
+ $this->assert_invalid_attribute( $result, $attribute, 'An unsupported attribute' );
+ }
+
+ /**
+ * 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' );
+
+ $post = $this->assert_data_written( $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.' );
+ }
+
+ /**
+ * Returns posts with an empty slug and the role of their author.
+ *
+ * @return array The role and the post, as a fixture name.
+ */
+ public static function data_posts_with_an_empty_slug(): array {
+ return array(
+ 'draft' => array( 'author', 'author:draft' ),
+ 'pending post' => array( 'contributor', 'contributor:pending' ),
+ );
+ }
+
+ /**
+ * The empty slug of a draft or a pending post, as the query returns it, can be sent back,
+ * also by a user who may not publish the post.
+ *
+ * @ticket 66706
+ * @dataProvider data_posts_with_an_empty_slug
+ * @since 7.3.0
+ *
+ * @param string $role The role of the author of the post.
+ * @param string $post The post, as a fixture name.
+ */
+ public function test_empty_slug_of_a_post_without_a_slug_can_be_sent_back( string $role, string $post ): void {
+ $post_id = self::$post_ids[ $post ];
+
+ $this->assertSame( '', get_post( $post_id )->post_name, 'Precondition: the post should have no slug.' );
+
+ $this->login_as( $role );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => 'Round trip',
+ 'slug' => '',
+ ),
+ array( 'slug' )
+ );
+
+ $stored = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( 'Round trip', $stored->post_title, 'The title should be stored.' );
+ $this->assertSame( '', $stored->post_name, 'The post should still have no slug.' );
+ $this->assertSame( '', $result['slug'], 'The empty slug should be returned.' );
+ }
+
+ /**
+ * An empty slug sent for a post that has a slug is an invalid slug.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_empty_slug_of_a_post_with_a_slug_is_an_invalid_slug(): void {
+ $post_id = self::$post_ids['author:publish'];
+
+ $this->assertNotSame( '', get_post( $post_id )->post_name, 'Precondition: the post should have a slug.' );
+
+ $this->login_as( 'author' );
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, array( 'slug' => '' ) ), $post_id );
+
+ $this->assert_invalid_attribute( $result, 'slug', 'An empty slug', 'The slug must contain characters that are valid in a slug.' );
+ }
+
+ /**
+ * A user who may not publish the post cannot set the slug of a post that is already pending.
+ *
+ * Intentionally strict: the save would drop the slug, so the call is refused instead of the
+ * slug being dropped without notice.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_of_a_stored_pending_post_is_refused_without_publish_posts(): void {
+ $post_id = self::$post_ids['contributor:pending'];
+
+ $this->login_as( 'contributor' );
+
+ $result = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, array( 'slug' => 'pending-slug' ) ), $post_id, 'Nothing should be written for a slug that cannot be stored.' );
+
+ $this->assert_refused( $result, 'A slug on a stored pending post without publish_posts' );
+ }
+
+ /**
+ * A user who may publish the post sets the slug of a post that is already pending.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_slug_of_a_stored_pending_post_is_stored_with_publish_posts(): void {
+ $post_id = self::$post_ids['contributor:pending'];
+
+ $this->login_as( 'editor' );
+
+ $result = $this->update_post( $post_id, array( 'slug' => 'pending-slug' ), array( 'slug' ) );
+ $stored = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( 'pending', $stored->post_status, 'The post should stay pending.' );
+ $this->assertSame( 'pending-slug', $stored->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 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 auto-draft' => array( 'administrator:auto-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, an auto-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' );
+
+ $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_data_written( $result, $post_id )->post_name, 'The sanitized slug should be made unique.' );
+ $this->assertSame( 'shared-slug-2', $result['slug'], 'The unique slug should be returned.' );
+ }
+
+ /**
+ * Returns parents for a draft page that takes the slug of `writer_child`, a child page of
+ * `page_writer:draft`.
+ *
+ * @return array The cases.
+ */
+ public static function data_draft_page_slugs_by_parent(): array {
+ return array(
+ 'shared parent sent' => array( 'page_writer:draft', 'writer-child-2' ),
+ 'different parent sent' => array( 'admin_page', 'writer-child' ),
+ );
+ }
+
+ /**
+ * The slug of 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 {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'draft',
+ 'post_title' => 'Moving page',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'slug' => 'writer-child',
+ 'parent' => self::$post_ids[ $parent_key ],
+ )
+ );
+
+ $this->assertSame( $expected, $this->assert_data_written( $result, $post_id )->post_name, 'The slug should be unique among the siblings.' );
+ }
+
+ /**
+ * Returns updates without a new date of a floating draft, 2099-01-15 10:00 in
+ * America/New_York, with the status they store.
+ *
+ * The date is in winter because PHP versions before 8.1 apply no daylight saving time
+ * after 2037.
+ *
+ * @return array, 1: string}> The data, and the stored status.
+ */
+ public static function data_updates_without_a_new_date_of_a_floating_draft(): array {
+ return array(
+ 'title' => array( array( 'title' => 'Still floating' ), 'draft' ),
+ 'pending' => array( array( 'status' => 'pending' ), 'pending' ),
+ 'title with the site date it shows' => array(
+ array(
+ 'date' => array( 'site' => '2099-01-15T10:00:00' ),
+ 'title' => 'Same date',
+ ),
+ 'draft',
+ ),
+ 'title with the GMT date it shows' => array(
+ array(
+ 'date' => array( 'gmt' => '2099-01-15T15:00:00' ),
+ 'title' => 'Same date',
+ ),
+ 'draft',
+ ),
+ );
+ }
+
+ /**
+ * An update without a date keeps a floating draft floating, also when it moves the draft
+ * to pending. Sending back the date the draft shows counts as not sent and never pins it.
+ *
+ * @ticket 66706
+ * @dataProvider data_updates_without_a_new_date_of_a_floating_draft
+ * @since 7.3.0
+ *
+ * @param array $data The data.
+ * @param string $status The stored status.
+ */
+ public function test_update_without_a_new_date_keeps_a_draft_floating( array $data, string $status ): void {
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+
+ $post = $this->assert_data_written( $this->update_post( $post_id, $data ), $post_id );
+
+ $this->assertSame( $status, $post->post_status, "The post should be stored as {$status}." );
+ $this->assertSame( '0000-00-00 00:00:00', $post->post_date_gmt, 'The post should keep floating.' );
+ }
+
+ /**
+ * Returns updates that publish a floating draft with a past local date, 2020-01-01 10:00 in
+ * America/New_York: a status that does not float, sent without a date, and `publish` sent
+ * with the date the draft shows.
+ *
+ * @return array}> The data.
+ */
+ public static function data_updates_that_stamp_the_current_time(): array {
+ return array(
+ 'publish without a date' => array( array( 'status' => 'publish' ) ),
+ 'future without a date' => array( array( 'status' => 'future' ) ),
+ 'publish with the shown site date' => array(
+ array(
+ 'date' => array( 'site' => '2020-01-01T10:00:00' ),
+ 'status' => 'publish',
+ ),
+ ),
+ 'publish with the shown GMT date' => array(
+ array(
+ 'date' => array( 'gmt' => '2020-01-01T15:00:00' ),
+ 'status' => 'publish',
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Publishing a floating draft with a past local date stamps the current time: without a
+ * date, also when it is sent as scheduled, and with the date it shows, as if no date was
+ * sent.
+ *
+ * @ticket 66706
+ * @dataProvider data_updates_that_stamp_the_current_time
+ * @since 7.3.0
+ *
+ * @param array $data The data.
+ */
+ public function test_publishing_a_floating_draft_with_a_past_date_stamps_the_current_time( array $data ): void {
+ $post_id = $this->create_floating_draft( '2020-01-01 10:00:00' );
+
+ $this->login_as( 'editor' );
+
+ $post = $this->assert_data_written( $this->update_post( $post_id, $data ), $post_id );
+
+ $this->assertSame( 'publish', $post->post_status, 'The post should be published.' );
+ $this->assertEqualsWithDelta( time(), strtotime( $post->post_date_gmt . ' UTC' ), 60, 'The GMT date should be the current time.' );
+ }
+
+ /**
+ * 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',
+ ),
+ ),
+ );
+ }
+
+ /**
+ * The date that core/content-query returns can be sent back after the site's timezone
+ * changed, when its `site` and `gmt` dates name different times: `site` wins, and as it
+ * equals the stored local date, the stored dates are kept.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_queried_date_can_be_sent_back_after_a_timezone_change(): void {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['editor'],
+ 'post_status' => 'publish',
+ 'post_date' => '2017-01-01 10:00:00',
+ 'post_date_gmt' => '2017-01-01 10:00:00',
+ )
+ );
+
+ update_option( 'timezone_string', 'Europe/Paris' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $queried = wp_get_ability( 'core/content-query' )->execute(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'ids' => array( $post_id ),
+ ),
+ 'fields' => array( 'date' ),
+ )
+ );
+
+ $this->assertIsArray( $queried, 'The query should succeed.' );
+ $date = $queried['items'][0]['date'];
+ $this->assertSame(
+ array(
+ 'site' => '2017-01-01T10:00:00+01:00',
+ 'gmt' => '2017-01-01T10:00:00+00:00',
+ ),
+ $date,
+ 'Precondition: the queried `site` and `gmt` dates should name different times.'
+ );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => 'Round trip',
+ 'date' => $date,
+ )
+ );
+
+ $post = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( 'Round trip', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( '2017-01-01 10:00:00', $post->post_date, 'The local date should be kept.' );
+ $this->assertSame( '2017-01-01 10:00:00', $post->post_date_gmt, 'The GMT date should be kept.' );
+ }
+
+ /**
+ * 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' );
+
+ $post = $this->assert_data_written( $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.' );
+ }
+
+ /**
+ * A new date pins a floating draft.
+ *
+ * @ticket 66706
+ * @dataProvider data_new_dates
+ * @since 7.3.0
+ *
+ * @param array $date The sent date.
+ */
+ public function test_new_date_pins_a_floating_draft( array $date ): void {
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+
+ $post = $this->assert_data_written( $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 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 {
+ $post_id = $this->create_floating_draft( '2099-01-15 10:00:00' );
+
+ $this->login_as( 'editor' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'date' => $date,
+ 'status' => $status,
+ ),
+ array( 'status' )
+ );
+ $post = $this->assert_data_written( $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 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' );
+
+ $result = $this->update_post( $post_id, array( 'content' => 'Protected body.' ), array( 'content.raw', 'content.protected' ) );
+
+ $this->assert_data_written( $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 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 = $this->build_write_input( $post_id, array( 'title' => 'Visibility' ), 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 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' );
+
+ $post = $this->assert_data_written( $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 `wp_after_insert_post` action fires once for the updated post, as in any regular save.
+ *
+ * A save that stores a revision also fires the action for the revision, so only the fires
+ * for the updated post are counted.
+ *
+ * @ticket 66706
+ * @since 7.3.0
+ */
+ public function test_wp_after_insert_post_fires_once(): void {
+ $post_id = self::$post_ids['administrator:draft'];
+ $fires = array();
+ add_action(
+ 'wp_after_insert_post',
+ static function ( $id ) use ( &$fires ): void {
+ $fires[] = (int) $id;
+ }
+ );
+
+ $this->login_as( 'administrator' );
+
+ $this->assert_data_written( $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.' );
+ }
+
+ /**
+ * Returns internal statuses that a post can be stored in, with a post stored in each.
+ *
+ * @return array The statuses, and the posts, as fixture names.
+ */
+ public static function data_internal_stored_statuses(): array {
+ return array(
+ 'trash' => array( 'trash', 'administrator:trash_publish' ),
+ 'auto-draft' => array( 'auto-draft', 'administrator: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.
+ * @param string $post The post stored in the status, as a fixture name.
+ */
+ public function test_direct_call_rejects_an_internal_status_the_post_already_has( string $status, string $post ): void {
+ $post_id = self::$post_ids[ $post ];
+
+ $this->assertSame( $status, get_post_status( $post_id ), 'Precondition: the post should be stored in the status.' );
+
+ $this->login_as( 'administrator' );
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $before = $this->snapshot( $post_id );
+ $result = $execute( $this->build_write_input( $post_id, array( 'status' => $status ) ) );
+
+ $this->assert_invalid_attribute( $result, 'status', 'A direct call with the internal status the post already has', 'The status must be a registered post status that is not internal.' );
+ $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' );
+
+ $post = $this->assert_data_written(
+ $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.' );
+ }
+
+ /**
+ * 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 = '2099-01-15T12: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, past date' => array( 'publish', false, $past, 'publish' ),
+ 'scheduled post, past date' => 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->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_data_written( $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', '2099-01-15T12:00:00' ),
+ 'scheduled post to publish, past date' => 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->assertFalse( current_user_can( 'publish_posts' ), 'Precondition: the user should not be able to publish posts.' );
+
+ $input = $this->build_write_input(
+ $post_id,
+ array(
+ 'status' => $status,
+ 'date' => array( 'gmt' => $date ),
+ )
+ );
+ $result = $this->run_ability_that_writes_nothing( $input, $post_id );
+
+ $this->assert_refused( $result, 'A published or scheduled post moved to the other status without publish_posts' );
+ }
+
+ /**
+ * Logs in as the subscriber and grants them `edit_post` and `read_post` on the draft of the
+ * `other` editor through `map_meta_cap`, while that post is a draft.
+ *
+ * @since 7.3.0
+ *
+ * @return int The ID of the granted draft.
+ */
+ private function login_as_subscriber_granted_one_draft(): int {
+ $user_id = self::$user_ids['subscriber'];
+ $post_id = self::$post_ids['other:draft'];
+
+ add_filter(
+ 'map_meta_cap',
+ static function ( $caps, $cap, $cap_user_id, $args ) use ( $user_id, $post_id ) {
+ if (
+ in_array( $cap, array( 'edit_post', 'read_post' ), true )
+ && $user_id === (int) $cap_user_id
+ && isset( $args[0] ) && $post_id === (int) $args[0]
+ && 'draft' === get_post_status( $post_id )
+ ) {
+ return array( 'read' );
+ }
+
+ return $caps;
+ },
+ 10,
+ 4
+ );
+ $this->login_as( 'subscriber' );
+
+ return $post_id;
+ }
+
+ /**
+ * 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 {
+ $post_id = $this->login_as_subscriber_granted_one_draft();
+ $other_id = self::$post_ids['editor:draft'];
+
+ $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.' );
+
+ $updated = $this->update_post( $post_id, array( 'title' => 'Granted title' ) );
+
+ $this->assertSame( 'Granted title', $this->assert_data_written( $updated, $post_id )->post_title, 'The title of the granted post should be stored.' );
+
+ $other = $this->run_ability_that_writes_nothing( $this->build_write_input( $other_id, array( 'title' => 'Not granted' ) ), $other_id, 'Nothing should be written for the post that is not granted.' );
+
+ $this->assert_refused( $other, 'Updating a post that is not granted' );
+
+ $publish = $this->run_ability_that_writes_nothing( $this->build_write_input( $post_id, array( 'status' => 'publish' ) ), $post_id, 'Nothing should be written for the refused publish.' );
+
+ $this->assert_refused( $publish, 'Publishing the granted post' );
+ }
+
+ /**
+ * An editor may update the title of the front page and of the posts page, but not 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_may_update_a_special_page_other_than_the_privacy_policy_page( string $page ): void {
+ $this->set_special_pages();
+ $post_id = self::$post_ids[ $page ];
+
+ $this->login_as( 'editor' );
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'title' => 'Special page' ) );
+
+ if ( 'privacy_page' === $page ) {
+ $this->assert_refused( $result, 'An editor updating the privacy policy page' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ return;
+ }
+
+ $this->assertSame( 'Special page', $this->assert_data_written( $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' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER,
+ )
+ );
+
+ $this->assertSame( REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, get_post( $post_id )->post_parent, 'Precondition: the page should keep the missing parent.' );
+ $this->assertNull( get_post( REST_TESTS_IMPOSSIBLY_HIGH_NUMBER ), 'Precondition: the parent should not exist.' );
+
+ $this->login_as( 'page_writer' );
+
+ $data = array( 'title' => 'Orphan' );
+ if ( $send_parent ) {
+ $data['parent'] = REST_TESTS_IMPOSSIBLY_HIGH_NUMBER;
+ }
+
+ $post = $this->assert_data_written( $this->update_post( $post_id, $data ), $post_id );
+
+ $this->assertSame( 'Orphan', $post->post_title, 'The title should be stored.' );
+ $this->assertSame( REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, $post->post_parent, 'The stored parent should not change.' );
+ }
+
+ /**
+ * 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 {
+ $post_id = $this->login_as_subscriber_granted_one_draft();
+
+ $this->assertTrue( current_user_can( 'edit_post', $post_id ), 'Precondition: the user should be able to edit the draft.' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'status' => 'pending',
+ 'title' => 'Out of reach',
+ ),
+ array( 'title.rendered', 'status', 'content.rendered' )
+ );
+
+ $post = $this->assert_data_written( $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 ), '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 {
+ $post_id = $this->login_as_subscriber_granted_one_draft();
+
+ $result = $this->update_post( $post_id, array( 'title' => 'Still a draft' ), array( 'title.rendered', 'status' ) );
+
+ $this->assert_data_written( $result, $post_id );
+ $this->assertTrue( current_user_can( 'read_post', $post_id ), 'The user should still be able to read the post.' );
+
+ $this->assertSameSetsWithIndex(
+ array(
+ 'id' => $post_id,
+ 'status' => 'draft',
+ 'title' => array( 'rendered' => 'Still a draft' ),
+ ),
+ $result,
+ 'The output should hold the ID and the requested fields.'
+ );
+ }
+
+ /**
+ * Returns malformed `terms`, which only a direct call can send.
+ *
+ * @return array The terms.
+ */
+ public static function data_malformed_terms(): array {
+ return array(
+ 'terms that is a word' => array( 'news' ),
+ 'term ID that is a word' => array( array( 'post_tag' => array( 'news' ) ) ),
+ 'term ID that is negative' => array( array( 'post_tag' => array( -1 ) ) ),
+ 'term IDs that are objects' => array( array( 'post_tag' => array( array( 'id' => 1 ) ) ) ),
+ );
+ }
+
+ /**
+ * The permission callback returns false for malformed `terms`.
+ *
+ * @ticket 66904
+ * @dataProvider data_malformed_terms
+ * @since 7.3.0
+ *
+ * @param mixed $terms The terms.
+ */
+ public function test_permission_callback_returns_false_for_malformed_terms( $terms ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $this->build_write_input( self::$post_ids['admin_post'], array( 'terms' => $terms ) ) ), 'The permission callback should return false.' );
+ }
+
+ /**
+ * The terms of each taxonomy sent replace the stored ones, an empty list removes them, and
+ * a taxonomy left out keeps its terms.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_replace_the_terms_of_each_taxonomy_sent(): void {
+ $category = self::factory()->category->create();
+ $tags = self::factory()->tag->create_many( 3 );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$user_ids['author'],
+ 'post_category' => array( $category ),
+ 'tags_input' => array_slice( $tags, 0, 2 ),
+ )
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->update_post( $post_id, array( 'terms' => array( 'post_tag' => array( $tags[1], $tags[2] ) ) ), array( 'terms' ) );
+
+ $this->assert_data_written( $result, $post_id );
+ $this->assertSame( array( $category ), $this->get_stored_term_ids( $post_id, 'category' ), 'The category should be kept.' );
+ $this->assertSame( array( $tags[1], $tags[2] ), $this->get_stored_term_ids( $post_id, 'post_tag' ), 'The tags should be replaced.' );
+ $this->assertSame( array( $category ), $result['terms']['category'], 'The output should hold the kept category.' );
+ $this->assertEqualsCanonicalizing( array( $tags[1], $tags[2] ), $result['terms']['post_tag'], 'The output should hold the new tags.' );
+
+ $result = $this->update_post( $post_id, array( 'terms' => array( 'post_tag' => array() ) ), array( 'terms' ) );
+
+ $this->assert_data_written( $result, $post_id );
+ $this->assertSame( array(), $this->get_stored_term_ids( $post_id, 'post_tag' ), 'The tags should be removed.' );
+ $this->assertSame(
+ array(
+ 'category' => array( $category ),
+ 'post_tag' => array(),
+ ),
+ $result['terms'],
+ 'The output should hold the kept category and no tag.'
+ );
+ }
+
+ /**
+ * Terms equal to the stored ones, in any order, change nothing and pass with no check.
+ *
+ * The author may not assign terms of the restricted taxonomy, and neither sends its terms
+ * back nor removes the ones the post does not have.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_terms_equal_to_the_stored_terms_pass_with_no_check(): void {
+ $term_ids = array( $this->register_restricted_taxonomy(), self::factory()->term->create( array( 'taxonomy' => 'cw_restricted' ) ) );
+ $post_id = self::factory()->post->create( array( 'post_author' => self::$user_ids['author'] ) );
+ $empty_id = self::factory()->post->create( array( 'post_author' => self::$user_ids['author'] ) );
+ wp_set_object_terms( $post_id, $term_ids, 'cw_restricted' );
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $this->assertFalse( current_user_can( get_taxonomy( 'cw_restricted' )->cap->assign_terms ), 'Precondition: the author should not be able to assign the terms.' );
+
+ $result = $this->update_post(
+ $post_id,
+ array(
+ 'title' => 'Same terms',
+ 'terms' => array( 'cw_restricted' => array_reverse( $term_ids ) ),
+ )
+ );
+
+ $post = $this->assert_data_written( $result, $post_id );
+
+ $this->assertSame( 'Same terms', $post->post_title, 'The title should be stored.' );
+ $this->assertEqualsCanonicalizing( $term_ids, $this->get_stored_term_ids( $post_id, 'cw_restricted' ), 'The terms should be kept.' );
+
+ $result = $this->update_post(
+ $empty_id,
+ array(
+ 'title' => 'Still no terms',
+ 'terms' => array( 'cw_restricted' => array() ),
+ )
+ );
+
+ $this->assertSame( 'Still no terms', $this->assert_data_written( $result, $empty_id )->post_title, 'The title should be stored.' );
+ }
+
+ /**
+ * Removing the terms of a taxonomy needs the capability to assign its terms.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_removing_terms_the_user_may_not_assign_is_refused(): void {
+ $term_id = $this->register_restricted_taxonomy();
+ $post_id = self::factory()->post->create( array( 'post_author' => self::$user_ids['author'] ) );
+ wp_set_object_terms( $post_id, array( $term_id ), 'cw_restricted' );
+
+ $this->login_as( 'author' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->update_post( $post_id, array( 'terms' => array( 'cw_restricted' => array() ) ) );
+
+ $this->assert_refused( $result, 'Removing terms the user may not assign' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Terms of a taxonomy that the post type does not use are refused even when the list is
+ * empty, so it would change nothing.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_empty_terms_of_a_taxonomy_the_post_type_does_not_use_are_an_invalid_attribute(): void {
+ $post_id = self::$post_ids['editor_draft_page'];
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $before = $this->snapshot( $post_id );
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'type' => 'page',
+ 'id' => $post_id,
+ ),
+ 'data' => array( 'terms' => array( 'category' => array() ) ),
+ )
+ );
+
+ $this->assert_invalid_attribute( $result, 'terms', 'Terms of a taxonomy pages do not use', 'The category taxonomy is not used by the post type.' );
+ $this->assertSame( $before, $this->snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * The terms are stored before the save hooks of the post run, so the hooks read the new
+ * terms.
+ *
+ * @ticket 66904
+ * @since 7.3.0
+ */
+ public function test_save_hooks_read_the_new_terms(): void {
+ $tag = self::factory()->tag->create();
+ $post_id = self::$post_ids['editor:draft'];
+ $read = array();
+
+ add_action(
+ 'save_post',
+ static function ( $id ) use ( &$read, $post_id ): void {
+ if ( $post_id === $id ) {
+ $read['save_post'] = wp_get_object_terms( $id, 'post_tag', array( 'fields' => 'ids' ) );
+ }
+ }
+ );
+ add_action(
+ 'wp_after_insert_post',
+ static function ( $id ) use ( &$read, $post_id ): void {
+ if ( $post_id === $id ) {
+ $read['wp_after_insert_post'] = wp_get_object_terms( $id, 'post_tag', array( 'fields' => 'ids' ) );
+ }
+ }
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assert_data_written( $this->update_post( $post_id, array( 'terms' => array( 'post_tag' => array( $tag ) ) ) ), $post_id );
+
+ $this->assertSame(
+ array(
+ 'save_post' => array( $tag ),
+ 'wp_after_insert_post' => array( $tag ),
+ ),
+ $read,
+ 'Both hooks should read the new tag.'
+ );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreTermCreateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermCreateAbility.php
new file mode 100644
index 0000000000000..822e5e4e71553
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermCreateAbility.php
@@ -0,0 +1,1067 @@
+ $data The attributes next to the taxonomy.
+ * @param list|null $fields Optional. The requested fields. Default null.
+ * @return array The input.
+ */
+ private function create_input( string $taxonomy, array $data, ?array $fields = null ): array {
+ $input = array( 'data' => array( 'taxonomy' => $taxonomy ) + $data );
+ if ( null !== $fields ) {
+ $input['fields'] = $fields;
+ }
+
+ return $input;
+ }
+
+ /**
+ * Asserts that a create call failed with the given error and stored nothing.
+ *
+ * @since 7.3.0
+ *
+ * @param array $input The input.
+ * @param string $code The expected error code.
+ * @param int $status The expected status.
+ * @param string $message The expected message.
+ * @param string $context What the call was, for the assertion messages.
+ * @param array $extra Optional. The expected error data next to the status.
+ * Default empty array.
+ */
+ private function assert_create_fails( array $input, string $code, int $status, string $message, string $context, array $extra = array() ): void {
+ $result = $this->run_rejected( $input, $context );
+
+ $this->assert_error( $result, $code, $status, $message, $context, $extra );
+ }
+
+ /**
+ * The ability is registered in the content category with its label and annotations.
+ *
+ * @ticket 66743
+ * @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/term-create ability should be registered.' );
+ $this->assertSame( 'Create Term', $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 input schema takes the taxonomy, the attributes and the field list.
+ *
+ * @ticket 66743
+ * @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.' );
+
+ $expected = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'data' ),
+ 'properties' => array(
+ 'data' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'taxonomy', 'name' ),
+ 'properties' => array(
+ 'taxonomy' => $this->taxonomy_schema(),
+ 'name' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'maxLength' => 200,
+ ),
+ 'slug' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ ),
+ 'description' => array( 'type' => 'string' ),
+ 'parent' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ ),
+ ),
+ ),
+ 'fields' => self::FIELDS_SCHEMA,
+ ),
+ );
+
+ $this->assert_schema( $expected, wp_get_ability( self::ABILITY )->get_input_schema(), 'The input schema should be exactly the documented one.' );
+ }
+
+ /**
+ * The output is one item, the same object as an item of the query.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_output_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The create ability should be registered.' );
+
+ $this->assert_schema( self::ITEM_SCHEMA, wp_get_ability( self::ABILITY )->get_output_schema(), 'The output schema should be exactly the documented one.' );
+ }
+
+ /**
+ * Returns raw input that the permission callback refuses even for an administrator.
+ *
+ * @since 7.3.0
+ *
+ * @return array The inputs.
+ */
+ public static function data_inputs_refused_by_the_permission_callback(): array {
+ return array(
+ 'input that is a string' => array( 'category' ),
+ 'input that is null' => array( null ),
+ 'missing data' => array( array() ),
+ 'data that is a string' => array( array( 'data' => 'category' ) ),
+ 'data that is an integer' => array( array( 'data' => 1 ) ),
+ 'missing taxonomy' => array( array( 'data' => array( 'name' => 'Refused' ) ) ),
+ 'taxonomy that is not a string' => array( array( 'data' => array( 'taxonomy' => array( 'category' ) ) ) ),
+ 'taxonomy that is not exposed' => array( array( 'data' => array( 'taxonomy' => 'nav_menu' ) ) ),
+ 'taxonomy that does not exist' => array( array( 'data' => array( 'taxonomy' => 'tt_missing' ) ) ),
+ 'taxonomy in where' => array( array( 'where' => array( 'taxonomy' => 'category' ) ) ),
+ 'object data, hidden taxonomy' => array( (object) array( 'data' => (object) array( 'taxonomy' => 'nav_menu' ) ) ),
+ );
+ }
+
+ /**
+ * The permission callback refuses malformed input and taxonomies that are not exposed.
+ *
+ * @ticket 66743
+ * @dataProvider data_inputs_refused_by_the_permission_callback
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_refuses_malformed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse the input.' );
+ }
+
+ /**
+ * Returns input forms that count as objects.
+ *
+ * @since 7.3.0
+ *
+ * @return array The inputs.
+ */
+ public static function data_object_input_forms(): array {
+ $data = array( 'taxonomy' => 'category' );
+
+ return array(
+ 'arrays' => array( array( 'data' => $data ) ),
+ 'input that is an object' => array( (object) array( 'data' => $data ) ),
+ 'data that is an object' => array( array( 'data' => (object) $data ) ),
+ 'both that are objects' => array( (object) array( 'data' => (object) $data ) ),
+ );
+ }
+
+ /**
+ * The permission callback accepts the input and `data` as arrays or objects, and reads
+ * nothing in `data` but the taxonomy.
+ *
+ * @ticket 66743
+ * @dataProvider data_object_input_forms
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_accepts_arrays_and_objects( $input ): void {
+ $this->login_as( 'editor' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertTrue( $permission( $input ), 'The permission callback should accept the input.' );
+ }
+
+ /**
+ * Returns who may create terms in each taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_create_by_role(): array {
+ $allowed = array(
+ 'category' => array( 'administrator', 'editor' ),
+ 'post_tag' => array( 'administrator', 'editor', 'author', 'contributor' ),
+ );
+
+ $cases = array();
+ foreach ( $allowed as $taxonomy => $roles ) {
+ foreach ( array( 'administrator', 'editor', 'author', 'contributor', 'subscriber', 'no_role', 'logged_out' ) as $role ) {
+ $cases[ "{$role} in {$taxonomy}" ] = array( $role, $taxonomy, in_array( $role, $roles, true ) );
+ }
+ }
+
+ return $cases;
+ }
+
+ /**
+ * Creating a category takes the capability to edit categories, creating a tag the capability
+ * to assign tags; everyone else is refused by both callbacks and nothing is stored.
+ *
+ * @ticket 66743
+ * @dataProvider data_create_by_role
+ * @since 7.3.0
+ *
+ * @param string $role The role.
+ * @param string $taxonomy The taxonomy.
+ * @param bool $allowed Whether the role may create the term.
+ */
+ public function test_create_by_role( string $role, string $taxonomy, bool $allowed ): void {
+ $this->login_as( $role );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $input = $this->create_input( $taxonomy, array( 'name' => "Made by {$role}" ) );
+
+ if ( $allowed ) {
+ $result = $this->run_ability( $input );
+
+ $this->assertIsArray( $result, 'The term should be created.' );
+ $this->assertSame( $this->expected_item( $result['id'], self::DEFAULT_KEYS ), $result, 'The created term should be returned with the default fields.' );
+ $this->assertSame( "Made by {$role}", get_term( $result['id'], $taxonomy )->name, 'The term should be stored in the taxonomy.' );
+ return;
+ }
+
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+
+ $result = $this->call_rejected( $execute, $input, 'Execute callback' );
+
+ $this->assert_error( $result, 'term_cannot_create', 403, 'Sorry, you are not allowed to create terms in this taxonomy.', 'Execute callback' );
+ }
+
+ /**
+ * A visitor who is not logged in is refused even when a filter grants the capability to
+ * create terms, and nothing is stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_logged_out_visitor_is_refused_even_with_the_capability(): void {
+ $capability = get_taxonomy( 'category' )->cap->edit_terms;
+
+ add_filter(
+ 'map_meta_cap',
+ static function ( array $caps, string $cap ) use ( $capability ): array {
+ return $capability === $cap ? array( 'exist' ) : $caps;
+ },
+ 10,
+ 2
+ );
+
+ $this->login_as( 'logged_out' );
+
+ $this->assertTrue( current_user_can( $capability ), 'The filter should grant the capability to the visitor.' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $input = $this->create_input( 'category', array( 'name' => 'By a visitor' ) );
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse the visitor.' );
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+ }
+
+ /**
+ * A super admin who has no role on the site can create a category.
+ *
+ * @ticket 66743
+ * @group ms-required
+ * @since 7.3.0
+ */
+ public function test_super_admin_can_create_a_category(): void {
+ $this->login_as( 'super_admin' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->create_input( 'category', array( 'name' => 'By the network' ) ) );
+
+ $this->assertIsArray( $result, 'The category should be created.' );
+ $this->assertSame( 'By the network', get_term( $result['id'], 'category' )->name, 'The category should be stored.' );
+ }
+
+ /**
+ * Returns the capability a taxonomy with its own capabilities requires to create a term.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_own_capabilities(): array {
+ return array(
+ 'hierarchical taxonomy' => array( true, 'edit_genres' ),
+ 'flat taxonomy' => array( false, 'assign_genres' ),
+ );
+ }
+
+ /**
+ * A taxonomy with its own capabilities requires its own capability, not the default one.
+ *
+ * @ticket 66743
+ * @dataProvider data_own_capabilities
+ * @since 7.3.0
+ *
+ * @param bool $hierarchical Whether the taxonomy is hierarchical.
+ * @param string $capability The capability that allows creating terms.
+ */
+ public function test_taxonomy_with_its_own_capabilities( bool $hierarchical, string $capability ): void {
+ $this->register_taxonomy_with_own_capabilities( $hierarchical );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected( $this->create_input( 'tt_genre', array( 'name' => 'Jazz' ) ), 'Administrator' );
+
+ $this->assert_refused( $result, 'Administrator' );
+
+ $user = self::factory()->user->create_and_get( array( 'role' => 'subscriber' ) );
+ $user->add_cap( $capability );
+ wp_set_current_user( $user->ID );
+
+ $result = $this->run_ability( $this->create_input( 'tt_genre', array( 'name' => 'Jazz' ) ) );
+
+ $this->assertIsArray( $result, 'A user with the taxonomy capability should create the term.' );
+ $this->assertSame( 'Jazz', get_term( $result['id'], 'tt_genre' )->name, 'The term should be stored.' );
+ }
+
+ /**
+ * Returns taxonomies that the execute callback does not find.
+ *
+ * @since 7.3.0
+ *
+ * @return array The taxonomies.
+ */
+ public static function data_taxonomies_that_are_not_found(): array {
+ return array(
+ 'taxonomy turned off after registration' => array( 'category' ),
+ 'taxonomy that is not exposed' => array( 'nav_menu' ),
+ 'taxonomy that does not exist' => array( 'tt_missing' ),
+ );
+ }
+
+ /**
+ * The execute callback checks itself that the taxonomy is exposed.
+ *
+ * @ticket 66743
+ * @dataProvider data_taxonomies_that_are_not_found
+ * @since 7.3.0
+ *
+ * @param string $taxonomy The taxonomy.
+ */
+ public function test_execute_refuses_a_taxonomy_that_is_not_exposed( string $taxonomy ): void {
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ get_taxonomy( 'category' )->show_in_abilities = false;
+
+ $result = $this->call_rejected( $execute, $this->create_input( $taxonomy, array( 'name' => 'Nowhere' ) ), $taxonomy );
+
+ $this->assert_taxonomy_not_found( $result, $taxonomy );
+ }
+
+ /**
+ * Returns attributes that would fail the attribute rules.
+ *
+ * @since 7.3.0
+ *
+ * @return array}> The attributes.
+ */
+ public static function data_invalid_attributes_for_a_tag(): array {
+ return array(
+ 'valid attributes' => array( array( 'name' => 'Fine' ) ),
+ 'parent on a tag' => array(
+ array(
+ 'name' => 'Fine',
+ 'parent' => 0,
+ ),
+ ),
+ 'slug without characters' => array(
+ array(
+ 'name' => 'Fine',
+ 'slug' => '!!!',
+ ),
+ ),
+ 'blank name' => array( array( 'name' => ' ' ) ),
+ );
+ }
+
+ /**
+ * A user who may not create terms gets the same refusal whatever the attributes hold.
+ *
+ * @ticket 66743
+ * @dataProvider data_invalid_attributes_for_a_tag
+ * @since 7.3.0
+ *
+ * @param array $data The attributes.
+ */
+ public function test_capability_is_checked_before_the_attributes( array $data ): void {
+ $this->login_as( 'subscriber' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $result = $this->call_rejected( $execute, $this->create_input( 'post_tag', $data ), 'Subscriber' );
+
+ $this->assert_error( $result, 'term_cannot_create', 403, 'Sorry, you are not allowed to create terms in this taxonomy.', 'Subscriber' );
+ }
+
+ /**
+ * Returns attributes that break an attribute rule, with the rule's attribute and message.
+ *
+ * @since 7.3.0
+ *
+ * @return array, attribute: string, message: string}> The cases.
+ */
+ public static function data_invalid_attributes(): array {
+ $flat = 'Cannot set parent term, taxonomy is not hierarchical.';
+ $missing = 'Parent term does not exist.';
+ $slug = 'The slug must contain characters that are valid in a slug.';
+
+ return array(
+ 'parent of zero on a tag' => array( 'post_tag', array( 'parent' => 0 ), 'parent', $flat ),
+ 'parent on a tag before a bad slug' => array(
+ 'post_tag',
+ array(
+ 'parent' => 'missing',
+ 'slug' => '!!!',
+ ),
+ 'parent',
+ $flat,
+ ),
+ 'parent that does not exist' => array( 'category', array( 'parent' => 'missing' ), 'parent', $missing ),
+ 'parent that is a tag' => array( 'category', array( 'parent' => 'alpha' ), 'parent', $missing ),
+ 'missing parent before a bad slug' => array(
+ 'category',
+ array(
+ 'parent' => 'missing',
+ 'slug' => '!!!',
+ ),
+ 'parent',
+ $missing,
+ ),
+ 'slug of punctuation' => array( 'category', array( 'slug' => '!!!' ), 'slug', $slug ),
+ 'slug of zero' => array( 'post_tag', array( 'slug' => '0' ), 'slug', $slug ),
+ );
+ }
+
+ /**
+ * Attributes that break a rule are refused before anything is stored.
+ *
+ * @ticket 66743
+ * @dataProvider data_invalid_attributes
+ * @since 7.3.0
+ *
+ * @param string $taxonomy The taxonomy.
+ * @param array $data The attributes, with a fixture name as parent.
+ * @param string $attribute The attribute in the error.
+ * @param string $message The expected message.
+ */
+ public function test_invalid_attributes_are_refused( string $taxonomy, array $data, string $attribute, string $message ): void {
+ if ( isset( $data['parent'] ) && is_string( $data['parent'] ) ) {
+ $data['parent'] = 'missing' === $data['parent'] ? self::MISSING_ID : self::$term_ids[ $data['parent'] ];
+ }
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected( $this->create_input( $taxonomy, array( 'name' => 'Rule breaker' ) + $data ), $attribute );
+
+ $this->assert_invalid_attribute( $result, $attribute, $message, $attribute );
+ }
+
+ /**
+ * A top-level category can be created with a parent of zero.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_parent_of_zero_creates_a_top_level_category(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Top',
+ 'parent' => 0,
+ ),
+ array( 'parent' )
+ )
+ );
+
+ $this->assertIsArray( $result, 'The category should be created.' );
+ $this->assertSame( 0, $result['parent'], 'The category should be at the top level.' );
+ }
+
+ /**
+ * A child category is created with the chosen fields.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_creates_a_child_category_with_chosen_fields(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Release notes',
+ 'parent' => self::$term_ids['news'],
+ ),
+ array( 'name', 'slug', 'parent', 'link' )
+ )
+ );
+
+ $this->assertIsArray( $result, 'The category should be created.' );
+ $this->assertSame( array( 'id', 'name', 'slug', 'parent', 'link' ), array_keys( $result ), 'The item should hold the ID and the chosen fields.' );
+ $this->assertSame( 'Release notes', $result['name'], 'The name should be returned.' );
+ $this->assertSame( 'release-notes', $result['slug'], 'The slug should be made from the name.' );
+ $this->assertSame( self::$term_ids['news'], $result['parent'], 'The parent should be returned.' );
+ $this->assertSame( get_term_link( $result['id'], 'category' ), $result['link'], 'The link should be the link of the stored term.' );
+ $this->assertSame( self::$term_ids['news'], get_term( $result['id'], 'category' )->parent, 'The parent should be stored.' );
+ }
+
+ /**
+ * A tag is created with the default fields, and creating it again is an error that names it.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_creating_an_existing_term_again_is_an_error(): void {
+ $this->login_as( 'contributor' );
+ $this->register_abilities();
+
+ $input = $this->create_input( 'post_tag', array( 'name' => 'gamma' ) );
+ $result = $this->run_ability( $input );
+
+ $this->assertIsArray( $result, 'The tag should be created.' );
+ $this->assertSame( $this->expected_item( $result['id'], self::DEFAULT_KEYS ), $result, 'The tag should be returned with the default fields.' );
+
+ $this->assert_create_fails( $input, 'term_exists', 400, 'A term with the name provided already exists in this taxonomy.', 'Again', array( 'term_id' => $result['id'] ) );
+ }
+
+ /**
+ * Creating a child category that exists under the same parent is an error that names it.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_creating_an_existing_child_category_again_is_an_error(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $input = $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Product updates',
+ 'parent' => self::$term_ids['news'],
+ )
+ );
+
+ $this->assert_create_fails( $input, 'term_exists', 400, 'A term with the name provided already exists with this parent.', 'Child', array( 'term_id' => self::$term_ids['product_updates'] ) );
+ }
+
+ /**
+ * A slug that is taken is made unique.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taken_slug_is_made_unique(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Other news',
+ 'slug' => 'news',
+ ),
+ array( 'slug' )
+ )
+ );
+
+ $this->assertIsArray( $result, 'The category should be created.' );
+ $this->assertSame( 'news-2', $result['slug'], 'The slug should be made unique.' );
+ $this->assertSame( 'news', get_term( self::$term_ids['news'] )->slug, 'The slug of the other category should not change.' );
+ }
+
+ /**
+ * Returns values that Core sanitizes, with the stored values, for each user who creates them.
+ *
+ * @since 7.3.0
+ *
+ * @return array, expected: array}> The cases.
+ */
+ public static function data_values_sanitized_by_core(): array {
+ $values = array(
+ 'name with an ampersand' => array(
+ array( 'name' => 'A & B' ),
+ array(
+ 'name' => 'A & B',
+ 'slug' => 'a-b',
+ ),
+ ),
+ 'name with markup' => array(
+ array( 'name' => 'Bold name' ),
+ array(
+ 'name' => 'Bold name',
+ 'slug' => 'bold-name',
+ ),
+ ),
+ 'name with spaces' => array(
+ array( 'name' => ' Spaced name ' ),
+ array( 'name' => 'Spaced name' ),
+ ),
+ 'name with a backslash' => array(
+ array( 'name' => 'Back\slash' ),
+ array(
+ 'name' => 'Back\slash',
+ 'slug' => 'backslash',
+ ),
+ ),
+ 'slug with capitals' => array(
+ array(
+ 'name' => 'Slugged',
+ 'slug' => 'My Slug HERE',
+ ),
+ array( 'slug' => 'my-slug-here' ),
+ ),
+ 'description with markup' => array(
+ array(
+ 'name' => 'Described',
+ 'description' => 'Kept \ back',
+ ),
+ array( 'description' => 'Kept \ back' ),
+ ),
+ );
+
+ $cases = array();
+ foreach ( array( 'contributor', 'administrator' ) as $role ) {
+ foreach ( $values as $name => list( $data, $expected ) ) {
+ $cases[ "{$name}, by {$role}" ] = array( $role, $data, $expected );
+ }
+ }
+
+ return $cases;
+ }
+
+ /**
+ * Values are stored as Core sanitizes them, for every user, and backslashes are kept.
+ *
+ * @ticket 66743
+ * @dataProvider data_values_sanitized_by_core
+ * @since 7.3.0
+ *
+ * @param string $role The role.
+ * @param array $data The attributes.
+ * @param array $expected The stored values, by attribute.
+ */
+ public function test_values_are_stored_as_core_sanitizes_them( string $role, array $data, array $expected ): void {
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->create_input( 'post_tag', $data, self::ITEM_KEYS ) );
+
+ $this->assertIsArray( $result, 'The tag should be created.' );
+
+ $term = get_term( $result['id'], 'post_tag' );
+
+ foreach ( $expected as $key => $value ) {
+ $this->assertSame( $value, $term->$key, "The {$key} should be stored as Core sanitizes it." );
+ $this->assertSame( $value, $result[ $key ], "The {$key} should be returned as stored." );
+ }
+ }
+
+ /**
+ * Only the allowed attributes the input gives reach the save, slashed.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_only_the_given_allowed_attributes_reach_the_save(): void {
+ $saved = array();
+ add_filter(
+ 'pre_insert_term',
+ static function ( $term, string $taxonomy, array $args ) use ( &$saved ) {
+ $saved[] = array(
+ 'term' => $term,
+ 'args' => $args,
+ );
+
+ return $term;
+ },
+ 10,
+ 3
+ );
+
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ $this->assertIsArray( $this->run_ability( $this->create_input( 'category', array( 'name' => 'Only a name' ) ) ), 'The category with only a name should be created.' );
+ $this->assertIsArray(
+ $this->run_ability(
+ $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Every\attribute',
+ 'slug' => 'every-attribute',
+ 'description' => 'With a \ backslash',
+ 'parent' => self::$term_ids['news'],
+ )
+ )
+ ),
+ 'The category with every attribute should be created.'
+ );
+ $this->assertIsArray(
+ $execute(
+ $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Extra keys',
+ 'term_group' => 5,
+ 'alias_of' => 'news',
+ 'term_id' => self::$term_ids['news'],
+ 'description' => 'Extra',
+ )
+ )
+ ),
+ 'The category with extra keys should be created.'
+ );
+
+ $this->assertCount( 3, $saved, 'Each call should reach the save once.' );
+ $this->assertSame( 'Only a name', $saved[0]['term'], 'The name should reach the save.' );
+ $this->assertSame( array(), $saved[0]['args'], 'Nothing but the name should reach the save.' );
+ $this->assertSame( 'Every\\\\attribute', $saved[1]['term'], 'The name should reach the save slashed.' );
+ $this->assertSame(
+ array(
+ 'slug' => 'every-attribute',
+ 'description' => 'With a \\\\ backslash',
+ 'parent' => self::$term_ids['news'],
+ ),
+ $saved[1]['args'],
+ 'Every allowed attribute should reach the save, slashed.'
+ );
+ $this->assertSame( array( 'description' => 'Extra' ), $saved[2]['args'], 'Keys that are not allowed should not reach the save.' );
+
+ $extra = get_term_by( 'name', 'Extra keys', 'category' );
+
+ $this->assertInstanceOf( WP_Term::class, $extra, 'The category with extra keys should be stored.' );
+ $this->assertSame( 0, $extra->term_group, 'The term group should not be set.' );
+ $this->assertNotSame( self::$term_ids['news'], $extra->term_id, 'The ID should not be taken from the input.' );
+ }
+
+ /**
+ * Returns names that Core refuses, with its error.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_names_refused_by_core(): array {
+ return array(
+ 'blank name' => array( ' ', 'empty_term_name', 'A name is required for this term.' ),
+ 'name that sanitizes to nothing' => array( '', 'invalid_term_name', 'Invalid term name.' ),
+ );
+ }
+
+ /**
+ * A name that Core refuses comes back as Core's error, keyed by the name.
+ *
+ * @ticket 66743
+ * @dataProvider data_names_refused_by_core
+ * @since 7.3.0
+ *
+ * @param string $name The name.
+ * @param string $code The expected error code.
+ * @param string $message The expected message.
+ */
+ public function test_name_refused_by_core_is_an_error( string $name, string $code, string $message ): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assert_create_fails( $this->create_input( 'category', array( 'name' => $name ) ), $code, 400, $message, $code, array( 'params' => array( 'data[name]' => $message ) ) );
+ }
+
+ /**
+ * Returns save errors with the data they come back with.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_save_errors(): array {
+ return array(
+ 'insert database error' => array( 'db_insert_error', 500 ),
+ 'update database error' => array( 'db_update_error', 500 ),
+ 'any other code' => array( 'tt_refused', 400 ),
+ );
+ }
+
+ /**
+ * A save error comes back with only its first code, its message and its status.
+ *
+ * @ticket 66743
+ * @dataProvider data_save_errors
+ * @since 7.3.0
+ *
+ * @param string $code The error code.
+ * @param int $status The expected status.
+ */
+ public function test_save_error_comes_back_with_only_its_code_message_and_status( string $code, int $status ): void {
+ add_filter(
+ 'pre_insert_term',
+ static function () use ( $code ) {
+ $error = new WP_Error(
+ $code,
+ 'The save was refused.',
+ array(
+ 'status' => 418,
+ 'secret' => 'database detail',
+ )
+ );
+ $error->add( 'tt_second', 'A second error.', 'more detail' );
+
+ return $error;
+ }
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assert_create_fails( $this->create_input( 'category', array( 'name' => 'Refused save' ) ), $code, $status, 'The save was refused.', $code );
+ }
+
+ /**
+ * A term that cannot be read back after the save is not found, and the save stands.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_term_that_cannot_be_read_back_is_not_found(): void {
+ add_action(
+ 'saved_term',
+ static function ( int $term_id, int $tt_id ) {
+ global $wpdb;
+
+ $wpdb->update( $wpdb->term_taxonomy, array( 'taxonomy' => 'post_tag' ), array( 'term_taxonomy_id' => $tt_id ) );
+ clean_term_cache( $term_id, 'category' );
+ clean_term_cache( $term_id, 'post_tag' );
+ },
+ 10,
+ 2
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->create_input( 'category', array( 'name' => 'Moved away' ) ) );
+
+ $this->assert_term_not_found( $result, 'Read back' );
+ $this->assertInstanceOf( WP_Term::class, get_term_by( 'name', 'Moved away', 'post_tag' ), 'The saved term should stand.' );
+ }
+
+ /**
+ * The created item is the item the query returns for the same term and fields.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_created_item_is_the_query_item(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Same as query',
+ 'description' => 'Described',
+ 'parent' => self::$term_ids['news'],
+ ),
+ self::ITEM_KEYS
+ )
+ );
+
+ $this->assertIsArray( $result, 'The category should be created.' );
+
+ $query = $this->run_query(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'ids' => array( $result['id'] ),
+ ),
+ 'fields' => self::ITEM_KEYS,
+ )
+ );
+
+ $this->assertSame( $query['items'] ?? null, array( $result ), 'The created item should be the query item.' );
+ }
+
+ /**
+ * The created item is read back by the term ID, which differs from the term-taxonomy ID.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_created_term_is_read_back_by_its_term_id(): void {
+ $this->offset_term_taxonomy_ids();
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->create_input( 'category', array( 'name' => 'Two IDs' ), self::ITEM_KEYS ) );
+ $term = get_term_by( 'name', 'Two IDs', 'category' );
+
+ $this->assertInstanceOf( WP_Term::class, $term, 'The category should be stored.' );
+ $this->assertNotSame( $term->term_id, $term->term_taxonomy_id, 'The term ID and the term-taxonomy ID should differ.' );
+ $this->assertSame( $this->expected_item( $term->term_id, self::ITEM_KEYS ), $result, 'The created item should be the saved term.' );
+ }
+
+ /**
+ * A parent below 0 that reaches the execute callback is not a term, and nothing is stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_parent_below_zero_is_refused(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation(
+ $this->create_input(
+ 'category',
+ array(
+ 'name' => 'Below zero',
+ 'parent' => -1,
+ )
+ ),
+ 'Parent -1'
+ );
+
+ $this->assert_invalid_attribute( $result, 'parent', 'Parent term does not exist.', 'Parent -1' );
+ }
+
+ /**
+ * A slug longer than 200 characters is saved as Core sanitizes it and returned as stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_slug_longer_than_200_characters_is_saved_as_core_sanitizes_it(): void {
+ $slug = str_repeat( 'Ab!', 100 );
+ $expected = sanitize_title( $slug );
+
+ $this->assertGreaterThan( 200, strlen( $slug ), 'Precondition: the slug should be longer than 200 characters.' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->create_input(
+ 'post_tag',
+ array(
+ 'name' => 'Long slug',
+ 'slug' => $slug,
+ ),
+ array( 'slug' )
+ )
+ );
+
+ $this->assertIsArray( $result, 'The tag should be created.' );
+ $this->assertSame( $expected, get_term( $result['id'], 'post_tag' )->slug, 'The slug should be stored as Core sanitizes it.' );
+ $this->assertSame( $expected, $result['slug'], 'The slug should be returned as stored.' );
+ }
+
+ /**
+ * Returns attributes at and beyond their length limit.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_lengths(): array {
+ return array(
+ 'name of 200 characters' => array( 'name', 200, true ),
+ 'name of 201 characters' => array( 'name', 201, false ),
+ 'slug of 200 characters' => array( 'slug', 200, true ),
+ );
+ }
+
+ /**
+ * The name takes at most 200 characters, and a slug of 200 characters is stored in full.
+ *
+ * @ticket 66743
+ * @dataProvider data_lengths
+ * @since 7.3.0
+ *
+ * @param string $attribute The attribute.
+ * @param int $length The length of the value.
+ * @param bool $valid Whether the value is accepted.
+ */
+ public function test_length_limits( string $attribute, int $length, bool $valid ): void {
+ $value = str_repeat( 'a', $length );
+ $data = array(
+ 'name' => 'Long one',
+ $attribute => $value,
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ if ( ! $valid ) {
+ $this->assert_invalid_input( $this->run_rejected( $this->create_input( 'post_tag', $data ), $attribute ), $attribute );
+ return;
+ }
+
+ $result = $this->run_ability( $this->create_input( 'post_tag', $data, array( $attribute ) ) );
+
+ $this->assertIsArray( $result, 'The tag should be created.' );
+ $this->assertSame( $value, $result[ $attribute ], "The {$attribute} should be stored in full." );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreTermDeleteAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermDeleteAbility.php
new file mode 100644
index 0000000000000..88f0507973919
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermDeleteAbility.php
@@ -0,0 +1,758 @@
+ The input.
+ */
+ private function delete_input( int $term_id, ?string $taxonomy = null ): array {
+ if ( null === $taxonomy ) {
+ $taxonomy = get_term( $term_id )->taxonomy;
+ }
+
+ return array(
+ 'where' => array(
+ 'taxonomy' => $taxonomy,
+ 'id' => $term_id,
+ ),
+ 'permanent' => true,
+ );
+ }
+
+ /**
+ * Asserts that a term is gone.
+ *
+ * @since 7.3.0
+ *
+ * @param mixed $result The ability result.
+ * @param int $term_id The term ID.
+ * @param string $context What the call was, for the assertion messages.
+ */
+ private function assert_deleted( $result, int $term_id, string $context ): void {
+ $this->assertSame( array( 'outcome' => 'deleted' ), $result, "{$context}: the outcome should be deleted." );
+
+ wp_cache_delete( $term_id, 'terms' );
+
+ $this->assertNull( get_term( $term_id ), "{$context}: the term should be gone." );
+ }
+
+ /**
+ * The ability is registered in the content category with its label and annotations.
+ *
+ * @ticket 66743
+ * @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/term-delete ability should be registered.' );
+ $this->assertSame( 'Delete Term', $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 input schema takes the term and a required `permanent`, and the output only the outcome.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_schemas(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The delete ability should be registered.' );
+
+ $input = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where', 'permanent' ),
+ 'properties' => array(
+ 'where' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'taxonomy', 'id' ),
+ 'properties' => array(
+ 'taxonomy' => $this->taxonomy_schema(),
+ 'id' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ ),
+ ),
+ 'permanent' => array( 'type' => 'boolean' ),
+ ),
+ );
+
+ $output = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'outcome' ),
+ 'properties' => array(
+ 'outcome' => array( 'type' => 'string' ),
+ ),
+ );
+
+ $ability = wp_get_ability( self::ABILITY );
+
+ $this->assert_schema( $input, $ability->get_input_schema(), 'The input schema should be exactly the documented one.' );
+ $this->assert_schema( $output, $ability->get_output_schema(), 'The output schema should be exactly the documented one.' );
+ }
+
+ /**
+ * The permission callback refuses malformed input, taxonomies that are not exposed and IDs
+ * that are not whole numbers of at least 1.
+ *
+ * @ticket 66743
+ * @dataProvider data_unprepared_where_inputs_that_are_refused
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_refuses_malformed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse the input.' );
+ }
+
+ /**
+ * The permission callback reads the ID in every form the schema accepts, and checks the
+ * capability on it.
+ *
+ * @ticket 66743
+ * @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_reads_every_form_of_the_id( string $id_type, bool $as_object ): void {
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $input = array( 'where' => $this->build_unprepared_where( self::$term_ids['empty'], $id_type, $as_object ) );
+
+ $this->login_as( 'editor' );
+ $this->assertTrue( $permission( $input ), 'The permission callback should let an editor through.' );
+
+ $this->login_as( 'subscriber' );
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse a subscriber.' );
+
+ $this->login_as( 'logged_out' );
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse a logged-out visitor.' );
+ }
+
+ /**
+ * The permission callback lets a term that is not in the taxonomy through, so that the
+ * ability answers that it is not found.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_permission_callback_lets_a_term_that_is_not_in_the_taxonomy_through(): void {
+ $this->login_as( 'subscriber' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ foreach ( array( self::MISSING_ID, self::$term_ids['alpha'] ) as $term_id ) {
+ $this->assertTrue( $permission( $this->delete_input( $term_id, 'category' ) ), "The permission callback should let term {$term_id} through." );
+ }
+ }
+
+ /**
+ * Returns terms that the ability does not find.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_terms_that_are_not_found(): array {
+ return array(
+ 'term that does not exist' => array( 'missing', 'category', 'administrator' ),
+ 'term of another taxonomy' => array( 'alpha', 'category', 'administrator' ),
+ 'category named as a tag' => array( 'empty', 'post_tag', 'administrator' ),
+ 'taxonomy turned off after registration' => array( 'empty', 'category', 'administrator' ),
+ 'term that does not exist for a subscriber' => array( 'missing', 'category', 'subscriber' ),
+ );
+ }
+
+ /**
+ * A term that is missing, of another taxonomy or in a taxonomy that is not exposed gives one
+ * identical not-found error, also for a user who may delete nothing.
+ *
+ * @ticket 66743
+ * @dataProvider data_terms_that_are_not_found
+ * @since 7.3.0
+ *
+ * @param string $term The term fixture name, or `missing`.
+ * @param string $taxonomy The taxonomy named in the input.
+ * @param string $role The role.
+ */
+ public function test_term_that_is_not_found( string $term, string $taxonomy, string $role ): void {
+ $this->login_as( $role );
+ $this->register_abilities();
+ $this->open_permission_gate();
+
+ if ( 'empty' === $term && 'category' === $taxonomy ) {
+ get_taxonomy( 'category' )->show_in_abilities = false;
+ }
+
+ $term_id = 'missing' === $term ? self::MISSING_ID : self::$term_ids[ $term ];
+ $result = $this->run_rejected( $this->delete_input( $term_id, $taxonomy ), $term );
+
+ $this->assert_term_not_found( $result, $term );
+ }
+
+ /**
+ * The execute callback checks itself that the taxonomy is exposed.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_execute_refuses_a_taxonomy_that_is_not_exposed(): void {
+ $menu_id = wp_create_nav_menu( 'Main' );
+
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $result = $this->call_rejected( $execute, $this->delete_input( $menu_id, 'nav_menu' ), 'Menu' );
+
+ $this->assert_term_not_found( $result, 'Menu' );
+ }
+
+ /**
+ * A second delete of the same term is not found.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_second_delete_is_not_found(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $input = $this->delete_input( self::$term_ids['beta'] );
+
+ $this->assert_deleted( $this->run_ability( $input ), self::$term_ids['beta'], 'First delete' );
+ $this->assert_term_not_found( $this->run_rejected( $input, 'Second delete' ), 'Second delete' );
+ }
+
+ /**
+ * Returns who may delete terms of each taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_delete_by_role(): array {
+ $cases = array();
+ foreach ( array( 'empty', 'beta' ) as $term ) {
+ foreach ( array( 'administrator', 'editor', 'author', 'contributor', 'subscriber', 'no_role', 'logged_out' ) as $role ) {
+ $cases[ "{$role} on {$term}" ] = array( $role, $term, in_array( $role, array( 'administrator', 'editor' ), true ) );
+ }
+ }
+
+ return $cases;
+ }
+
+ /**
+ * Deleting a term takes the capability to delete it; everyone else is refused by both
+ * callbacks and nothing is stored.
+ *
+ * @ticket 66743
+ * @dataProvider data_delete_by_role
+ * @since 7.3.0
+ *
+ * @param string $role The role.
+ * @param string $term The term fixture name.
+ * @param bool $allowed Whether the role may delete the term.
+ */
+ public function test_delete_by_role( string $role, string $term, bool $allowed ): void {
+ $this->login_as( $role );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $term_id = self::$term_ids[ $term ];
+ $input = $this->delete_input( $term_id );
+
+ if ( $allowed ) {
+ $this->assert_deleted( $this->run_ability( $input ), $term_id, $role );
+ return;
+ }
+
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+
+ $result = $this->call_rejected( $execute, $input, 'Execute callback' );
+
+ $this->assert_error( $result, 'term_cannot_delete', 403, 'Sorry, you are not allowed to delete this term.', 'Execute callback' );
+ }
+
+ /**
+ * A visitor who is not logged in is refused even when a filter grants the capability to
+ * delete the term, and nothing is stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_logged_out_visitor_is_refused_even_with_the_capability(): void {
+ $this->filter_term_capability( 'delete_term', self::$term_ids['empty'], true );
+
+ $this->login_as( 'logged_out' );
+
+ $this->assertTrue( current_user_can( 'delete_term', self::$term_ids['empty'] ), 'The filter should grant the capability to the visitor.' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $input = $this->delete_input( self::$term_ids['empty'] );
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse the visitor.' );
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+ }
+
+ /**
+ * A super admin who has no role on the site can delete a category, but not the default one.
+ *
+ * @ticket 66743
+ * @group ms-required
+ * @since 7.3.0
+ */
+ public function test_super_admin_can_delete_a_category(): void {
+ $this->login_as( 'super_admin' );
+ $this->register_abilities();
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( self::$term_ids['empty'] ) ), self::$term_ids['empty'], 'Super admin' );
+
+ $result = $this->run_rejected( $this->delete_input( self::$term_ids['uncategorized'] ), 'Default category' );
+
+ $this->assert_error( $result, 'term_is_default', 400, 'The default category cannot be deleted.', 'Default category' );
+ }
+
+ /**
+ * Deleting one term can be granted to a user who may otherwise delete none.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_delete_term_granted_for_one_term(): void {
+ $this->filter_term_capability( 'delete_term', self::$term_ids['empty'], true );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( self::$term_ids['empty'] ) ), self::$term_ids['empty'], 'Granted' );
+ $this->assert_refused( $this->run_rejected( $this->delete_input( self::$term_ids['roadmap'] ), 'Other term' ), 'Other term' );
+ }
+
+ /**
+ * Deleting one term can be revoked from a user who may otherwise delete every term, and both
+ * callbacks follow it.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_delete_term_revoked_for_one_term(): void {
+ $this->filter_term_capability( 'delete_term', self::$term_ids['empty'], false );
+
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $input = $this->delete_input( self::$term_ids['empty'] );
+
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+ $this->assert_error( $this->call_rejected( $execute, $input, 'Execute callback' ), 'term_cannot_delete', 403, 'Sorry, you are not allowed to delete this term.', 'Execute callback' );
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( self::$term_ids['roadmap'] ) ), self::$term_ids['roadmap'], 'Other term' );
+ }
+
+ /**
+ * A taxonomy with its own capabilities requires its own capability to delete a term.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taxonomy_with_its_own_capabilities(): void {
+ $this->register_taxonomy_with_own_capabilities();
+ $term_id = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_genre',
+ 'name' => 'Jazz',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assert_refused( $this->run_rejected( $this->delete_input( $term_id ), 'Administrator' ), 'Administrator' );
+
+ $user = self::factory()->user->create_and_get( array( 'role' => 'subscriber' ) );
+ $user->add_cap( 'delete_genres' );
+ wp_set_current_user( $user->ID );
+
+ $result = $this->run_ability( $this->delete_input( $term_id ) );
+
+ $this->assert_deleted( $result, $term_id, 'Taxonomy capability' );
+ }
+
+ /**
+ * Returns default terms with the message their delete gives.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_default_terms(): array {
+ return array(
+ 'default category' => array( 'category', 'The default category cannot be deleted.' ),
+ 'default term of a taxonomy' => array( 'default_term', 'The default term cannot be deleted.' ),
+ );
+ }
+
+ /**
+ * A default term cannot be deleted by a user who may delete terms of its taxonomy.
+ *
+ * @ticket 66743
+ * @dataProvider data_default_terms
+ * @since 7.3.0
+ *
+ * @param string $kind Which default term to delete.
+ * @param string $message The expected message.
+ */
+ public function test_default_term_cannot_be_deleted( string $kind, string $message ): void {
+ if ( 'default_term' === $kind ) {
+ register_taxonomy(
+ 'tt_shelf',
+ 'post',
+ array(
+ 'hierarchical' => true,
+ 'show_in_abilities' => true,
+ 'default_term' => array( 'name' => 'Unsorted' ),
+ )
+ );
+ $term_id = (int) get_option( 'default_term_tt_shelf' );
+ } else {
+ $term_id = self::$term_ids['uncategorized'];
+ }
+
+ $this->assertInstanceOf( WP_Term::class, get_term( $term_id ), 'Precondition: the default term should exist.' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected( $this->delete_input( $term_id ), $kind );
+
+ $this->assert_error( $result, 'term_is_default', 400, $message, $kind );
+ }
+
+ /**
+ * Returns terms that a default option names although Core's delete does not refuse them as
+ * the default.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_terms_named_only_by_a_default_option(): array {
+ return array(
+ 'tag set in its default option' => array( 'default_option' ),
+ 'term set in the default term option of a taxonomy without one' => array( 'default_term_option' ),
+ );
+ }
+
+ /**
+ * Names a term in a default option that does not make it the default term of its taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @param string $kind Which option names the term.
+ * @return int The term ID.
+ */
+ private function name_term_in_a_default_option( string $kind ): int {
+ if ( 'default_option' === $kind ) {
+ update_option( 'default_post_tag', self::$term_ids['alpha'] );
+
+ return self::$term_ids['alpha'];
+ }
+
+ register_taxonomy(
+ 'tt_shelf',
+ 'post',
+ array(
+ 'hierarchical' => true,
+ 'show_in_abilities' => true,
+ )
+ );
+ $term_id = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_shelf',
+ 'name' => 'Unsorted',
+ )
+ );
+ update_option( 'default_term_tt_shelf', $term_id );
+
+ return $term_id;
+ }
+
+ /**
+ * A term that a default option names, but that Core's delete does not refuse as the default,
+ * is refused by the capability check, since Core denies its delete.
+ *
+ * @ticket 66743
+ * @dataProvider data_terms_named_only_by_a_default_option
+ * @since 7.3.0
+ *
+ * @param string $kind Which option names the term.
+ */
+ public function test_term_named_only_by_a_default_option_is_refused_by_the_capability_check( string $kind ): void {
+ $term_id = $this->name_term_in_a_default_option( $kind );
+
+ $this->login_as( 'editor' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $input = $this->delete_input( $term_id );
+
+ $this->assertTrue( current_user_can( get_taxonomy( get_term( $term_id )->taxonomy )->cap->delete_terms ), "{$kind}: precondition: the user should be able to delete terms of the taxonomy." );
+ $this->assert_refused( $this->run_rejected( $input, "{$kind}: ability" ), "{$kind}: ability" );
+ $this->assert_error( $this->call_rejected( $execute, $input, "{$kind}: execute callback" ), 'term_cannot_delete', 403, 'Sorry, you are not allowed to delete this term.', "{$kind}: execute callback" );
+ }
+
+ /**
+ * A term that a default option names, but that Core's delete does not refuse as the default,
+ * is deleted when its delete is granted.
+ *
+ * @ticket 66743
+ * @dataProvider data_terms_named_only_by_a_default_option
+ * @since 7.3.0
+ *
+ * @param string $kind Which option names the term.
+ */
+ public function test_term_named_only_by_a_default_option_is_deleted_when_granted( string $kind ): void {
+ $term_id = $this->name_term_in_a_default_option( $kind );
+ $this->filter_term_capability( 'delete_term', $term_id, true );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->delete_input( $term_id ) );
+
+ $this->assert_deleted( $result, $term_id, $kind );
+ }
+
+ /**
+ * Being granted the delete of the default category is not enough without the capability to
+ * delete categories.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_default_term_needs_the_taxonomy_capability(): void {
+ $this->filter_term_capability( 'delete_term', self::$term_ids['uncategorized'], true );
+
+ $this->login_as( 'subscriber' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $input = $this->delete_input( self::$term_ids['uncategorized'] );
+
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+ $this->assert_error( $this->call_rejected( $execute, $input, 'Execute callback' ), 'term_cannot_delete', 403, 'Sorry, you are not allowed to delete this term.', 'Execute callback' );
+ }
+
+ /**
+ * A term that is still there after the delete is a failure.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_term_still_there_after_the_delete_is_a_failure(): void {
+ $term_id = self::$term_ids['empty'];
+ $as_default = static function () use ( $term_id ): int {
+ return $term_id;
+ };
+
+ add_filter(
+ 'term_exists_default_query_args',
+ static function ( array $args ) use ( $as_default ): array {
+ add_filter( 'pre_option_default_category', $as_default );
+
+ return $args;
+ }
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $before = $this->snapshot();
+ $result = $this->run_ability( $this->delete_input( $term_id ) );
+
+ remove_filter( 'pre_option_default_category', $as_default );
+
+ $this->assertSame( $before, $this->snapshot(), 'Nothing stored should change.' );
+ $this->assert_error( $result, 'term_delete_failed', 500, 'The term cannot be deleted.', 'Still there' );
+ $this->assertInstanceOf( WP_Term::class, get_term( $term_id, 'category' ), 'The term should still exist.' );
+ }
+
+ /**
+ * Deleting a category moves its children to its parent, and only posts left without a
+ * category get the default category.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_delete_reassigns_children_and_posts_as_core_does(): void {
+ $only = self::factory()->post->create( array( 'post_category' => array( self::$term_ids['product_updates'] ) ) );
+ $both = self::factory()->post->create( array( 'post_category' => array( self::$term_ids['product_updates'], self::$term_ids['news'] ) ) );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( self::$term_ids['product_updates'] ) ), self::$term_ids['product_updates'], 'Delete' );
+
+ clean_term_cache( self::$term_ids['roadmap'], 'category' );
+
+ $this->assertSame( self::$term_ids['news'], get_term( self::$term_ids['roadmap'] )->parent, 'The child should move to the parent of the deleted category.' );
+ $this->assertSame( array( self::$term_ids['uncategorized'] ), wp_get_post_categories( $only ), 'A post left without a category should get the default category.' );
+ $this->assertSame( array( self::$term_ids['news'] ), wp_get_post_categories( $both ), 'A post with another category should not get the default category.' );
+ }
+
+ /**
+ * A tag is deleted.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_deletes_a_tag(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assert_deleted( $this->run_ability( $this->delete_input( self::$term_ids['beta'] ) ), self::$term_ids['beta'], 'Tag' );
+ $this->assertSame( array(), wp_get_post_tags( self::$post_ids['published'], array( 'fields' => 'ids' ) ), 'The post should have no tag left.' );
+ }
+
+ /**
+ * `permanent` set to false is refused, since terms have no Trash, and nothing changes.
+ *
+ * @ticket 66743
+ * @dataProvider data_permanent_values_that_are_refused
+ * @since 7.3.0
+ *
+ * @param mixed $permanent The `permanent` value.
+ */
+ public function test_refuses_a_delete_that_is_not_permanent( $permanent ): void {
+ $input = $this->delete_input( self::$term_ids['empty'] );
+ $input['permanent'] = $permanent;
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected( $input, 'Not permanent' );
+
+ $this->assert_error( $result, 'term_trash_not_supported', 501, 'Terms do not support trashing. Set `permanent` to true to delete the term.', 'Not permanent' );
+ $this->assertInstanceOf( WP_Term::class, get_term( self::$term_ids['empty'], 'category' ), 'The term should still exist.' );
+ }
+
+ /**
+ * Returns `permanent` values that are refused.
+ *
+ * @since 7.3.0
+ *
+ * @return array The values.
+ */
+ public static function data_permanent_values_that_are_refused(): array {
+ return array(
+ 'false' => array( false ),
+ 'false as text' => array( 'false' ),
+ );
+ }
+
+ /**
+ * Input without `permanent` fails the schema, and with validation skipped it deletes
+ * nothing.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_deletes_nothing_without_permanent(): void {
+ $input = $this->delete_input( self::$term_ids['empty'] );
+ unset( $input['permanent'] );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation( $input, 'Without permanent' );
+
+ $this->assert_error( $result, 'term_trash_not_supported', 501, 'Terms do not support trashing. Set `permanent` to true to delete the term.', 'Without permanent' );
+ $this->assertInstanceOf( WP_Term::class, get_term( self::$term_ids['empty'], 'category' ), 'The term should still exist.' );
+ }
+
+ /**
+ * The term and the capability are checked before `permanent`: a term that is not found,
+ * or one the caller cannot delete, gives its own error for a delete that is not permanent.
+ *
+ * @ticket 66743
+ * @dataProvider data_errors_before_permanent
+ * @since 7.3.0
+ *
+ * @param bool $exists Whether the term to delete exists.
+ * @param string $code The expected error code.
+ */
+ public function test_checks_the_term_before_permanent( bool $exists, string $code ): void {
+ $term_id = $exists ? self::$term_ids['empty'] : self::MISSING_ID;
+ $input = $this->delete_input( $term_id, 'category' );
+ $input['permanent'] = false;
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ if ( $exists ) {
+ $this->open_permission_gate();
+ $this->filter_term_capability( 'delete_term', $term_id, false );
+ }
+
+ $result = $this->run_rejected( $input, $code );
+
+ $this->assertWPError( $result, "{$code}: the call should fail." );
+ $this->assertSame( $code, $result->get_error_code(), "{$code}: the error of the earlier check should be returned." );
+ }
+
+ /**
+ * Returns the errors that come before the `permanent` check.
+ *
+ * @since 7.3.0
+ *
+ * @return array Whether the term exists, and the error code.
+ */
+ public static function data_errors_before_permanent(): array {
+ return array(
+ 'term not found' => array( false, 'term_not_found' ),
+ 'term not deletable' => array( true, 'term_cannot_delete' ),
+ );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreTermUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermUpdateAbility.php
new file mode 100644
index 0000000000000..518979c6642c9
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermUpdateAbility.php
@@ -0,0 +1,935 @@
+ $data The attributes.
+ * @param list|null $fields Optional. The requested fields. Default null.
+ * @param string|null $taxonomy Optional. The taxonomy. Default the taxonomy of the term.
+ * @return array The input.
+ */
+ private function update_input( int $term_id, array $data, ?array $fields = null, ?string $taxonomy = null ): array {
+ if ( null === $taxonomy ) {
+ $taxonomy = get_term( $term_id )->taxonomy;
+ }
+
+ $input = array(
+ 'where' => array(
+ 'taxonomy' => $taxonomy,
+ 'id' => $term_id,
+ ),
+ 'data' => $data,
+ );
+ if ( null !== $fields ) {
+ $input['fields'] = $fields;
+ }
+
+ return $input;
+ }
+
+ /**
+ * The ability is registered in the content category with its label and annotations.
+ *
+ * @ticket 66743
+ * @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/term-update ability should be registered.' );
+ $this->assertSame( 'Update Term', $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 input schema takes the term, the attributes and the field list.
+ *
+ * @ticket 66743
+ * @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.' );
+
+ $expected = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where', 'data' ),
+ 'properties' => array(
+ 'where' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'taxonomy', 'id' ),
+ 'properties' => array(
+ 'taxonomy' => $this->taxonomy_schema(),
+ 'id' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ ),
+ ),
+ 'data' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'minProperties' => 1,
+ 'properties' => array(
+ 'name' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ 'maxLength' => 200,
+ ),
+ 'slug' => array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ ),
+ 'description' => array( 'type' => 'string' ),
+ 'parent' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ ),
+ ),
+ ),
+ 'fields' => self::FIELDS_SCHEMA,
+ ),
+ );
+
+ $this->assert_schema( $expected, wp_get_ability( self::ABILITY )->get_input_schema(), 'The input schema should be exactly the documented one.' );
+ }
+
+ /**
+ * The output is one item, the same object as an item of the query.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_output_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The update ability should be registered.' );
+
+ $this->assert_schema( self::ITEM_SCHEMA, wp_get_ability( self::ABILITY )->get_output_schema(), 'The output schema should be exactly the documented one.' );
+ }
+
+ /**
+ * The permission callback refuses malformed input, taxonomies that are not exposed and IDs
+ * that are not whole numbers of at least 1.
+ *
+ * @ticket 66743
+ * @dataProvider data_unprepared_where_inputs_that_are_refused
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_refuses_malformed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse the input.' );
+ }
+
+ /**
+ * The permission callback reads the ID in every form the schema accepts, and checks the
+ * capability on it.
+ *
+ * @ticket 66743
+ * @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_reads_every_form_of_the_id( string $id_type, bool $as_object ): void {
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $input = array(
+ 'where' => $this->build_unprepared_where( self::$term_ids['news'], $id_type, $as_object ),
+ 'data' => array( 'description' => 'Any' ),
+ );
+
+ $this->login_as( 'editor' );
+ $this->assertTrue( $permission( $input ), 'The permission callback should let an editor through.' );
+
+ $this->login_as( 'subscriber' );
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse a subscriber.' );
+
+ $this->login_as( 'logged_out' );
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse a logged-out visitor.' );
+
+ $this->assertFalse( $permission( (object) $input ), 'The permission callback should refuse a logged-out visitor for object input.' );
+ }
+
+ /**
+ * The permission callback lets a term that is not in the taxonomy through, so that the
+ * ability answers that it is not found.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_permission_callback_lets_a_term_that_is_not_in_the_taxonomy_through(): void {
+ $this->login_as( 'subscriber' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ foreach ( array( self::MISSING_ID, self::$term_ids['alpha'] ) as $term_id ) {
+ $this->assertTrue( $permission( $this->update_input( $term_id, array( 'name' => 'Any' ), null, 'category' ) ), "The permission callback should let term {$term_id} through." );
+ }
+ }
+
+ /**
+ * Returns terms that the ability does not find.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_terms_that_are_not_found(): array {
+ return array(
+ 'term that does not exist' => array( 'missing', 'category', 'administrator' ),
+ 'term of another taxonomy' => array( 'alpha', 'category', 'administrator' ),
+ 'category named as a tag' => array( 'product_updates', 'post_tag', 'administrator' ),
+ 'taxonomy turned off after registration' => array( 'news', 'category', 'administrator' ),
+ 'term that does not exist for a subscriber' => array( 'missing', 'category', 'subscriber' ),
+ );
+ }
+
+ /**
+ * A term that is missing, of another taxonomy or in a taxonomy that is not exposed gives one
+ * identical not-found error, also for a user who may edit nothing.
+ *
+ * @ticket 66743
+ * @dataProvider data_terms_that_are_not_found
+ * @since 7.3.0
+ *
+ * @param string $term The term fixture name, or `missing`.
+ * @param string $taxonomy The taxonomy named in the input.
+ * @param string $role The role.
+ */
+ public function test_term_that_is_not_found( string $term, string $taxonomy, string $role ): void {
+ $this->login_as( $role );
+ $this->register_abilities();
+ $this->open_permission_gate();
+
+ if ( 'news' === $term ) {
+ get_taxonomy( 'category' )->show_in_abilities = false;
+ }
+
+ $term_id = 'missing' === $term ? self::MISSING_ID : self::$term_ids[ $term ];
+ $result = $this->run_rejected( $this->update_input( $term_id, array( 'name' => 'Product updates' ), null, $taxonomy ), $term );
+
+ $this->assert_term_not_found( $result, $term );
+ }
+
+ /**
+ * The execute callback checks itself that the taxonomy is exposed.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_execute_refuses_a_taxonomy_that_is_not_exposed(): void {
+ $menu_id = wp_create_nav_menu( 'Main' );
+
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $result = $this->call_rejected( $execute, $this->update_input( $menu_id, array( 'name' => 'Renamed' ), null, 'nav_menu' ), 'Menu' );
+
+ $this->assert_term_not_found( $result, 'Menu' );
+ }
+
+ /**
+ * Returns who may edit terms of each taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_update_by_role(): array {
+ $cases = array();
+ foreach ( array( 'news', 'beta' ) as $term ) {
+ foreach ( array( 'administrator', 'editor', 'author', 'contributor', 'subscriber', 'no_role', 'logged_out' ) as $role ) {
+ $cases[ "{$role} on {$term}" ] = array( $role, $term, in_array( $role, array( 'administrator', 'editor' ), true ) );
+ }
+ }
+
+ return $cases;
+ }
+
+ /**
+ * Editing a term takes the capability to edit it; everyone else is refused by both callbacks
+ * and nothing is stored.
+ *
+ * @ticket 66743
+ * @dataProvider data_update_by_role
+ * @since 7.3.0
+ *
+ * @param string $role The role.
+ * @param string $term The term fixture name.
+ * @param bool $allowed Whether the role may edit the term.
+ */
+ public function test_update_by_role( string $role, string $term, bool $allowed ): void {
+ $this->login_as( $role );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $term_id = self::$term_ids[ $term ];
+ $input = $this->update_input( $term_id, array( 'description' => "Edited by {$role}" ) );
+
+ if ( $allowed ) {
+ $result = $this->run_ability( $input );
+
+ $this->assertSame( $this->expected_item( $term_id, self::DEFAULT_KEYS ), $result, 'The updated term should be returned with the default fields.' );
+ $this->assertSame( "Edited by {$role}", get_term( $term_id )->description, 'The description should be stored.' );
+ return;
+ }
+
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+
+ $result = $this->call_rejected( $execute, $input, 'Execute callback' );
+
+ $this->assert_error( $result, 'term_cannot_edit', 403, 'Sorry, you are not allowed to edit this term.', 'Execute callback' );
+ }
+
+ /**
+ * A super admin who has no role on the site can edit a category.
+ *
+ * @ticket 66743
+ * @group ms-required
+ * @since 7.3.0
+ */
+ public function test_super_admin_can_edit_a_category(): void {
+ $this->login_as( 'super_admin' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['news'], array( 'description' => 'By the network' ) ) );
+
+ $this->assertIsArray( $result, 'The category should be updated.' );
+ $this->assertSame( 'By the network', get_term( self::$term_ids['news'] )->description, 'The description should be stored.' );
+ }
+
+ /**
+ * A visitor who is not logged in is refused even when a filter grants the capability to
+ * edit the term, and nothing is stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_logged_out_visitor_is_refused_even_with_the_capability(): void {
+ $this->filter_term_capability( 'edit_term', self::$term_ids['news'], true );
+
+ $this->login_as( 'logged_out' );
+
+ $this->assertTrue( current_user_can( 'edit_term', self::$term_ids['news'] ), 'The filter should grant the capability to the visitor.' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+ $input = $this->update_input( self::$term_ids['news'], array( 'description' => 'By a visitor' ) );
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse the visitor.' );
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+ }
+
+ /**
+ * Editing one term can be granted to a user who may otherwise edit none.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_edit_term_granted_for_one_term(): void {
+ $this->filter_term_capability( 'edit_term', self::$term_ids['news'], true );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['news'], array( 'description' => 'Granted' ) ) );
+
+ $this->assertIsArray( $result, 'The granted term should be updated.' );
+ $this->assertSame( 'Granted', get_term( self::$term_ids['news'] )->description, 'The description should be stored.' );
+
+ $result = $this->run_rejected( $this->update_input( self::$term_ids['empty'], array( 'description' => 'Not granted' ) ), 'Other term' );
+
+ $this->assert_refused( $result, 'Other term' );
+ }
+
+ /**
+ * Editing one term can be revoked from a user who may otherwise edit every term, and both
+ * callbacks follow it.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_edit_term_revoked_for_one_term(): void {
+ $this->filter_term_capability( 'edit_term', self::$term_ids['news'], false );
+
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $input = $this->update_input( self::$term_ids['news'], array( 'description' => 'Revoked' ) );
+
+ $this->assert_refused( $this->run_rejected( $input, 'Ability' ), 'Ability' );
+ $this->assert_error( $this->call_rejected( $execute, $input, 'Execute callback' ), 'term_cannot_edit', 403, 'Sorry, you are not allowed to edit this term.', 'Execute callback' );
+
+ $this->assertIsArray( $this->run_ability( $this->update_input( self::$term_ids['empty'], array( 'description' => 'Still allowed' ) ) ), 'Another term should still be updated.' );
+ }
+
+ /**
+ * A taxonomy with its own capabilities requires its own capability to edit a term.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taxonomy_with_its_own_capabilities(): void {
+ $this->register_taxonomy_with_own_capabilities();
+ $term_id = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_genre',
+ 'name' => 'Jazz',
+ )
+ );
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $this->assert_refused( $this->run_rejected( $this->update_input( $term_id, array( 'name' => 'Blues' ) ), 'Administrator' ), 'Administrator' );
+
+ $user = self::factory()->user->create_and_get( array( 'role' => 'subscriber' ) );
+ $user->add_cap( 'edit_genres' );
+ wp_set_current_user( $user->ID );
+
+ $result = $this->run_ability( $this->update_input( $term_id, array( 'name' => 'Blues' ) ) );
+
+ $this->assertIsArray( $result, 'A user with the taxonomy capability should update the term.' );
+ $this->assertSame( 'Blues', get_term( $term_id )->name, 'The name should be stored.' );
+ }
+
+ /**
+ * Returns attributes that would fail the attribute rules or the save.
+ *
+ * @since 7.3.0
+ *
+ * @return array}> The attributes.
+ */
+ public static function data_attributes_behind_the_capability(): array {
+ return array(
+ 'valid attributes' => array( array( 'description' => 'Fine' ) ),
+ 'parent of the term' => array( array( 'parent' => 'news' ) ),
+ 'parent that is missing' => array( array( 'parent' => 'missing' ) ),
+ 'slug without characters' => array( array( 'slug' => '!!!' ) ),
+ 'taken slug' => array( array( 'slug' => 'empty' ) ),
+ );
+ }
+
+ /**
+ * A user who may not edit the term gets the same refusal whatever the attributes hold.
+ *
+ * @ticket 66743
+ * @dataProvider data_attributes_behind_the_capability
+ * @since 7.3.0
+ *
+ * @param array $data The attributes, with a fixture name as parent.
+ */
+ public function test_capability_is_checked_before_the_attributes( array $data ): void {
+ if ( isset( $data['parent'] ) ) {
+ $data['parent'] = 'missing' === $data['parent'] ? self::MISSING_ID : self::$term_ids[ $data['parent'] ];
+ }
+
+ $this->login_as( 'author' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $result = $this->call_rejected( $execute, $this->update_input( self::$term_ids['news'], $data ), 'Author' );
+
+ $this->assert_error( $result, 'term_cannot_edit', 403, 'Sorry, you are not allowed to edit this term.', 'Author' );
+ }
+
+ /**
+ * Returns attributes that break an attribute rule, with the rule's attribute and message.
+ *
+ * @since 7.3.0
+ *
+ * @return array, attribute: string, message: string}> The cases.
+ */
+ public static function data_invalid_attributes(): array {
+ $flat = 'Cannot set parent term, taxonomy is not hierarchical.';
+ $missing = 'Parent term does not exist.';
+ $loop = 'The parent term cannot be the term itself or one of its descendants.';
+ $slug = 'The slug must contain characters that are valid in a slug.';
+
+ return array(
+ 'parent of zero on a tag' => array( 'beta', array( 'parent' => 0 ), 'parent', $flat ),
+ 'parent on a tag before a bad slug' => array(
+ 'beta',
+ array(
+ 'parent' => 'alpha',
+ 'slug' => '!!!',
+ ),
+ 'parent',
+ $flat,
+ ),
+ 'parent that does not exist' => array( 'news', array( 'parent' => 'missing' ), 'parent', $missing ),
+ 'parent that is a tag' => array( 'news', array( 'parent' => 'alpha' ), 'parent', $missing ),
+ 'parent that is the term itself' => array( 'news', array( 'parent' => 'news' ), 'parent', $loop ),
+ 'parent that is a descendant' => array( 'news', array( 'parent' => 'roadmap' ), 'parent', $loop ),
+ 'descendant before a bad slug' => array(
+ 'news',
+ array(
+ 'parent' => 'product_updates',
+ 'slug' => '0',
+ ),
+ 'parent',
+ $loop,
+ ),
+ 'slug of punctuation' => array( 'news', array( 'slug' => '!!!' ), 'slug', $slug ),
+ 'slug of zero' => array( 'beta', array( 'slug' => '0' ), 'slug', $slug ),
+ );
+ }
+
+ /**
+ * Attributes that break a rule are refused before anything is stored.
+ *
+ * @ticket 66743
+ * @dataProvider data_invalid_attributes
+ * @since 7.3.0
+ *
+ * @param string $term The term fixture name.
+ * @param array $data The attributes, with a fixture name as parent.
+ * @param string $attribute The attribute in the error.
+ * @param string $message The expected message.
+ */
+ public function test_invalid_attributes_are_refused( string $term, array $data, string $attribute, string $message ): void {
+ if ( isset( $data['parent'] ) && is_string( $data['parent'] ) ) {
+ $data['parent'] = 'missing' === $data['parent'] ? self::MISSING_ID : self::$term_ids[ $data['parent'] ];
+ }
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected( $this->update_input( self::$term_ids[ $term ], $data ), $attribute );
+
+ $this->assert_invalid_attribute( $result, $attribute, $message, $attribute );
+ }
+
+ /**
+ * A slug taken by another term is Core's error, keyed by the slug, when the parent stays.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taken_slug_is_an_error(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $message = 'The slug “news” is already in use by another term.';
+ $result = $this->run_rejected( $this->update_input( self::$term_ids['empty'], array( 'slug' => 'news' ) ), 'Taken slug' );
+
+ $this->assert_error( $result, 'duplicate_term_slug', 400, $message, 'Taken slug', array( 'params' => array( 'data[slug]' => $message ) ) );
+ }
+
+ /**
+ * A slug taken by another term is made unique when the parent changes too.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taken_slug_with_a_new_parent_is_made_unique(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->update_input(
+ self::$term_ids['empty'],
+ array(
+ 'slug' => 'roadmap',
+ 'parent' => self::$term_ids['news'],
+ ),
+ array( 'slug', 'parent' )
+ )
+ );
+
+ $this->assertSame(
+ array(
+ 'id' => self::$term_ids['empty'],
+ 'slug' => 'roadmap-news',
+ 'parent' => self::$term_ids['news'],
+ ),
+ $result,
+ 'The slug should be made unique with the parent slug.'
+ );
+ $this->assertSame( 'roadmap', get_term( self::$term_ids['roadmap'] )->slug, 'The slug of the other category should not change.' );
+ }
+
+ /**
+ * A term can take the name of another term.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_term_can_take_the_name_of_another_term(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['empty'], array( 'name' => 'News' ), array( 'name', 'slug' ) ) );
+
+ $this->assertSame(
+ array(
+ 'id' => self::$term_ids['empty'],
+ 'name' => 'News',
+ 'slug' => 'empty',
+ ),
+ $result,
+ 'The term should take the name and keep its slug.'
+ );
+ }
+
+ /**
+ * A name that Core refuses comes back as Core's error, keyed by the name.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_blank_name_is_an_error(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $message = 'A name is required for this term.';
+ $result = $this->run_rejected( $this->update_input( self::$term_ids['news'], array( 'name' => ' ' ) ), 'Blank name' );
+
+ $this->assert_error( $result, 'empty_term_name', 400, $message, 'Blank name', array( 'params' => array( 'data[name]' => $message ) ) );
+ }
+
+ /**
+ * Only the given attributes change; every other value of the term is kept.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_only_the_given_attributes_change(): void {
+ $before = get_term( self::$term_ids['product_updates'] );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['product_updates'], array( 'description' => 'Release notes and roadmap updates.' ), array( 'name', 'description' ) ) );
+
+ $this->assertSame(
+ array(
+ 'id' => self::$term_ids['product_updates'],
+ 'name' => 'Product updates',
+ 'description' => 'Release notes and roadmap updates.',
+ ),
+ $result,
+ 'The updated term should be returned with the chosen fields.'
+ );
+
+ $after = get_term( self::$term_ids['product_updates'] );
+
+ $this->assertSame( $before->name, $after->name, 'The name should be kept.' );
+ $this->assertSame( $before->slug, $after->slug, 'The slug should be kept.' );
+ $this->assertSame( $before->parent, $after->parent, 'The parent should be kept.' );
+ $this->assertSame( $before->term_group, $after->term_group, 'The term group should be kept.' );
+ }
+
+ /**
+ * Moving a category to the top level changes its link.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_moving_a_category_to_the_top_level(): void {
+ $old_link = get_term_link( self::$term_ids['product_updates'], 'category' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['product_updates'], array( 'parent' => 0 ), array( 'name', 'parent', 'link' ) ) );
+
+ $this->assertSame( $this->expected_item( self::$term_ids['product_updates'], array( 'name', 'parent', 'link' ) ), $result, 'The moved category should be returned with the chosen fields.' );
+ $this->assertSame( 0, $result['parent'], 'The category should be at the top level.' );
+ $this->assertNotSame( $old_link, $result['link'], 'The link should change with the parent.' );
+ }
+
+ /**
+ * Values are stored as Core sanitizes them, and backslashes are kept.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_values_are_stored_as_core_sanitizes_them(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ $this->update_input(
+ self::$term_ids['empty'],
+ array(
+ 'name' => 'Back\slash & co',
+ 'slug' => 'My Slug HERE',
+ 'description' => 'Kept \ back',
+ ),
+ self::ITEM_KEYS
+ )
+ );
+
+ $term = get_term( self::$term_ids['empty'] );
+
+ $this->assertSame( 'Back\slash & co', $term->name, 'The name should be stored as Core sanitizes it.' );
+ $this->assertSame( 'my-slug-here', $term->slug, 'The slug should be stored as Core sanitizes it.' );
+ $this->assertSame( 'Kept \ back', $term->description, 'The description should be stored as Core sanitizes it.' );
+ $this->assertSame( $this->expected_item( self::$term_ids['empty'], self::ITEM_KEYS ), $result, 'The stored values should be returned.' );
+ }
+
+ /**
+ * Keys that are not allowed do not reach the save, also past the schema.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_keys_that_are_not_allowed_do_not_reach_the_save(): void {
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+ $result = $execute(
+ $this->update_input(
+ self::$term_ids['empty'],
+ array(
+ 'description' => 'Allowed',
+ 'term_group' => 5,
+ 'alias_of' => 'news',
+ 'taxonomy' => 'post_tag',
+ 'term_id' => self::$term_ids['news'],
+ )
+ )
+ );
+
+ $this->assertIsArray( $result, 'The term should be updated.' );
+
+ $term = get_term( self::$term_ids['empty'] );
+
+ $this->assertSame( 'Allowed', $term->description, 'The allowed attribute should be stored.' );
+ $this->assertSame( 0, $term->term_group, 'The term group should not be set.' );
+ $this->assertSame( 'category', $term->taxonomy, 'The taxonomy should not change.' );
+ $this->assertSame( 'News', get_term( self::$term_ids['news'] )->name, 'The term named by the extra ID should not change.' );
+ }
+
+ /**
+ * A term that cannot be read back after the save is not found, and the save stands.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_term_that_cannot_be_read_back_is_not_found(): void {
+ add_action(
+ 'saved_term',
+ static function ( int $term_id, int $tt_id ) {
+ global $wpdb;
+
+ $wpdb->update( $wpdb->term_taxonomy, array( 'taxonomy' => 'post_tag' ), array( 'term_taxonomy_id' => $tt_id ) );
+ clean_term_cache( $term_id, 'category' );
+ clean_term_cache( $term_id, 'post_tag' );
+ },
+ 10,
+ 2
+ );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['empty'], array( 'description' => 'Moved away' ) ) );
+
+ $this->assert_term_not_found( $result, 'Read back' );
+ $this->assertSame( 'Moved away', get_term( self::$term_ids['empty'], 'post_tag' )->description, 'The save should stand.' );
+ }
+
+ /**
+ * The updated item is the item the query returns for the same term and fields.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_updated_item_is_the_query_item(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['roadmap'], array( 'name' => 'Same as query' ), self::ITEM_KEYS ) );
+
+ $query = $this->run_query(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'ids' => array( self::$term_ids['roadmap'] ),
+ ),
+ 'fields' => self::ITEM_KEYS,
+ )
+ );
+
+ $this->assertSame( $query['items'] ?? null, array( $result ), 'The updated item should be the query item.' );
+ }
+
+ /**
+ * The updated item is read back by the term ID, which differs from the term-taxonomy ID.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_updated_term_is_read_back_by_its_term_id(): void {
+ $this->offset_term_taxonomy_ids();
+
+ $term_id = self::factory()->category->create( array( 'name' => 'Two IDs' ) );
+ self::factory()->category->create( array( 'name' => 'Next to two IDs' ) );
+
+ $this->assertNotSame( $term_id, get_term( $term_id )->term_taxonomy_id, 'The term ID and the term-taxonomy ID should differ.' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( $term_id, array( 'description' => 'Read back' ), self::ITEM_KEYS ) );
+
+ $this->assertSame( $this->expected_item( $term_id, self::ITEM_KEYS ), $result, 'The updated item should be the saved term.' );
+ $this->assertSame( 'Read back', $result['description'], 'The updated item should hold the new description.' );
+ }
+
+ /**
+ * The default category can be edited.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_default_category_can_be_edited(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['uncategorized'], array( 'name' => 'General' ), array( 'name' ) ) );
+
+ $this->assertSame(
+ array(
+ 'id' => self::$term_ids['uncategorized'],
+ 'name' => 'General',
+ ),
+ $result,
+ 'The default category should be renamed.'
+ );
+ }
+
+ /**
+ * A parent below 0 that reaches the execute callback is not a term, and nothing is stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_parent_below_zero_is_refused(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation( $this->update_input( self::$term_ids['news'], array( 'parent' => -1 ) ), 'Parent -1' );
+
+ $this->assert_invalid_attribute( $result, 'parent', 'Parent term does not exist.', 'Parent -1' );
+ }
+
+ /**
+ * A slug longer than 200 characters is saved as Core sanitizes it and returned as stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_slug_longer_than_200_characters_is_saved_as_core_sanitizes_it(): void {
+ $slug = str_repeat( 'Ab!', 100 );
+ $expected = sanitize_title( $slug );
+
+ $this->assertGreaterThan( 200, strlen( $slug ), 'Precondition: the slug should be longer than 200 characters.' );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['beta'], array( 'slug' => $slug ), array( 'slug' ) ) );
+
+ $this->assertIsArray( $result, 'The tag should be updated.' );
+ $this->assertSame( $expected, get_term( self::$term_ids['beta'], 'post_tag' )->slug, 'The slug should be stored as Core sanitizes it.' );
+ $this->assertSame( $expected, $result['slug'], 'The slug should be returned as stored.' );
+ }
+
+ /**
+ * Returns attributes at and beyond their length limit.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_lengths(): array {
+ return array(
+ 'name of 200 characters' => array( 'name', 200, true ),
+ 'name of 201 characters' => array( 'name', 201, false ),
+ 'slug of 200 characters' => array( 'slug', 200, true ),
+ );
+ }
+
+ /**
+ * The name takes at most 200 characters, and a slug of 200 characters is stored in full.
+ *
+ * @ticket 66743
+ * @dataProvider data_lengths
+ * @since 7.3.0
+ *
+ * @param string $attribute The attribute.
+ * @param int $length The length of the value.
+ * @param bool $valid Whether the value is accepted.
+ */
+ public function test_length_limits( string $attribute, int $length, bool $valid ): void {
+ $value = str_repeat( 'b', $length );
+
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ if ( ! $valid ) {
+ $this->assert_invalid_input( $this->run_rejected( $this->update_input( self::$term_ids['beta'], array( $attribute => $value ) ), $attribute ), $attribute );
+ return;
+ }
+
+ $result = $this->run_ability( $this->update_input( self::$term_ids['beta'], array( $attribute => $value ), array( $attribute ) ) );
+
+ $this->assertIsArray( $result, 'The tag should be updated.' );
+ $this->assertSame( $value, $result[ $attribute ], "The {$attribute} should be stored in full." );
+ }
+
+ /**
+ * Input that fails the schema is refused before anything is stored.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_empty_data_is_refused(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $this->assert_invalid_input( $this->run_rejected( $this->update_input( self::$term_ids['news'], array() ), 'Empty data' ), 'Empty data' );
+ }
+}
diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreTermsAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermsAbility.php
new file mode 100644
index 0000000000000..5fe355b38b22c
--- /dev/null
+++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermsAbility.php
@@ -0,0 +1,2027 @@
+ The IDs, in their order.
+ */
+ private function item_ids( $result, string $context ): array {
+ $this->assertIsArray( $result, "{$context}: the query should succeed." );
+ $this->assertArrayHasKey( 'items', $result, "{$context}: the result should hold items." );
+
+ return array_map(
+ static function ( array $item ): int {
+ return $item['id'];
+ },
+ $result['items']
+ );
+ }
+
+ /**
+ * Creates tags and returns their IDs and slugs.
+ *
+ * @since 7.3.0
+ *
+ * @param int $count The number of tags.
+ * @return array{ids: list, slugs: list} The IDs and slugs.
+ */
+ private function create_tags( int $count ): array {
+ $ids = array();
+ $slugs = array();
+ for ( $i = 1; $i <= $count; $i++ ) {
+ $ids[] = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'post_tag',
+ 'name' => sprintf( 'extra %02d', $i ),
+ )
+ );
+ $slugs[] = sprintf( 'extra-%02d', $i );
+ }
+
+ return array(
+ 'ids' => $ids,
+ 'slugs' => $slugs,
+ );
+ }
+
+ /**
+ * The ability is registered in the content category with its label and annotations.
+ *
+ * @ticket 66743
+ * @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/terms-query ability should be registered.' );
+ $this->assertSame( 'Query Terms', $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->assertTrue( $annotations['readonly'], 'The ability should 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.' );
+ }
+
+ /**
+ * None of the term abilities is registered when no taxonomy is exposed to abilities.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_no_term_ability_is_registered_without_an_exposed_taxonomy(): void {
+ foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
+ $taxonomy->show_in_abilities = false;
+ }
+
+ $this->register_abilities();
+
+ foreach ( self::TERM_ABILITIES as $ability_name ) {
+ $this->assertFalse( wp_has_ability( $ability_name ), "The {$ability_name} ability should not be registered without an exposed taxonomy." );
+ }
+ }
+
+ /**
+ * The taxonomy enums of the four abilities list the exposed taxonomies and no other.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taxonomy_enums_list_only_the_exposed_taxonomies(): void {
+ $this->register_taxonomy_with_own_capabilities();
+ register_taxonomy(
+ 'tt_hidden',
+ 'post',
+ array(
+ 'public' => true,
+ 'show_in_rest' => true,
+ 'show_in_abilities' => false,
+ )
+ );
+ register_taxonomy(
+ 'tt_truthy',
+ 'post',
+ array(
+ 'public' => true,
+ 'show_in_abilities' => 1,
+ )
+ );
+
+ $this->register_abilities();
+
+ $expected = array( 'category', 'post_tag', 'tt_genre' );
+ $paths = array(
+ 'core/terms-query' => array( 'where', 'taxonomy' ),
+ 'core/term-create' => array( 'data', 'taxonomy' ),
+ 'core/term-update' => array( 'where', 'taxonomy' ),
+ 'core/term-delete' => array( 'where', 'taxonomy' ),
+ );
+
+ foreach ( $paths as $ability_name => $path ) {
+ $this->assertTrue( wp_has_ability( $ability_name ), "The {$ability_name} ability should be registered." );
+
+ $schema = wp_get_ability( $ability_name )->get_input_schema();
+ $enum = $schema['properties'][ $path[0] ]['properties'][ $path[1] ]['enum'];
+
+ $this->assertSameSets( $expected, $enum, "The taxonomy enum of {$ability_name} should list every exposed taxonomy and no other." );
+ }
+ }
+
+ /**
+ * The input schema is the filter object, the field list and the pagination.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_input_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The query ability should be registered.' );
+
+ $list = static function ( array $items ): array {
+ return array(
+ 'type' => 'array',
+ 'uniqueItems' => true,
+ 'minItems' => 1,
+ 'maxItems' => 100,
+ 'items' => $items,
+ );
+ };
+
+ $expected = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'where' ),
+ 'properties' => array(
+ 'where' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'taxonomy' ),
+ 'properties' => array(
+ 'taxonomy' => $this->taxonomy_schema(),
+ 'ids' => $list(
+ array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ )
+ ),
+ 'slugs' => $list(
+ array(
+ 'type' => 'string',
+ 'minLength' => 1,
+ )
+ ),
+ 'parent' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ ),
+ 'post' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ 'hide_empty' => array( 'type' => 'boolean' ),
+ ),
+ ),
+ 'fields' => self::FIELDS_SCHEMA,
+ 'pagination' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'properties' => array(
+ 'page' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ 'per_page' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ 'maximum' => 100,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ $this->assert_schema( $expected, wp_get_ability( self::ABILITY )->get_input_schema(), 'The input schema should be exactly the documented one.' );
+ }
+
+ /**
+ * The output schema is the list of items and the pagination totals.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_output_schema(): void {
+ $this->register_abilities();
+
+ $this->assertTrue( wp_has_ability( self::ABILITY ), 'The query ability should be registered.' );
+
+ $expected = array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'items', 'pagination' ),
+ 'properties' => array(
+ 'items' => array(
+ 'type' => 'array',
+ 'items' => self::ITEM_SCHEMA,
+ ),
+ 'pagination' => array(
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => array( 'total', 'total_pages' ),
+ 'properties' => array(
+ 'total' => array( 'type' => 'integer' ),
+ 'total_pages' => array( 'type' => 'integer' ),
+ ),
+ ),
+ ),
+ );
+
+ $this->assert_schema( $expected, wp_get_ability( self::ABILITY )->get_output_schema(), 'The output schema should be exactly the documented one.' );
+ }
+
+ /**
+ * Returns raw input that the permission callback refuses even for an administrator.
+ *
+ * @since 7.3.0
+ *
+ * @return array The inputs.
+ */
+ public static function data_inputs_refused_by_the_permission_callback(): array {
+ return array(
+ 'input that is a string' => array( 'category' ),
+ 'input that is null' => array( null ),
+ 'missing where' => array( array() ),
+ 'where that is a string' => array( array( 'where' => 'category' ) ),
+ 'where that is an integer' => array( array( 'where' => 1 ) ),
+ 'missing taxonomy' => array( array( 'where' => array( 'parent' => 0 ) ) ),
+ 'taxonomy that is not a string' => array( array( 'where' => array( 'taxonomy' => array( 'category' ) ) ) ),
+ 'taxonomy that is not exposed' => array( array( 'where' => array( 'taxonomy' => 'nav_menu' ) ) ),
+ 'taxonomy that does not exist' => array( array( 'where' => array( 'taxonomy' => 'tt_missing' ) ) ),
+ 'object where with a hidden taxonomy' => array( array( 'where' => (object) array( 'taxonomy' => 'nav_menu' ) ) ),
+ 'object input without a where' => array( (object) array( 'fields' => array( 'id' ) ) ),
+ );
+ }
+
+ /**
+ * The permission callback refuses malformed input and taxonomies that are not exposed.
+ *
+ * @ticket 66743
+ * @dataProvider data_inputs_refused_by_the_permission_callback
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_refuses_malformed_input( $input ): void {
+ $this->login_as( 'administrator' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( $input ), 'The permission callback should refuse the input.' );
+ }
+
+ /**
+ * Returns input forms that count as objects.
+ *
+ * @since 7.3.0
+ *
+ * @return array The inputs.
+ */
+ public static function data_object_input_forms(): array {
+ $where = array( 'taxonomy' => 'post_tag' );
+
+ return array(
+ 'arrays' => array( array( 'where' => $where ) ),
+ 'input that is an object' => array( (object) array( 'where' => $where ) ),
+ 'where that is an object' => array( array( 'where' => (object) $where ) ),
+ 'both that are objects' => array( (object) array( 'where' => (object) $where ) ),
+ );
+ }
+
+ /**
+ * The permission callback accepts the input and `where` as arrays or objects.
+ *
+ * @ticket 66743
+ * @dataProvider data_object_input_forms
+ * @since 7.3.0
+ *
+ * @param mixed $input The input.
+ */
+ public function test_permission_callback_accepts_arrays_and_objects( $input ): void {
+ $this->login_as( 'subscriber' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertTrue( $permission( $input ), 'The permission callback should accept the input.' );
+ }
+
+ /**
+ * A logged-out visitor cannot query, also for a public taxonomy.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_logged_out_visitor_is_refused(): void {
+ $this->login_as( 'logged_out' );
+
+ $permission = $this->get_ability_callbacks()['permission_callback'];
+
+ $this->assertFalse( $permission( array( 'where' => array( 'taxonomy' => 'category' ) ) ), 'The permission callback should refuse a logged-out visitor.' );
+
+ $result = $this->run_rejected( array( 'where' => array( 'taxonomy' => 'category' ) ), 'Logged out' );
+
+ $this->assert_refused( $result, 'Logged out' );
+ }
+
+ /**
+ * Returns every logged-in role, a user with no role on the site included.
+ *
+ * @since 7.3.0
+ *
+ * @return array The roles.
+ */
+ public static function data_logged_in_roles(): array {
+ return array(
+ 'administrator' => array( 'administrator' ),
+ 'editor' => array( 'editor' ),
+ 'author' => array( 'author' ),
+ 'contributor' => array( 'contributor' ),
+ 'subscriber' => array( 'subscriber' ),
+ 'user with no role' => array( 'no_role' ),
+ );
+ }
+
+ /**
+ * Any logged-in user can query terms, without a capability.
+ *
+ * @ticket 66743
+ * @dataProvider data_logged_in_roles
+ * @since 7.3.0
+ *
+ * @param string $role The role.
+ */
+ public function test_any_logged_in_user_can_query( string $role ): void {
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => array( 'taxonomy' => 'post_tag' ) ) );
+
+ $this->assertSame( array( self::$term_ids['alpha'], self::$term_ids['beta'] ), $this->item_ids( $result, $role ), 'Every tag should be listed by name.' );
+ }
+
+ /**
+ * A super admin who has no role on the site can query.
+ *
+ * @ticket 66743
+ * @group ms-required
+ * @since 7.3.0
+ */
+ public function test_super_admin_can_query(): void {
+ $this->login_as( 'super_admin' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => array( 'taxonomy' => 'post_tag' ) ) );
+
+ $this->assertSame( array( self::$term_ids['alpha'], self::$term_ids['beta'] ), $this->item_ids( $result, 'Super admin' ), 'Every tag should be listed by name.' );
+ }
+
+ /**
+ * Returns taxonomies that the execute callback does not find.
+ *
+ * @since 7.3.0
+ *
+ * @return array The taxonomies.
+ */
+ public static function data_taxonomies_that_are_not_found(): array {
+ return array(
+ 'taxonomy turned off after registration' => array( 'category' ),
+ 'taxonomy that is not exposed' => array( 'nav_menu' ),
+ 'taxonomy that does not exist' => array( 'tt_missing' ),
+ );
+ }
+
+ /**
+ * The execute callback checks itself that the taxonomy is exposed.
+ *
+ * @ticket 66743
+ * @dataProvider data_taxonomies_that_are_not_found
+ * @since 7.3.0
+ *
+ * @param string $taxonomy The taxonomy.
+ */
+ public function test_execute_refuses_a_taxonomy_that_is_not_exposed( string $taxonomy ): void {
+ $this->login_as( 'administrator' );
+
+ $execute = $this->get_ability_callbacks()['execute_callback'];
+
+ get_taxonomy( 'category' )->show_in_abilities = false;
+
+ $result = $this->call_rejected( $execute, array( 'where' => array( 'taxonomy' => $taxonomy ) ), $taxonomy );
+
+ $this->assert_taxonomy_not_found( $result, $taxonomy );
+ }
+
+ /**
+ * Returns parent filters on a flat taxonomy.
+ *
+ * @since 7.3.0
+ *
+ * @return array}> The filters.
+ */
+ public static function data_parent_filters_on_a_flat_taxonomy(): array {
+ return array(
+ 'parent of zero' => array( array( 'parent' => 0 ) ),
+ 'parent of a term' => array( array( 'parent' => 5 ) ),
+ 'parent with the later filters' => array(
+ array(
+ 'parent' => 0,
+ 'hide_empty' => true,
+ 'post' => self::MISSING_ID,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * A parent filter on a flat taxonomy is an error, also for zero, before the other filters.
+ *
+ * @ticket 66743
+ * @dataProvider data_parent_filters_on_a_flat_taxonomy
+ * @since 7.3.0
+ *
+ * @param array $where The filters next to the taxonomy.
+ */
+ public function test_parent_filter_on_a_flat_taxonomy_is_an_error( array $where ): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected( array( 'where' => array( 'taxonomy' => 'post_tag' ) + $where ), 'Parent on tags' );
+ $message = 'The "post_tag" taxonomy is not hierarchical.';
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, $message, 'Parent on tags', array( 'params' => array( 'where[parent]' => $message ) ) );
+ }
+
+ /**
+ * Hiding empty terms cannot be combined with the post filter, and that is checked before the post.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_hide_empty_with_the_post_filter_is_an_error(): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $message = 'The hide_empty filter cannot be combined with the post filter.';
+ $extra = array( 'params' => array( 'where[hide_empty]' => $message ) );
+
+ foreach ( array( self::$post_ids['published'], self::MISSING_ID ) as $post_id ) {
+ $context = "Hide empty with post {$post_id}";
+ $result = $this->run_rejected(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => $post_id,
+ 'hide_empty' => true,
+ ),
+ ),
+ $context
+ );
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, $message, $context, $extra );
+ }
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => self::$post_ids['published'],
+ 'hide_empty' => false,
+ ),
+ )
+ );
+
+ $this->assertSame( array( self::$term_ids['beta'] ), $this->item_ids( $result, 'Hide empty false' ), 'Hiding no terms should be allowed with the post filter.' );
+ }
+
+ /**
+ * Returns posts that the post filter refuses, with the user who asks.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_posts_refused_by_the_post_filter(): array {
+ return array(
+ 'post that does not exist' => array( 'missing', 'administrator' ),
+ 'post type without the taxonomy' => array( 'page', 'administrator' ),
+ 'private post the user cannot read' => array( 'private', 'subscriber' ),
+ 'private post for a user with no role' => array( 'private', 'no_role' ),
+ );
+ }
+
+ /**
+ * A post that is missing, of a type without the taxonomy or not readable gives one identical error.
+ *
+ * @ticket 66743
+ * @dataProvider data_posts_refused_by_the_post_filter
+ * @since 7.3.0
+ *
+ * @param string $post The post fixture name, or `missing`.
+ * @param string $role The role.
+ */
+ public function test_post_filter_refuses_a_post_that_cannot_be_used( string $post, string $role ): void {
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $post_id = 'missing' === $post ? self::MISSING_ID : self::$post_ids[ $post ];
+ $result = $this->run_rejected(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'post' => $post_id,
+ ),
+ ),
+ $post
+ );
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, 'Invalid post ID.', $post, array( 'params' => array( 'where[post]' => 'Invalid post ID.' ) ) );
+ }
+
+ /**
+ * A published post that is not publicly viewable is refused for a user who cannot edit it,
+ * with the same error, and listed for a user who can.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_post_filter_refuses_a_published_post_that_is_not_publicly_viewable(): void {
+ register_post_type(
+ 'tt_internal',
+ array(
+ 'public' => false,
+ 'show_in_abilities' => true,
+ 'map_meta_cap' => true,
+ 'taxonomies' => array( 'post_tag' ),
+ )
+ );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_type' => 'tt_internal',
+ 'post_status' => 'publish',
+ )
+ );
+ wp_set_object_terms( $post_id, array( self::$term_ids['alpha'] ), 'post_tag' );
+
+ $this->assertSame( 'publish', get_post_status( $post_id ), 'The post should be published.' );
+ $this->assertFalse( is_post_publicly_viewable( $post_id ), 'The post should not be publicly viewable.' );
+
+ $input = array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => $post_id,
+ ),
+ );
+
+ $this->register_abilities();
+
+ foreach ( array( 'no_role', 'subscriber', 'author' ) as $role ) {
+ $this->login_as( $role );
+
+ $this->assertFalse( current_user_can( 'edit_post', $post_id ), "Precondition: The {$role} user should not be able to edit the post." );
+
+ $result = $this->run_rejected( $input, $role );
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, 'Invalid post ID.', $role, array( 'params' => array( 'where[post]' => 'Invalid post ID.' ) ) );
+ }
+
+ $this->login_as( 'editor' );
+
+ $this->assertSame( array( self::$term_ids['alpha'] ), $this->item_ids( $this->run_ability( $input ), 'Editor' ), 'A user who can edit the post should get its tags.' );
+ }
+
+ /**
+ * Returns post IDs the schema refuses, with whether a global post is set.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_post_ids_below_one(): array {
+ return array(
+ 'post zero' => array( 0, false ),
+ 'post minus one' => array( -1, false ),
+ 'post zero with a global post' => array( 0, true ),
+ 'post minus one with a global post' => array( -1, true ),
+ );
+ }
+
+ /**
+ * A post ID below 1 that reaches the execute callback gives the error of the other posts
+ * the filter refuses, also when a global post with tags is set.
+ *
+ * @ticket 66743
+ * @dataProvider data_post_ids_below_one
+ * @since 7.3.0
+ *
+ * @param int $post The post ID the schema refuses.
+ * @param bool $with_global Whether to set the global post to a post with tags.
+ */
+ public function test_post_filter_refuses_a_post_id_below_one( int $post, bool $with_global ): void {
+ if ( $with_global ) {
+ $GLOBALS['post'] = get_post( self::$post_ids['published'] );
+ $this->assertNotEmpty( get_the_terms( $GLOBALS['post'], 'post_tag' ), 'The global post should have tags.' );
+ }
+
+ $this->login_as( 'administrator' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => $post,
+ ),
+ ),
+ "Post {$post}"
+ );
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, 'Invalid post ID.', "Post {$post}", array( 'params' => array( 'where[post]' => 'Invalid post ID.' ) ) );
+ }
+
+ /**
+ * The terms of a published post are listed with the default fields.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_lists_the_tags_of_a_post(): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => self::$post_ids['published'],
+ ),
+ )
+ );
+
+ $this->assertSame(
+ array(
+ 'items' => array( $this->expected_item( self::$term_ids['beta'], self::DEFAULT_KEYS ) ),
+ 'pagination' => array(
+ 'total' => 1,
+ 'total_pages' => 1,
+ ),
+ ),
+ $result,
+ 'The tags of the post should be listed with the default fields.'
+ );
+ }
+
+ /**
+ * The terms of a private post are listed for a user who can read it.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_lists_the_tags_of_a_private_post_the_user_can_read(): void {
+ $this->login_as( 'editor' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => self::$post_ids['private'],
+ ),
+ )
+ );
+
+ $this->assertSame( array( self::$term_ids['alpha'] ), $this->item_ids( $result, 'Private post' ), 'The tags of the private post should be listed.' );
+ }
+
+ /**
+ * The post filter works for a post type that is registered as exposed to abilities.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_post_filter_accepts_a_post_type_that_is_exposed(): void {
+ register_post_type(
+ 'tt_book',
+ array(
+ 'public' => true,
+ 'show_in_abilities' => true,
+ 'taxonomies' => array( 'post_tag' ),
+ )
+ );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_type' => 'tt_book',
+ 'post_status' => 'publish',
+ )
+ );
+ wp_set_object_terms( $post_id, array( self::$term_ids['alpha'] ), 'post_tag' );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => $post_id,
+ ),
+ )
+ );
+
+ $this->assertSame( array( self::$term_ids['alpha'] ), $this->item_ids( $result, 'Book' ), 'The tags of the book should be listed.' );
+ }
+
+ /**
+ * A published post of a public post type that is not exposed to abilities gives the error
+ * of the other posts the filter refuses, for every user.
+ *
+ * @ticket 66743
+ * @dataProvider data_logged_in_roles
+ * @since 7.3.0
+ *
+ * @param string $role The role.
+ */
+ public function test_post_filter_refuses_a_post_type_that_is_not_exposed( string $role ): void {
+ register_post_type(
+ 'tt_book',
+ array(
+ 'public' => true,
+ 'taxonomies' => array( 'post_tag' ),
+ )
+ );
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_type' => 'tt_book',
+ 'post_status' => 'publish',
+ )
+ );
+ wp_set_object_terms( $post_id, array( self::$term_ids['alpha'] ), 'post_tag' );
+
+ $this->assertTrue( is_post_publicly_viewable( $post_id ), 'Precondition: The post should be publicly viewable.' );
+
+ $this->login_as( $role );
+ $this->register_abilities();
+
+ $result = $this->run_rejected(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => $post_id,
+ ),
+ ),
+ $role
+ );
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, 'Invalid post ID.', $role, array( 'params' => array( 'where[post]' => 'Invalid post ID.' ) ) );
+ }
+
+ /**
+ * The terms of a post are paged by the ability.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_pages_the_terms_of_a_post(): void {
+ $tags = $this->create_tags( 2 );
+ wp_set_object_terms( self::$post_ids['published'], $tags['ids'], 'post_tag', true );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'post' => self::$post_ids['published'],
+ ),
+ 'fields' => array( 'name' ),
+ 'pagination' => array(
+ 'page' => 2,
+ 'per_page' => 2,
+ ),
+ )
+ );
+
+ $this->assertSame(
+ array(
+ 'items' => array(
+ array(
+ 'id' => $tags['ids'][1],
+ 'name' => 'extra 02',
+ ),
+ ),
+ 'pagination' => array(
+ 'total' => 3,
+ 'total_pages' => 2,
+ ),
+ ),
+ $result,
+ 'The second page should hold the last tag of the post by name.'
+ );
+ }
+
+ /**
+ * The top-level categories are listed by name with the chosen fields, two per page.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_lists_top_level_categories_with_chosen_fields(): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $input = array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'parent' => 0,
+ ),
+ 'fields' => array( 'name', 'slug', 'count' ),
+ 'pagination' => array( 'per_page' => 2 ),
+ );
+ $keys = array( 'name', 'slug', 'count' );
+ $result = $this->run_ability( $input );
+
+ $this->assertSame(
+ array(
+ 'items' => array(
+ $this->expected_item( self::$term_ids['empty'], $keys ),
+ $this->expected_item( self::$term_ids['news'], $keys ),
+ ),
+ 'pagination' => array(
+ 'total' => 3,
+ 'total_pages' => 2,
+ ),
+ ),
+ $result,
+ 'The first page should hold the first two top-level categories by name.'
+ );
+ $this->assertSame( array( 'id', 'name', 'slug', 'count' ), array_keys( $result['items'][0] ), 'The item should hold the ID and the chosen fields.' );
+ $this->assertSame( 1, $result['items'][1]['count'], 'The count should be an integer.' );
+
+ $input['pagination']['page'] = 2;
+
+ $this->assertSame( array( self::$term_ids['uncategorized'] ), $this->item_ids( $this->run_ability( $input ), 'Page 2' ), 'The second page should hold the last top-level category.' );
+ }
+
+ /**
+ * Returns filters with the categories they match, by name.
+ *
+ * The last three cases put a post in a category first. With empty categories hidden, an
+ * empty category is still listed when one of its descendants is in use.
+ *
+ * @since 7.3.0
+ *
+ * @return array, expected: list, used?: string}> The cases.
+ */
+ public static function data_category_filters(): array {
+ return array(
+ 'no filter' => array( array(), array( 'empty', 'news', 'product_updates', 'roadmap', 'uncategorized' ) ),
+ 'children of a category' => array( array( 'parent' => 'news' ), array( 'product_updates' ) ),
+ 'hide empty' => array( array( 'hide_empty' => true ), array( 'news' ) ),
+ 'hide empty set to false' => array( array( 'hide_empty' => false ), array( 'empty', 'news', 'product_updates', 'roadmap', 'uncategorized' ) ),
+ 'IDs with unknown and tag IDs' => array( array( 'ids' => array( 'roadmap', 'news', 'missing', 'alpha' ) ), array( 'news', 'roadmap' ) ),
+ 'slugs with unknown and tags' => array( array( 'slugs' => array( 'roadmap', 'news', 'nothing', 'beta' ) ), array( 'news', 'roadmap' ) ),
+ 'slugs that are sanitized' => array( array( 'slugs' => array( 'ROADMAP', 'News', '!!!' ) ), array( 'news', 'roadmap' ) ),
+ 'IDs and slugs together' => array(
+ array(
+ 'ids' => array( 'news', 'roadmap' ),
+ 'slugs' => array( 'news', 'empty' ),
+ ),
+ array( 'news' ),
+ ),
+ 'hide empty, used descendant' => array( array( 'hide_empty' => true ), array( 'news', 'product_updates', 'roadmap' ), 'roadmap' ),
+ 'hide empty with a parent' => array(
+ array(
+ 'parent' => 'news',
+ 'hide_empty' => true,
+ ),
+ array( 'product_updates' ),
+ 'roadmap',
+ ),
+ 'hide empty with IDs' => array(
+ array(
+ 'ids' => array( 'product_updates', 'empty' ),
+ 'hide_empty' => true,
+ ),
+ array( 'product_updates' ),
+ 'roadmap',
+ ),
+ );
+ }
+
+ /**
+ * The filters select the categories they name, ordered by name.
+ *
+ * @ticket 66743
+ * @dataProvider data_category_filters
+ * @since 7.3.0
+ *
+ * @param array $where The filters, with fixture names for IDs.
+ * @param list $expected The fixture names of the expected categories.
+ * @param string|null $used Optional. The fixture name of a category that gets a published post first.
+ */
+ public function test_filters_select_the_categories( array $where, array $expected, ?string $used = null ): void {
+ if ( null !== $used ) {
+ self::factory()->post->create(
+ array(
+ 'post_status' => 'publish',
+ 'post_category' => array( self::$term_ids[ $used ] ),
+ )
+ );
+ }
+
+ $ids = static function ( array $names ): array {
+ return array_map(
+ static function ( string $name ): int {
+ return 'missing' === $name ? self::MISSING_ID : self::$term_ids[ $name ];
+ },
+ $names
+ );
+ };
+
+ if ( isset( $where['parent'] ) ) {
+ $where['parent'] = self::$term_ids[ $where['parent'] ];
+ }
+ if ( isset( $where['ids'] ) ) {
+ $where['ids'] = $ids( $where['ids'] );
+ }
+ if ( isset( $where['slugs'] ) ) {
+ $where['slugs'] = array_map(
+ static function ( string $name ): string {
+ return isset( self::$term_ids[ $name ] ) ? get_term( self::$term_ids[ $name ] )->slug : $name;
+ },
+ $where['slugs']
+ );
+ }
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => array( 'taxonomy' => 'category' ) + $where ) );
+
+ $this->assertSame( $ids( $expected ), $this->item_ids( $result, 'Filters' ), 'The matching categories should be listed by name.' );
+ $this->assertSame( count( $expected ), $result['pagination']['total'], 'The total should count the matching categories.' );
+ $this->assertSame( 1, $result['pagination']['total_pages'], 'The categories should fit on one page.' );
+ }
+
+ /**
+ * The registered query arguments of a taxonomy apply, but the paging stays the ability's own.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taxonomy_query_arguments_apply_with_the_ability_paging(): void {
+ register_taxonomy(
+ 'tt_ordered',
+ 'post',
+ array(
+ 'show_in_abilities' => true,
+ 'args' => array(
+ 'orderby' => 'slug',
+ 'order' => 'DESC',
+ 'number' => 1,
+ 'offset' => 5,
+ ),
+ )
+ );
+
+ $ids = array();
+ foreach ( array(
+ 'Apple' => 'a-slug',
+ 'Banana' => 'c-slug',
+ 'Cherry' => 'b-slug',
+ ) as $name => $slug ) {
+ $ids[ $slug ] = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_ordered',
+ 'name' => $name,
+ 'slug' => $slug,
+ )
+ );
+ }
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $input = array(
+ 'where' => array( 'taxonomy' => 'tt_ordered' ),
+ 'pagination' => array( 'per_page' => 2 ),
+ );
+
+ $this->assertSame( array( $ids['c-slug'], $ids['b-slug'] ), $this->item_ids( $this->run_ability( $input ), 'Page 1' ), 'The first page should hold two terms in the order the taxonomy sets.' );
+
+ $input['pagination']['page'] = 2;
+ $result = $this->run_ability( $input );
+
+ $this->assertSame( array( $ids['a-slug'] ), $this->item_ids( $result, 'Page 2' ), 'The second page should hold the last term in the order the taxonomy sets.' );
+ $this->assertSame(
+ array(
+ 'total' => 3,
+ 'total_pages' => 2,
+ ),
+ $result['pagination'],
+ 'The totals should count every term of the taxonomy.'
+ );
+ }
+
+ /**
+ * Returns kinds of result a taxonomy can be registered to query.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_registered_kinds_of_result(): array {
+ return array(
+ 'term IDs' => array( 'ids' ),
+ 'term names' => array( 'names' ),
+ 'a count' => array( 'count' ),
+ );
+ }
+
+ /**
+ * The items are terms, whatever kind of result the registered query arguments of a
+ * taxonomy ask for.
+ *
+ * @ticket 66743
+ * @dataProvider data_registered_kinds_of_result
+ * @since 7.3.0
+ *
+ * @param string $fields The kind of result the taxonomy is registered to query.
+ */
+ public function test_taxonomy_query_arguments_do_not_change_the_kind_of_result( string $fields ): void {
+ register_taxonomy(
+ 'tt_kind',
+ 'post',
+ array(
+ 'show_in_abilities' => true,
+ 'args' => array( 'fields' => $fields ),
+ )
+ );
+ $term_id = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_kind',
+ 'name' => 'Apple',
+ )
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => array( 'taxonomy' => 'tt_kind' ) ) );
+
+ $this->assertSame( array( $term_id ), $this->item_ids( $result, 'Kind of result' ), 'The term should be listed.' );
+ $this->assertSame( 'Apple', $result['items'][0]['name'], 'The item should hold the name of the term.' );
+ $this->assertSame(
+ array(
+ 'total' => 1,
+ 'total_pages' => 1,
+ ),
+ $result['pagination'],
+ 'The totals should count the term.'
+ );
+ }
+
+ /**
+ * The registered query arguments of a taxonomy apply to the terms of a post as Core applies
+ * them, paging included, and the totals count every term of the post.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taxonomy_query_arguments_apply_to_the_terms_of_a_post_as_core_applies_them(): void {
+ register_taxonomy(
+ 'tt_limited',
+ 'post',
+ array(
+ 'show_in_abilities' => true,
+ 'args' => array( 'number' => 1 ),
+ )
+ );
+
+ $post_id = self::$post_ids['published'];
+ $names = array( 'Apple', 'Banana', 'Cherry' );
+ foreach ( $names as $name ) {
+ self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_limited',
+ 'name' => $name,
+ )
+ );
+ }
+ wp_set_object_terms( $post_id, $names, 'tt_limited' );
+
+ $per_page = 2;
+ $expected = wp_list_pluck(
+ wp_get_object_terms(
+ $post_id,
+ 'tt_limited',
+ array(
+ 'number' => $per_page,
+ 'offset' => 0,
+ )
+ ),
+ 'term_id'
+ );
+
+ $this->assertLessThan( $per_page, count( $expected ), 'Precondition: Core should list fewer terms of the post than the page size.' );
+ $this->assertNotEmpty( $expected, 'Precondition: Core should list a term of the post.' );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'tt_limited',
+ 'post' => $post_id,
+ ),
+ 'pagination' => array( 'per_page' => $per_page ),
+ )
+ );
+
+ $this->assertSame( array_map( 'intval', $expected ), $this->item_ids( $result, 'Terms of the post' ), 'The page should hold what Core lists for the post.' );
+ $this->assertSame(
+ array(
+ 'total' => 3,
+ 'total_pages' => 2,
+ ),
+ $result['pagination'],
+ 'The totals should count every term of the post.'
+ );
+ }
+
+ /**
+ * A registered query argument of a taxonomy replaces the ability's own argument of the
+ * same key.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_taxonomy_query_argument_replaces_the_ability_argument(): void {
+ register_taxonomy(
+ 'tt_filled',
+ 'post',
+ array(
+ 'show_in_abilities' => true,
+ 'args' => array( 'hide_empty' => true ),
+ )
+ );
+ $filled = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_filled',
+ 'name' => 'Filled',
+ )
+ );
+ self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_filled',
+ 'name' => 'Unused',
+ )
+ );
+ wp_set_object_terms( self::$post_ids['published'], array( $filled ), 'tt_filled' );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ foreach ( array(
+ 'absent' => array(),
+ 'false' => array( 'hide_empty' => false ),
+ ) as $case => $where ) {
+ $result = $this->run_ability( array( 'where' => array( 'taxonomy' => 'tt_filled' ) + $where ) );
+
+ $this->assertSame( array( $filled ), $this->item_ids( $result, "hide_empty {$case}" ), "With hide_empty {$case}, the taxonomy's own value should apply." );
+ $this->assertSame(
+ array(
+ 'total' => 1,
+ 'total_pages' => 1,
+ ),
+ $result['pagination'],
+ "With hide_empty {$case}, the totals should count only the terms in use."
+ );
+ }
+ }
+
+ /**
+ * Returns how many terms are listed per page by default.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_default_page_sizes(): array {
+ return array(
+ 'without IDs or slugs' => array( null, 10 ),
+ 'with IDs' => array( 'ids', 100 ),
+ 'with slugs' => array( 'slugs', 100 ),
+ );
+ }
+
+ /**
+ * Ten terms are listed per page by default, a hundred when IDs or slugs are given.
+ *
+ * @ticket 66743
+ * @dataProvider data_default_page_sizes
+ * @since 7.3.0
+ *
+ * @param string|null $filter The list filter, if any.
+ * @param int $per_page The expected page size.
+ */
+ public function test_default_page_size( ?string $filter, int $per_page ): void {
+ $tags = $this->create_tags( 11 );
+ $where = array( 'taxonomy' => 'post_tag' );
+ $total = 13;
+ if ( null !== $filter ) {
+ $where[ $filter ] = $tags[ $filter ];
+ $total = 11;
+ }
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => $where ) );
+
+ $this->assertCount( min( $per_page, $total ), $this->item_ids( $result, 'Default page' ), 'The first page should hold the default number of tags.' );
+ $this->assertSame(
+ array(
+ 'total' => $total,
+ 'total_pages' => (int) ceil( $total / $per_page ),
+ ),
+ $result['pagination'],
+ 'The totals should follow the default page size.'
+ );
+ }
+
+ /**
+ * Returns page sizes the schema refuses, with the page size they read as.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_page_sizes_out_of_bounds(): array {
+ return array(
+ 'zero without IDs or slugs' => array( 0, null, 11, 10 ),
+ 'minus one without IDs or slugs' => array( -1, null, 11, 10 ),
+ 'zero with IDs' => array( 0, 'ids', 11, 100 ),
+ 'minus one with slugs' => array( -1, 'slugs', 11, 100 ),
+ 'above the maximum' => array( 500, null, 101, 100 ),
+ );
+ }
+
+ /**
+ * A page size below 1 that reaches the execute callback reads as the default page size,
+ * and one above 100 reads as 100.
+ *
+ * @ticket 66743
+ * @dataProvider data_page_sizes_out_of_bounds
+ * @since 7.3.0
+ *
+ * @param int $per_page The page size the schema refuses.
+ * @param string|null $filter The list filter, if any.
+ * @param int $extra How many tags to add to the two fixture tags.
+ * @param int $size The page size it should read as.
+ */
+ public function test_page_size_out_of_bounds_is_bounded( int $per_page, ?string $filter, int $extra, int $size ): void {
+ $tags = $this->create_tags( $extra );
+ $where = array( 'taxonomy' => 'post_tag' );
+ $total = $extra + 2;
+ if ( null !== $filter ) {
+ $where[ $filter ] = $tags[ $filter ];
+ $total = $extra;
+ }
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation(
+ array(
+ 'where' => $where,
+ 'pagination' => array( 'per_page' => $per_page ),
+ ),
+ "Page size {$per_page}"
+ );
+
+ $this->assertCount( min( $size, $total ), $this->item_ids( $result, "Page size {$per_page}" ), "The first page should hold {$size} tags at most." );
+ $this->assertSame(
+ array(
+ 'total' => $total,
+ 'total_pages' => (int) ceil( $total / $size ),
+ ),
+ $result['pagination'],
+ "The totals should follow a page size of {$size}."
+ );
+ }
+
+ /**
+ * Returns page numbers the schema refuses.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_pages_below_one(): array {
+ return array(
+ 'page zero' => array( 0 ),
+ 'page minus one' => array( -1 ),
+ );
+ }
+
+ /**
+ * A page number below 1 that reaches the execute callback reads as page 1.
+ *
+ * @ticket 66743
+ * @dataProvider data_pages_below_one
+ * @since 7.3.0
+ *
+ * @param int $page The page number the schema refuses.
+ */
+ public function test_page_below_one_reads_as_the_first_page( int $page ): void {
+ $this->create_tags( 11 );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $input = array(
+ 'where' => array( 'taxonomy' => 'post_tag' ),
+ 'pagination' => array( 'per_page' => 5 ),
+ );
+ $first = $this->run_ability( $input );
+
+ $input['pagination']['page'] = $page;
+
+ $result = $this->run_past_validation( $input, "Page {$page}" );
+
+ $this->assertCount( 5, $this->item_ids( $first, 'Page 1' ), 'The first page should hold five tags.' );
+ $this->assertSame( $first, $result, "Page {$page} should give the first page." );
+ }
+
+ /**
+ * A page beyond the last one is an error, also with an explicit page size.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_page_beyond_the_last_is_an_error(): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected(
+ array(
+ 'where' => array( 'taxonomy' => 'category' ),
+ 'pagination' => array(
+ 'page' => 4,
+ 'per_page' => 2,
+ ),
+ ),
+ 'Page 4'
+ );
+
+ $this->assert_error( $result, 'terms_invalid_page_number', 404, 'The page number requested is larger than the number of pages available.', 'Page 4' );
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array( 'taxonomy' => 'category' ),
+ 'pagination' => array(
+ 'page' => 3,
+ 'per_page' => 2,
+ ),
+ )
+ );
+
+ $this->assertSame( array( self::$term_ids['uncategorized'] ), $this->item_ids( $result, 'Page 3' ), 'The last page should hold the last category.' );
+ }
+
+ /**
+ * With empty categories hidden, an empty category that has a descendant in use is listed
+ * and counted, so the pages reach every listed category.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_pages_count_an_empty_category_with_a_used_descendant(): void {
+ self::factory()->post->create(
+ array(
+ 'post_status' => 'publish',
+ 'post_category' => array( self::$term_ids['roadmap'] ),
+ )
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $input = array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'hide_empty' => true,
+ ),
+ 'pagination' => array(
+ 'page' => 3,
+ 'per_page' => 1,
+ ),
+ );
+
+ $result = $this->run_ability( $input );
+
+ $this->assertSame( array( self::$term_ids['roadmap'] ), $this->item_ids( $result, 'Page 3' ), 'The third page should hold the used child category.' );
+ $this->assertSame(
+ array(
+ 'total' => 3,
+ 'total_pages' => 3,
+ ),
+ $result['pagination'],
+ 'The totals should count the two used categories and the empty category between them.'
+ );
+
+ $input['pagination']['page'] = 4;
+ $result = $this->run_rejected( $input, 'Page 4' );
+
+ $this->assert_error( $result, 'terms_invalid_page_number', 404, 'The page number requested is larger than the number of pages available.', 'Page 4' );
+ }
+
+ /**
+ * Filters that match nothing give an empty list and zero totals, on any page.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_no_match_gives_an_empty_list(): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $empty = array(
+ 'items' => array(),
+ 'pagination' => array(
+ 'total' => 0,
+ 'total_pages' => 0,
+ ),
+ );
+
+ foreach ( array( 1, 3 ) as $page ) {
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'ids' => array( self::MISSING_ID, self::$term_ids['alpha'] ),
+ ),
+ 'pagination' => array( 'page' => $page ),
+ )
+ );
+
+ $this->assertSame( $empty, $result, "Page {$page} of no match should be an empty list with zero totals." );
+ }
+ }
+
+ /**
+ * A total that is not a number counts as zero, and the page of terms is still returned.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_total_that_is_not_a_number_counts_as_zero(): void {
+ add_filter(
+ 'terms_pre_query',
+ static function ( $terms, WP_Term_Query $query ) {
+ return 'count' === $query->query_vars['fields'] ? 'not a number' : $terms;
+ },
+ 10,
+ 2
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => array( 'taxonomy' => 'post_tag' ) ) );
+
+ $this->assertSame( array( self::$term_ids['alpha'], self::$term_ids['beta'] ), $this->item_ids( $result, 'Not a number' ), 'The tags should still be listed.' );
+ $this->assertSame(
+ array(
+ 'total' => 0,
+ 'total_pages' => 0,
+ ),
+ $result['pagination'],
+ 'The totals should be zero.'
+ );
+ }
+
+ /**
+ * Returns the terms Core lists for the tags, or for the tags of the published post.
+ *
+ * @since 7.3.0
+ *
+ * @param bool $with_post Whether to list the tags of the published post.
+ * @return array The result of Core's call.
+ */
+ private function core_tag_result( bool $with_post ): array {
+ if ( $with_post ) {
+ return wp_get_object_terms( self::$post_ids['published'], 'post_tag' );
+ }
+
+ return get_terms(
+ array(
+ 'taxonomy' => 'post_tag',
+ 'hide_empty' => false,
+ )
+ );
+ }
+
+ /**
+ * Returns the filters through which a result that is not a term can reach the ability.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_result_filters(): array {
+ return array(
+ 'terms of the taxonomy' => array( 'get_terms', false ),
+ 'terms of a post' => array( 'wp_get_object_terms', true ),
+ );
+ }
+
+ /**
+ * Results that are not terms are skipped.
+ *
+ * @ticket 66743
+ * @dataProvider data_result_filters
+ * @since 7.3.0
+ *
+ * @param string $filter The filter that adds the results.
+ * @param bool $with_post Whether to filter by the post.
+ */
+ public function test_results_that_are_not_terms_are_skipped( string $filter, bool $with_post ): void {
+ add_filter(
+ $filter,
+ static function ( $terms ) {
+ if ( ! is_array( $terms ) ) {
+ return $terms;
+ }
+
+ $terms[] = 'not a term';
+ $terms[] = 5;
+ $terms[] = (object) array( 'term_id' => self::$term_ids['alpha'] );
+
+ return $terms;
+ }
+ );
+
+ $core = $this->core_tag_result( $with_post );
+
+ $this->assertContains( 'not a term', $core, 'Precondition: the filter should add the entries on this path.' );
+
+ $where = array( 'taxonomy' => 'post_tag' );
+ if ( $with_post ) {
+ $where['post'] = self::$post_ids['published'];
+ }
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => $where ) );
+
+ $expected = $with_post ? array( self::$term_ids['beta'] ) : array( self::$term_ids['alpha'], self::$term_ids['beta'] );
+
+ $this->assertSame( $expected, $this->item_ids( $result, $filter ), 'Only the terms should be listed.' );
+ }
+
+ /**
+ * A term of another taxonomy that a filter adds to the result is skipped.
+ *
+ * @ticket 66743
+ * @dataProvider data_result_filters
+ * @since 7.3.0
+ *
+ * @param string $filter The filter that adds the term.
+ * @param bool $with_post Whether to filter by the post.
+ */
+ public function test_terms_of_another_taxonomy_are_skipped( string $filter, bool $with_post ): void {
+ add_filter(
+ $filter,
+ static function ( $terms ) {
+ if ( ! is_array( $terms ) ) {
+ return $terms;
+ }
+
+ $terms[] = get_term( self::$term_ids['news'], 'category' );
+
+ return $terms;
+ }
+ );
+
+ $foreign = array_filter(
+ $this->core_tag_result( $with_post ),
+ static function ( $term ): bool {
+ return $term instanceof WP_Term && 'category' === $term->taxonomy;
+ }
+ );
+
+ $this->assertCount( 1, $foreign, 'Precondition: the filter should add the category on this path.' );
+
+ $where = array( 'taxonomy' => 'post_tag' );
+ if ( $with_post ) {
+ $where['post'] = self::$post_ids['published'];
+ }
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => $where ) );
+
+ $expected = $with_post ? array( self::$term_ids['beta'] ) : array( self::$term_ids['alpha'], self::$term_ids['beta'] );
+
+ $this->assertSame( $expected, $this->item_ids( $result, $filter ), 'Only the tags should be listed.' );
+ }
+
+ /**
+ * Returns ID list entries below 1.
+ *
+ * @since 7.3.0
+ *
+ * @return array The entries, with `-` and a fixture name for a negative ID.
+ */
+ public static function data_id_entries_below_one(): array {
+ return array(
+ 'ID zero' => array( 0 ),
+ 'negative ID' => array( '-news' ),
+ );
+ }
+
+ /**
+ * An entry of the ID list below 1 that reaches the execute callback is left out, and the
+ * other IDs are queried.
+ *
+ * @ticket 66743
+ * @dataProvider data_id_entries_below_one
+ * @since 7.3.0
+ *
+ * @param int|string $entry The entry, with `-` and a fixture name for a negative ID.
+ */
+ public function test_id_entry_below_one_is_left_out( $entry ): void {
+ if ( is_string( $entry ) ) {
+ $entry = -self::$term_ids[ substr( $entry, 1 ) ];
+ }
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'ids' => array( self::$term_ids['roadmap'], $entry ),
+ ),
+ ),
+ "Entry {$entry}"
+ );
+
+ $this->assertSame(
+ array(
+ 'items' => array( $this->expected_item( self::$term_ids['roadmap'], self::DEFAULT_KEYS ) ),
+ 'pagination' => array(
+ 'total' => 1,
+ 'total_pages' => 1,
+ ),
+ ),
+ $result,
+ 'Only the valid ID should be queried.'
+ );
+ }
+
+ /**
+ * Returns taxonomies with the error a parent filter below 0 gives on them.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_parent_filters_below_zero(): array {
+ return array(
+ 'hierarchical taxonomy' => array( 'category', 'The parent filter must be a non-negative integer.' ),
+ 'flat taxonomy' => array( 'post_tag', 'The "post_tag" taxonomy is not hierarchical.' ),
+ );
+ }
+
+ /**
+ * A parent filter below 0 that reaches the execute callback is refused; on a flat taxonomy
+ * the error for a parent on that taxonomy comes first.
+ *
+ * @ticket 66743
+ * @dataProvider data_parent_filters_below_zero
+ * @since 7.3.0
+ *
+ * @param string $taxonomy The taxonomy.
+ * @param string $message The expected message.
+ */
+ public function test_parent_filter_below_zero_is_an_error( string $taxonomy, string $message ): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation(
+ array(
+ 'where' => array(
+ 'taxonomy' => $taxonomy,
+ 'parent' => -1,
+ ),
+ ),
+ "Parent -1 on {$taxonomy}"
+ );
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, $message, "Parent -1 on {$taxonomy}", array( 'params' => array( 'where[parent]' => $message ) ) );
+ }
+
+ /**
+ * Returns ID and slug lists the schema refuses, with the parameter they are reported as.
+ *
+ * @since 7.3.0
+ *
+ * @return array, message: string}> The cases.
+ */
+ public static function data_lists_without_a_valid_entry(): array {
+ $ids = 'The ids filter must list one or more valid term IDs.';
+ $slugs = 'The slugs filter must list one or more valid term slugs.';
+
+ return array(
+ 'only the ID zero' => array( 'ids', array( 0 ), $ids ),
+ 'only a negative ID' => array( 'ids', array( '-news' ), $ids ),
+ 'zero and a negative ID' => array( 'ids', array( 0, '-news' ), $ids ),
+ 'no ID' => array( 'ids', array(), $ids ),
+ 'no slug' => array( 'slugs', array(), $slugs ),
+ );
+ }
+
+ /**
+ * An ID list with no entry of at least 1, and a slug list with no entry, that reach the
+ * execute callback are refused.
+ *
+ * @ticket 66743
+ * @dataProvider data_lists_without_a_valid_entry
+ * @since 7.3.0
+ *
+ * @param string $filter The list filter.
+ * @param list $values The entries, with fixture names for IDs and `-` for a negative ID.
+ * @param string $message The expected message.
+ */
+ public function test_list_without_a_valid_entry_is_an_error( string $filter, array $values, string $message ): void {
+ $values = array_map(
+ static function ( $value ) {
+ if ( ! is_string( $value ) ) {
+ return $value;
+ }
+
+ return '-' === $value[0] ? -self::$term_ids[ substr( $value, 1 ) ] : self::$term_ids[ $value ];
+ },
+ $values
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_past_validation(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ $filter => $values,
+ ),
+ ),
+ $filter
+ );
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, $message, $filter, array( 'params' => array( "where[{$filter}]" => $message ) ) );
+ }
+
+ /**
+ * A slug list that the schema accepts, in which no slug is left after sanitizing, is an
+ * error and not an empty page.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_slugs_that_sanitize_to_nothing_are_an_error(): void {
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_rejected(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'slugs' => array( '!!!', '???' ),
+ ),
+ ),
+ 'Slugs'
+ );
+ $message = 'The slugs filter must list one or more valid term slugs.';
+
+ $this->assert_error( $result, 'terms_invalid_filter', 400, $message, 'Slugs', array( 'params' => array( 'where[slugs]' => $message ) ) );
+ }
+
+ /**
+ * Returns each field with the taxonomy it is asked for.
+ *
+ * @since 7.3.0
+ *
+ * @return array, taxonomy: string, keys: list}> The cases.
+ */
+ public static function data_field_lists(): array {
+ $cases = array();
+ foreach ( self::ITEM_KEYS as $key ) {
+ $cases[ "{$key} of a category" ] = array( array( $key ), 'category', array_values( array_unique( array( 'id', $key ) ) ) );
+ }
+
+ return $cases + array(
+ 'parent of a tag' => array( array( 'parent' ), 'post_tag', array( 'id' ) ),
+ 'every field of a tag' => array( self::ITEM_KEYS, 'post_tag', array( 'id', 'taxonomy', 'name', 'slug', 'description', 'count', 'link' ) ),
+ 'every field reversed' => array( array_reverse( self::ITEM_KEYS ), 'category', self::ITEM_KEYS ),
+ 'empty list' => array( array(), 'category', self::DEFAULT_KEYS ),
+ 'fields in another order' => array( array( 'link', 'name', 'id' ), 'category', array( 'id', 'name', 'link' ) ),
+ );
+ }
+
+ /**
+ * The item holds the ID and exactly the requested keys, in their fixed order, and the parent
+ * only for a hierarchical taxonomy.
+ *
+ * @ticket 66743
+ * @dataProvider data_field_lists
+ * @since 7.3.0
+ *
+ * @param list $fields The requested fields.
+ * @param string $taxonomy The taxonomy.
+ * @param list $keys The expected keys, in their order.
+ */
+ public function test_fields_select_the_keys( array $fields, string $taxonomy, array $keys ): void {
+ $term_id = 'category' === $taxonomy ? self::$term_ids['product_updates'] : self::$term_ids['beta'];
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => $taxonomy,
+ 'ids' => array( $term_id ),
+ ),
+ 'fields' => $fields,
+ )
+ );
+
+ $this->assertSame( array( $term_id ), $this->item_ids( $result, 'Fields' ), 'The term should be listed.' );
+ $this->assertSame( $keys, array_keys( $result['items'][0] ), 'The item should hold exactly the expected keys in their order.' );
+ $this->assertSame( $this->expected_item( $term_id, $keys ), $result['items'][0], 'The item should hold the values of the term.' );
+ }
+
+ /**
+ * Every value of an item has its type, and the name and description are the stored values.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_item_holds_the_stored_values(): void {
+ $term_id = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'category',
+ 'name' => 'Tips & tricks',
+ 'description' => 'Bold & plain',
+ 'parent' => self::$term_ids['news'],
+ )
+ );
+ $stored = get_term( $term_id );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'ids' => array( $term_id ),
+ ),
+ 'fields' => self::ITEM_KEYS,
+ )
+ );
+
+ $this->assertSame(
+ array(
+ array(
+ 'id' => $term_id,
+ 'taxonomy' => 'category',
+ 'name' => $stored->name,
+ 'slug' => $stored->slug,
+ 'description' => $stored->description,
+ 'parent' => self::$term_ids['news'],
+ 'count' => 0,
+ 'link' => get_term_link( $stored ),
+ ),
+ ),
+ $result['items'] ?? null,
+ 'The item should hold the stored values with their types.'
+ );
+ $this->assertSame( 'Tips & tricks', $result['items'][0]['name'], 'The name should be the stored name, not decoded.' );
+ $this->assertSame( 'Bold & plain', $result['items'][0]['description'], 'The description should be the stored description, not rendered.' );
+ }
+
+ /**
+ * The link is empty when the term link is not a string.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_link_is_empty_when_the_term_link_is_an_error(): void {
+ add_filter(
+ 'term_link',
+ static function () {
+ return new WP_Error( 'tt_no_link', 'No link.' );
+ }
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability(
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'ids' => array( self::$term_ids['beta'] ),
+ ),
+ 'fields' => array( 'link' ),
+ )
+ );
+
+ $this->assertSame(
+ array(
+ array(
+ 'id' => self::$term_ids['beta'],
+ 'link' => '',
+ ),
+ ),
+ $result['items'] ?? null,
+ 'The link should be empty.'
+ );
+ }
+
+ /**
+ * An exposed taxonomy that is not public can be queried.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_exposed_taxonomy_that_is_not_public_can_be_queried(): void {
+ register_taxonomy(
+ 'tt_private',
+ 'post',
+ array(
+ 'public' => false,
+ 'show_in_abilities' => true,
+ )
+ );
+ $term_id = self::factory()->term->create(
+ array(
+ 'taxonomy' => 'tt_private',
+ 'name' => 'Internal',
+ )
+ );
+
+ $this->login_as( 'subscriber' );
+ $this->register_abilities();
+
+ $result = $this->run_ability( array( 'where' => array( 'taxonomy' => 'tt_private' ) ) );
+
+ $this->assertSame( array( $this->expected_item( $term_id, self::DEFAULT_KEYS ) ), $result['items'] ?? null, 'The term should be listed with the default fields.' );
+ }
+}
diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php
index 0374d38eb37f4..3ae3b4ba3d1a3 100644
--- a/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php
+++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesContentController.php
@@ -2,8 +2,10 @@
declare( strict_types=1 );
+require_once __DIR__ . '/../abilities-api/testcase-content-write-ability.php';
+
/**
- * 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 +410,374 @@ 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}." );
+ }
+
+ /**
+ * Create runs with POST and the input in a JSON body.
+ *
+ * @ticket 66706
+ */
+ 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
+ */
+ 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.'
+ );
+ }
+
+ /**
+ * Returns `permanent` values as they arrive in a query string, or null when it is not sent,
+ * and the outcome.
+ *
+ * @return array The cases.
+ */
+ public static function data_permanent_query_string_values(): array {
+ return array(
+ 'not sent' => array( null, 'trashed' ),
+ 'true' => array( 'true', 'deleted' ),
+ 'false' => array( 'false', 'trashed' ),
+ );
+ }
+
+ /**
+ * Delete runs with DELETE and the input in the query string, where the ID is a string and
+ * `permanent` is read as a boolean.
+ *
+ * @ticket 66706
+ * @dataProvider data_permanent_query_string_values
+ *
+ * @param string|null $permanent The value in the query string, or null when it is not sent.
+ * @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' ) );
+
+ $input = array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => (string) $post_id,
+ ),
+ );
+ if ( null !== $permanent ) {
+ $input['permanent'] = $permanent;
+ }
+
+ $response = $this->server->dispatch( $this->write_request( 'DELETE', 'core/content-delete', $input ) );
+
+ $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 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
+ *
+ * @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 = WP_Abilities_Content_Write_UnitTestCase::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, WP_Abilities_Content_Write_UnitTestCase::snapshot( $post_id ), 'Nothing should be written.' );
+ }
+
+ /**
+ * Returns write requests that fail, and the error response each receives.
+ *
+ * `post` names the post the request targets: `missing` for an ID that no post has, `published`
+ * for a published post by the administrator, `trashed` for a post in the Trash, or null for a
+ * create. `params` is the expected error `params`, or null to skip that check.
+ *
+ * @return array, post: string|null, user: string, status: int, code: string, params?: array}> The cases.
+ */
+ public static function data_failing_write_requests(): array {
+ return array(
+ 'create that fails the schema' => array(
+ 'ability' => 'core/content-create',
+ 'method' => 'POST',
+ 'input' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'post_password' => 'secret',
+ ),
+ ),
+ 'post' => null,
+ 'user' => 'administrator',
+ 'status' => 400,
+ 'code' => 'ability_invalid_input',
+ ),
+ 'update of a missing post' => array(
+ 'ability' => 'core/content-update',
+ 'method' => 'POST',
+ 'input' => array( 'data' => array( 'title' => 'Missing' ) ),
+ 'post' => 'missing',
+ 'user' => 'administrator',
+ 'status' => 404,
+ 'code' => 'content_not_found',
+ ),
+ 'logged-out create' => array(
+ 'ability' => 'core/content-create',
+ 'method' => 'POST',
+ 'input' => array( 'data' => array( 'type' => 'post' ) ),
+ 'post' => null,
+ 'user' => 'logged-out',
+ 'status' => 401,
+ 'code' => 'rest_ability_cannot_execute',
+ ),
+ 'subscriber create' => array(
+ 'ability' => 'core/content-create',
+ 'method' => 'POST',
+ 'input' => array( 'data' => array( 'type' => 'post' ) ),
+ 'post' => null,
+ 'user' => 'subscriber',
+ 'status' => 403,
+ 'code' => 'rest_ability_cannot_execute',
+ ),
+ 'update of a post the user cannot edit' => array(
+ 'ability' => 'core/content-update',
+ 'method' => 'POST',
+ 'input' => array( 'data' => array( 'title' => 'Not mine' ) ),
+ 'post' => 'published',
+ 'user' => 'subscriber',
+ 'status' => 403,
+ 'code' => 'rest_ability_cannot_execute',
+ ),
+ 'create with an unsupported attribute' => array(
+ 'ability' => 'core/content-create',
+ 'method' => 'POST',
+ 'input' => array(
+ 'data' => array(
+ 'type' => 'post',
+ 'title' => 'With a parent',
+ 'parent' => 1,
+ ),
+ ),
+ 'post' => null,
+ 'user' => 'administrator',
+ 'status' => 400,
+ 'code' => 'content_invalid_attribute',
+ 'params' => array( 'data[parent]' => 'The parent attribute is only supported for hierarchical post types.' ),
+ ),
+ 'delete with a non-boolean permanent' => array(
+ 'ability' => 'core/content-delete',
+ 'method' => 'DELETE',
+ 'input' => array( 'permanent' => 'yes' ),
+ 'post' => 'published',
+ 'user' => 'administrator',
+ 'status' => 400,
+ 'code' => 'ability_invalid_input',
+ ),
+ 'trashing a trashed post' => array(
+ 'ability' => 'core/content-delete',
+ 'method' => 'DELETE',
+ 'input' => array(),
+ 'post' => 'trashed',
+ 'user' => 'administrator',
+ 'status' => 410,
+ 'code' => 'content_already_trashed',
+ ),
+ );
+ }
+
+ /**
+ * A failing write request receives the error with its status and writes nothing.
+ *
+ * Input that fails the schema is rejected, also a `permanent` value in the query string that
+ * is not a boolean. A request the permission callback refuses is refused before the ability
+ * runs, as unauthenticated for a logged-out user and as forbidden for a logged-in one, and
+ * the errors of the abilities reach the response with their status and `params`.
+ *
+ * @ticket 66706
+ * @dataProvider data_failing_write_requests
+ *
+ * @param string $ability The ability name.
+ * @param string $method The HTTP method.
+ * @param array $input The ability input, without `where`.
+ * @param string|null $post The post the request targets, or null for none.
+ * @param string $user The user: `administrator`, `subscriber` or `logged-out`.
+ * @param int $status The expected status.
+ * @param string $code The expected error code.
+ * @param array|null $params The expected error params, or null to skip that check.
+ */
+ public function test_failing_write_request_returns_the_error_and_writes_nothing( string $ability, string $method, array $input, ?string $post, string $user, int $status, string $code, ?array $params = null ): void {
+ $post_id = null;
+ if ( 'missing' === $post ) {
+ $post_id = REST_TESTS_IMPOSSIBLY_HIGH_NUMBER;
+ } elseif ( null !== $post ) {
+ $post_id = self::factory()->post->create(
+ array(
+ 'post_author' => self::$admin_id,
+ 'post_status' => 'publish',
+ )
+ );
+ if ( 'trashed' === $post ) {
+ wp_trash_post( $post_id );
+ }
+ }
+
+ if ( null !== $post ) {
+ // A query string carries the ID as a string.
+ $input = array_merge(
+ array(
+ 'where' => array(
+ 'type' => 'post',
+ 'id' => 'POST' === $method ? $post_id : (string) $post_id,
+ ),
+ ),
+ $input
+ );
+ }
+
+ $user_ids = array(
+ 'administrator' => self::$admin_id,
+ 'subscriber' => self::$subscriber_id,
+ 'logged-out' => 0,
+ );
+ wp_set_current_user( $user_ids[ $user ] );
+
+ $context = $this->dataName();
+ $before = WP_Abilities_Content_Write_UnitTestCase::snapshot( $post_id );
+ $response = $this->server->dispatch( $this->write_request( $method, $ability, $input ) );
+
+ $this->assert_error_response( $response, $status, $code, $context );
+ if ( null !== $params ) {
+ $this->assertSame( $params, $response->get_data()['data']['params'] ?? null, "{$context}: the params should reach the response." );
+ }
+ $this->assertSame( $before, WP_Abilities_Content_Write_UnitTestCase::snapshot( $post_id ), "{$context}: nothing should be written." );
+ }
}
diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesTermsController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesTermsController.php
new file mode 100644
index 0000000000000..e302cd8afc0c1
--- /dev/null
+++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesTermsController.php
@@ -0,0 +1,457 @@
+server = $wp_rest_server;
+ do_action( 'rest_api_init' );
+
+ $this->register_abilities();
+ }
+
+ /**
+ * Removes the server.
+ *
+ * @since 7.3.0
+ */
+ public function tear_down(): void {
+ global $wp_rest_server;
+ $wp_rest_server = null;
+
+ parent::tear_down();
+ }
+
+ /**
+ * Builds a run request for a term 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 run_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;
+ }
+
+ /**
+ * Dispatches a request that must be rejected, and asserts its status and code and that
+ * nothing stored changed.
+ *
+ * @since 7.3.0
+ *
+ * @param WP_REST_Request $request The request.
+ * @param int $status The expected status.
+ * @param string $code The expected error code.
+ * @param string $context What the request was, for the assertion messages.
+ * @return array The response data.
+ */
+ private function dispatch_rejected( WP_REST_Request $request, int $status, string $code, string $context ): array {
+ $before = $this->snapshot();
+ $response = $this->server->dispatch( $request );
+
+ $this->assertSame( $before, $this->snapshot(), "{$context}: nothing stored should change." );
+ $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}." );
+
+ return $response->get_data();
+ }
+
+ /**
+ * Query runs with GET and the input in the query string, where numbers are strings.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_query_runs_with_get_and_the_input_in_the_query_string(): void {
+ $this->login_as( 'subscriber' );
+
+ $response = $this->server->dispatch(
+ $this->run_request(
+ 'GET',
+ 'core/terms-query',
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'parent' => '0',
+ ),
+ 'fields' => array( 'name' ),
+ 'pagination' => array( 'per_page' => '2' ),
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The query request should succeed.' );
+ $this->assertSame(
+ array(
+ 'items' => array(
+ array(
+ 'id' => self::$term_ids['empty'],
+ 'name' => 'Empty',
+ ),
+ array(
+ 'id' => self::$term_ids['news'],
+ 'name' => 'News',
+ ),
+ ),
+ 'pagination' => array(
+ 'total' => 3,
+ 'total_pages' => 2,
+ ),
+ ),
+ $response->get_data(),
+ 'The first two top-level categories should be returned.'
+ );
+ }
+
+ /**
+ * A logged-out visitor cannot query.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_logged_out_query_returns_401(): void {
+ $this->login_as( 'logged_out' );
+
+ $this->dispatch_rejected( $this->run_request( 'GET', 'core/terms-query', array( 'where' => array( 'taxonomy' => 'category' ) ) ), 401, 'rest_ability_cannot_execute', 'Logged out' );
+ }
+
+ /**
+ * Create runs with POST and the input in a JSON body.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_create_runs_with_post_and_a_json_body(): void {
+ $this->login_as( 'editor' );
+
+ $response = $this->server->dispatch(
+ $this->run_request(
+ 'POST',
+ 'core/term-create',
+ array(
+ 'data' => array(
+ 'taxonomy' => 'category',
+ 'name' => 'Over the run route',
+ 'parent' => self::$term_ids['news'],
+ ),
+ 'fields' => array( 'name', 'parent' ),
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The create request should succeed.' );
+
+ $data = $response->get_data();
+
+ $this->assertSame( array( 'id', 'name', 'parent' ), array_keys( $data ), 'The created term should be returned in the chosen fields.' );
+ $this->assertSame( 'Over the run route', get_term( $data['id'], 'category' )->name, 'The created term should be stored.' );
+ $this->assertSame( self::$term_ids['news'], $data['parent'], 'The parent should be returned.' );
+ }
+
+ /**
+ * A subscriber cannot create a category over the run route.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_subscriber_create_returns_403(): void {
+ $this->login_as( 'subscriber' );
+
+ $input = array(
+ 'data' => array(
+ 'taxonomy' => 'category',
+ 'name' => 'Refused',
+ ),
+ );
+
+ $this->dispatch_rejected( $this->run_request( 'POST', 'core/term-create', $input ), 403, 'rest_ability_cannot_execute', 'Subscriber' );
+ }
+
+ /**
+ * Update runs with POST and the input in a JSON body.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_update_runs_with_post_and_a_json_body(): void {
+ $this->login_as( 'editor' );
+
+ $response = $this->server->dispatch(
+ $this->run_request(
+ 'POST',
+ 'core/term-update',
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'id' => self::$term_ids['beta'],
+ ),
+ 'data' => array( 'description' => 'Updated over the run route' ),
+ 'fields' => array( 'description' ),
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The update request should succeed.' );
+ $this->assertSame(
+ array(
+ 'id' => self::$term_ids['beta'],
+ 'description' => 'Updated over the run route',
+ ),
+ $response->get_data(),
+ 'The updated term should be returned in the chosen fields.'
+ );
+ }
+
+ /**
+ * A user who may not edit the term cannot update it over the run route.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_update_by_a_user_who_may_not_edit_the_term_returns_403(): void {
+ $this->login_as( 'author' );
+
+ $input = array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'id' => self::$term_ids['news'],
+ ),
+ 'data' => array( 'description' => 'Refused' ),
+ );
+
+ $this->dispatch_rejected( $this->run_request( 'POST', 'core/term-update', $input ), 403, 'rest_ability_cannot_execute', 'Author' );
+ }
+
+ /**
+ * Delete runs with DELETE and the input in the query string, where the ID is a string.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_delete_runs_with_delete_and_the_input_in_the_query_string(): void {
+ $this->login_as( 'editor' );
+
+ $response = $this->server->dispatch(
+ $this->run_request(
+ 'DELETE',
+ 'core/term-delete',
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'id' => (string) self::$term_ids['beta'],
+ ),
+ 'permanent' => 'true',
+ )
+ )
+ );
+
+ $this->assertSame( 200, $response->get_status(), 'The delete request should succeed.' );
+ $this->assertSame( array( 'outcome' => 'deleted' ), $response->get_data(), 'The outcome should be deleted.' );
+ $this->assertNull( get_term( self::$term_ids['beta'] ), 'The tag should be gone.' );
+ }
+
+ /**
+ * Returns errors of the abilities with the response they give.
+ *
+ * @since 7.3.0
+ *
+ * @return array, status: int, code: string, data: array}> The cases.
+ */
+ public static function data_ability_errors(): array {
+ $flat = 'The "post_tag" taxonomy is not hierarchical.';
+
+ return array(
+ 'parent filter on tags' => array(
+ 'GET',
+ 'core/terms-query',
+ array(
+ 'where' => array(
+ 'taxonomy' => 'post_tag',
+ 'parent' => 0,
+ ),
+ ),
+ 400,
+ 'terms_invalid_filter',
+ array( 'params' => array( 'where[parent]' => $flat ) ),
+ ),
+ 'update of a missing term' => array(
+ 'POST',
+ 'core/term-update',
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'id' => self::MISSING_ID,
+ ),
+ 'data' => array( 'name' => 'Nobody' ),
+ ),
+ 404,
+ 'term_not_found',
+ array(),
+ ),
+ 'create of an existing tag' => array(
+ 'POST',
+ 'core/term-create',
+ array(
+ 'data' => array(
+ 'taxonomy' => 'post_tag',
+ 'name' => 'alpha',
+ ),
+ ),
+ 400,
+ 'term_exists',
+ array( 'term_id' => 'alpha' ),
+ ),
+ 'delete of the default' => array(
+ 'DELETE',
+ 'core/term-delete',
+ array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'id' => 'uncategorized',
+ ),
+ 'permanent' => true,
+ ),
+ 400,
+ 'term_is_default',
+ array(),
+ ),
+ );
+ }
+
+ /**
+ * Errors of the abilities reach the response with their status and data.
+ *
+ * @ticket 66743
+ * @dataProvider data_ability_errors
+ * @since 7.3.0
+ *
+ * @param string $method The HTTP method.
+ * @param string $ability The ability name.
+ * @param array $input The input, with fixture names for term IDs.
+ * @param int $status The expected status.
+ * @param string $code The expected error code.
+ * @param array $data The expected error data next to the status.
+ */
+ public function test_ability_errors_reach_the_response( string $method, string $ability, array $input, int $status, string $code, array $data ): void {
+ if ( isset( $input['where']['id'] ) && is_string( $input['where']['id'] ) ) {
+ $input['where']['id'] = self::$term_ids[ $input['where']['id'] ];
+ }
+ if ( isset( $data['term_id'] ) ) {
+ $data['term_id'] = self::$term_ids[ $data['term_id'] ];
+ }
+
+ $this->login_as( 'editor' );
+
+ $response = $this->dispatch_rejected( $this->run_request( $method, $ability, $input ), $status, $code, $code );
+
+ $this->assertSameSetsWithIndex( array( 'status' => $status ) + $data, $response['data'] ?? null, 'The error data should reach the response.' );
+ }
+
+ /**
+ * Returns requests with a method the ability does not take.
+ *
+ * @since 7.3.0
+ *
+ * @return array The cases.
+ */
+ public static function data_wrong_methods(): array {
+ return array(
+ 'query with POST' => array( 'POST', 'core/terms-query' ),
+ 'create with GET' => array( 'GET', 'core/term-create' ),
+ 'create with DELETE' => array( 'DELETE', 'core/term-create' ),
+ 'update with GET' => array( 'GET', 'core/term-update' ),
+ 'update with DELETE' => array( 'DELETE', 'core/term-update' ),
+ 'delete with GET' => array( 'GET', 'core/term-delete' ),
+ 'delete with POST' => array( 'POST', 'core/term-delete' ),
+ );
+ }
+
+ /**
+ * A request with a method the ability does not take is refused and stores nothing.
+ *
+ * @ticket 66743
+ * @dataProvider data_wrong_methods
+ * @since 7.3.0
+ *
+ * @param string $method The HTTP method.
+ * @param string $ability The ability name.
+ */
+ public function test_wrong_method_returns_405( string $method, string $ability ): void {
+ $this->login_as( 'administrator' );
+
+ $input = array(
+ 'where' => array(
+ 'taxonomy' => 'category',
+ 'id' => self::$term_ids['empty'],
+ ),
+ 'data' => array(
+ 'taxonomy' => 'category',
+ 'name' => 'Wrong method',
+ ),
+ );
+
+ $this->dispatch_rejected( $this->run_request( $method, $ability, $input ), 405, 'rest_ability_invalid_method', "{$method} {$ability}" );
+ }
+
+ /**
+ * Input that fails the schema is refused and stores nothing.
+ *
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_create_with_input_that_fails_the_schema_returns_400(): void {
+ $this->login_as( 'administrator' );
+
+ $input = array(
+ 'data' => array(
+ 'taxonomy' => 'category',
+ 'name' => '',
+ ),
+ );
+
+ $this->dispatch_rejected( $this->run_request( 'POST', 'core/term-create', $input ), 400, 'ability_invalid_input', 'Empty name' );
+ }
+}
diff --git a/tests/phpunit/tests/taxonomy.php b/tests/phpunit/tests/taxonomy.php
index 3162252598c53..7db8d0e704f7c 100644
--- a/tests/phpunit/tests/taxonomy.php
+++ b/tests/phpunit/tests/taxonomy.php
@@ -275,6 +275,66 @@ public function test_register_taxonomy_show_in_quick_edit_should_default_to_valu
$this->assertFalse( $tax_2->show_in_quick_edit );
}
+ /**
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_register_taxonomy_show_in_abilities_defaults_to_false() {
+ register_taxonomy( 'wptests_tax', 'post', array( 'public' => true ) );
+
+ $this->assertFalse( get_taxonomy( 'wptests_tax' )->show_in_abilities );
+ }
+
+ /**
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_register_taxonomy_show_in_abilities_true() {
+ register_taxonomy( 'wptests_tax', 'post', array( 'show_in_abilities' => true ) );
+
+ $this->assertTrue( get_taxonomy( 'wptests_tax' )->show_in_abilities );
+ }
+
+ /**
+ * @ticket 66743
+ * @since 7.3.0
+ *
+ * @dataProvider data_register_taxonomy_show_in_abilities_values_other_than_true
+ *
+ * @param mixed $value The value passed as `show_in_abilities`.
+ */
+ public function test_register_taxonomy_show_in_abilities_is_false_for_values_other_than_true( $value ) {
+ register_taxonomy( 'wptests_tax', 'post', array( 'show_in_abilities' => $value ) );
+
+ $this->assertFalse( get_taxonomy( 'wptests_tax' )->show_in_abilities );
+ }
+
+ /**
+ * Data provider.
+ *
+ * @since 7.3.0
+ *
+ * @return array[]
+ */
+ public static function data_register_taxonomy_show_in_abilities_values_other_than_true() {
+ return array(
+ 'false' => array( false ),
+ 'array' => array( array( 'create' ) ),
+ 'string false' => array( 'false' ),
+ 'string true' => array( 'true' ),
+ 'integer 1' => array( 1 ),
+ );
+ }
+
+ /**
+ * @ticket 66743
+ * @since 7.3.0
+ */
+ public function test_category_and_post_tag_show_in_abilities() {
+ $this->assertTrue( get_taxonomy( 'category' )->show_in_abilities, 'Categories should be exposed to abilities.' );
+ $this->assertTrue( get_taxonomy( 'post_tag' )->show_in_abilities, 'Tags should be exposed to abilities.' );
+ }
+
/**
* @ticket 53212
*/