From a53d52a677c2772913c0cea6a283282f2ab1cfc1 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 20 Nov 2026 14:48:48 +0000 Subject: [PATCH] Abilities API: Add the `core/terms-query`, `core/term-create`, `core/term-update` and `core/term-delete` abilities. Adds four abilities for the terms of the taxonomies that set the new `show_in_abilities` argument of `register_taxonomy()`, which is on for `category` and `post_tag`. `core/terms-query` returns a page of the terms of a taxonomy with the totals, filtered by IDs, slugs, parent, post or `hide_empty`. `core/term-create`, `core/term-update` and `core/term-delete` create, change and permanently delete a term. The create and update abilities return the term in the same form as the query. The abilities require a logged-in user, and each call checks the capabilities of the user for the taxonomy and the term. A default term cannot be deleted. See #66743. --- src/wp-includes/abilities.php | 5 + .../abilities/class-wp-abilities-terms.php | 1451 +++++++++++++ src/wp-includes/class-wp-taxonomy.php | 15 + src/wp-includes/taxonomy.php | 6 + .../abilities-api/testcase-terms-ability.php | 867 ++++++++ .../wpRegisterCoreTermCreateAbility.php | 1067 ++++++++++ .../wpRegisterCoreTermDeleteAbility.php | 656 ++++++ .../wpRegisterCoreTermUpdateAbility.php | 935 +++++++++ .../wpRegisterCoreTermsAbility.php | 1862 +++++++++++++++++ .../wpRestAbilitiesTermsController.php | 455 ++++ tests/phpunit/tests/taxonomy.php | 60 + 11 files changed, 7379 insertions(+) create mode 100644 src/wp-includes/abilities/class-wp-abilities-terms.php create mode 100644 tests/phpunit/tests/abilities-api/testcase-terms-ability.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreTermCreateAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreTermDeleteAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreTermUpdateAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreTermsAbility.php create mode 100644 tests/phpunit/tests/rest-api/wpRestAbilitiesTermsController.php diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index 835c19e04f949..a19c9bfbfd80e 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/terms-query`, `core/term-create`, `core/term-update`, and `core/term-delete` abilities. * * @global wpdb $wpdb WordPress database abstraction object. */ @@ -379,4 +381,7 @@ function wp_register_core_abilities(): void { // Register the content abilities (currently the read-only `core/content-query`). ( 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-terms.php b/src/wp-includes/abilities/class-wp-abilities-terms.php new file mode 100644 index 0000000000000..420a9acd7cb4b --- /dev/null +++ b/src/wp-includes/abilities/class-wp-abilities-terms.php @@ -0,0 +1,1451 @@ +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. 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; + } + + /** + * 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; + if ( + ! $post instanceof WP_Post + || ! is_object_in_taxonomy( $post->post_type, $taxonomy ) + || ( ! is_post_publicly_viewable( $post ) && ! current_user_can( 'read_post', $post->ID ) ) + ) { + 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'] ) ) { + if ( empty( $where['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'] = $where['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 is set + * afterwards, so on this path it is always the one requested. + */ + 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['number'] = $per_page; + $args['offset'] = ( $page - 1 ) * $per_page; + + $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. + * + * @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 ) + ); + } + + 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.' ), + ), + '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. 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 of a post type that uses 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. It is sanitized as a term name is when it is saved.' ), + ), + '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' ), + 'properties' => array( + 'where' => $this->get_where_term_schema( $taxonomies, __( 'Selects the term to delete, by its taxonomy and ID.' ) ), + ), + ); + } + + /** + * 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-taxonomy.php b/src/wp-includes/class-wp-taxonomy.php index f44ce34a11def..b9021f4150345 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/taxonomy.php b/src/wp-includes/taxonomy.php index 8a64e726d2fcd..4d02297516645 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-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/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..b46bb4ccbfd7e --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermDeleteAbility.php @@ -0,0 +1,656 @@ + 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, + ), + ); + } + + /** + * 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 only the term, 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' ), + 'properties' => array( + 'where' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'taxonomy', 'id' ), + 'properties' => array( + 'taxonomy' => $this->taxonomy_schema(), + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + ), + ), + ), + ); + + $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.' ); + } +} 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..c8daf5be4becd --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreTermsAbility.php @@ -0,0 +1,1862 @@ + 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 read 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, + '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->login_as( 'no_role' ); + $this->register_abilities(); + + $result = $this->run_rejected( $input, 'No role' ); + + $this->assert_error( $result, 'terms_invalid_filter', 400, 'Invalid post ID.', 'No role', array( 'params' => array( 'where[post]' => 'Invalid post ID.' ) ) ); + + $this->login_as( 'subscriber' ); + + $this->assertSame( array( self::$term_ids['alpha'] ), $this->item_ids( $this->run_ability( $input ), 'Subscriber' ), 'A user who can read 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 not exposed to abilities. + * + * @ticket 66743 + * @since 7.3.0 + */ + public function test_post_filter_accepts_a_post_type_that_is_not_exposed(): 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->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.' ); + } + + /** + * 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. + * + * @since 7.3.0 + * + * @return array, expected: list}> 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' ) ), + 'IDs and slugs together' => array( + array( + 'ids' => array( 'news', 'roadmap' ), + 'slugs' => array( 'news', 'empty' ), + ), + array( 'news' ), + ), + ); + } + + /** + * 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. + */ + public function test_filters_select_the_categories( array $where, array $expected ): void { + $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.' + ); + } + + /** + * 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.' ); + } + + /** + * A page that holds terms is returned even when it is beyond the counted pages, which + * happens when empty ancestors of used categories are listed but not counted. + * + * @ticket 66743 + * @since 7.3.0 + */ + public function test_page_that_holds_terms_beyond_the_counted_pages_is_returned(): 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' => 2, + 'total_pages' => 2, + ), + $result['pagination'], + 'The totals should count only the used categories.' + ); + + $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 ) ) ); + } + + /** + * 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/wpRestAbilitiesTermsController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesTermsController.php new file mode 100644 index 0000000000000..e7b0ed64fe105 --- /dev/null +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesTermsController.php @@ -0,0 +1,455 @@ +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'], + ), + ) + ) + ); + + $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', + ), + ), + 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 */