From a372a8772f8732308864da997e1b1dc95dd5b1b6 Mon Sep 17 00:00:00 2001 From: Faisal Ahammad Date: Mon, 23 Nov 2026 20:58:50 +0600 Subject: [PATCH] Abilities API: Let plugins add fields and query filters to content abilities. Adds `wp_register_ability_post_field()` and `wp_register_ability_post_query_filter()`, registered on the new `wp_abilities_api_extensions_init` action, which fires before abilities are registered. `core/content-query` adds registered fields to its output under `extensions..`, and accepts registered filters under `where.extensions..`. The schemas stay closed, so unregistered keys still fail validation, and they do not change when nothing is registered. A query filter returns only `meta_query`, `tax_query`, `post__in` or `post__not_in`. These are joined with AND with the core filters and the other query filters before the query runs, so the totals match the results. A filter that does not apply to the queried post type is refused. See #66550. --- src/wp-includes/abilities-api.php | 193 +++++ .../class-wp-abilities-registry.php | 11 + .../abilities/class-wp-abilities-content.php | 191 ++++- .../wpRegisterAbilityPostExtensions.php | 741 ++++++++++++++++++ 4 files changed, 1132 insertions(+), 4 deletions(-) create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterAbilityPostExtensions.php diff --git a/src/wp-includes/abilities-api.php b/src/wp-includes/abilities-api.php index 50f4b6ac05610..f68edea26c545 100644 --- a/src/wp-includes/abilities-api.php +++ b/src/wp-includes/abilities-api.php @@ -895,3 +895,196 @@ function wp_get_ability_categories(): array { return $registry->get_all_registered(); } + +/** + * Registers a field that content abilities add to the posts they return. + * + * The field is returned under `extensions..` for each post, and the + * `fields` input of the abilities accepts its path, such as `extensions.my-plugin.language`. + * It is not a default field, so a caller must request it, directly or through the + * `extensions` or `extensions.` path. Abilities that return posts, such as + * `core/content-query`, read the registered fields when they are registered, so post + * fields must be registered on the `wp_abilities_api_extensions_init` action hook. + * + * Example: + * + * function my_plugin_register_post_fields(): void { + * wp_register_ability_post_field( + * 'my-plugin', + * 'language', + * array( + * 'schema' => array( + * 'type' => array( 'string', 'null' ), + * 'description' => __( 'The language slug of the post, such as "fi".', 'my-plugin' ), + * ), + * 'get_callback' => static function ( WP_Post $post ) { + * return my_plugin_get_post_language( $post->ID ); + * }, + * ) + * ); + * } + * add_action( 'wp_abilities_api_extensions_init', 'my_plugin_register_post_fields' ); + * + * @since 7.3.0 + * + * @param string $extension_namespace The namespace of the plugin that registers the field, + * such as `my-plugin`. Lowercase letters, digits, and dashes. + * @param string $name The field name. Lowercase letters, digits, dashes, and underscores. + * @param array $args { + * Arguments for the field. + * + * @type array $schema The JSON Schema of the field value, used in the + * output schema of the abilities. + * @type callable $get_callback Returns the field value for a post. Receives the + * WP_Post object, which is set up as the global post. + * Only called for posts the current user can read. + * @type string[] $object_types Optional. The post types the field applies to. The field + * is left out of posts of other post types. Default empty + * array, which applies to every post type. + * } + * @return bool True if the field was registered, false otherwise. + */ +function wp_register_ability_post_field( string $extension_namespace, string $name, array $args ): bool { + return _wp_register_ability_post_extension( 'fields', 'get_callback', __FUNCTION__, $extension_namespace, $name, $args ); +} + +/** + * Registers a query filter that content abilities accept for the posts they query. + * + * The filter is read from `where.extensions..` in the input of + * abilities that query posts, such as `core/content-query`. Its callback turns the + * value into a limited set of query arguments, which the ability joins with its own + * filters and with the other query filters, so a post must match all of them. The + * ability applies them to every query it runs, so the totals match the results. + * Query filters must be registered on the `wp_abilities_api_extensions_init` action hook. + * + * The callback receives the filter value, already validated against the schema, and the + * WP_Post_Type object of the queried post type. It returns an array with any of the + * following WP_Query arguments, or a WP_Error to refuse the query: + * + * - `meta_query` and `tax_query`: added as a nested clause, joined with AND. + * - `post__in`: intersected with the IDs the other filters allow. An empty list matches no post. + * - `post__not_in`: merged with the IDs the other filters exclude. + * + * Example: + * + * function my_plugin_register_post_query_filters(): void { + * wp_register_ability_post_query_filter( + * 'my-plugin', + * 'language', + * array( + * 'schema' => array( + * 'type' => 'string', + * 'minLength' => 1, + * 'description' => __( 'Only return posts in this language, such as "fi".', 'my-plugin' ), + * ), + * 'callback' => static function ( string $language ): array { + * return array( + * 'tax_query' => array( + * array( + * 'taxonomy' => 'language', + * 'field' => 'slug', + * 'terms' => $language, + * ), + * ), + * ); + * }, + * ) + * ); + * } + * add_action( 'wp_abilities_api_extensions_init', 'my_plugin_register_post_query_filters' ); + * + * @since 7.3.0 + * + * @param string $extension_namespace The namespace of the plugin that registers the filter, + * such as `my-plugin`. Lowercase letters, digits, and dashes. + * @param string $name The filter name. Lowercase letters, digits, dashes, and underscores. + * @param array $args { + * Arguments for the query filter. + * + * @type array $schema The JSON Schema of the filter value, used in the + * input schema of the abilities. + * @type callable $callback Returns the query arguments for a filter value, or a + * WP_Error to refuse the query. + * @type string[] $object_types Optional. The post types the filter applies to. A query + * of another post type that sets the filter is refused. + * Default empty array, which applies to every post type. + * } + * @return bool True if the query filter was registered, false otherwise. + */ +function wp_register_ability_post_query_filter( string $extension_namespace, string $name, array $args ): bool { + return _wp_register_ability_post_extension( 'query_filters', 'callback', __FUNCTION__, $extension_namespace, $name, $args ); +} + +/** + * Registers a post field or a post query filter for content abilities. + * + * @since 7.3.0 + * @access private + * + * @global array $wp_ability_post_extensions Registered post fields and query filters, keyed by + * kind, then namespace, then name. + * + * @param string $kind The kind of extension: `fields` or `query_filters`. + * @param string $callback_key The argument that holds the callback. + * @param string $function_name The public function that was called, for notices. + * @param string $extension_namespace The extension namespace. + * @param string $name The extension name. + * @param array $args The extension arguments. + * @return bool True if the extension was registered, false otherwise. + */ +function _wp_register_ability_post_extension( string $kind, string $callback_key, string $function_name, string $extension_namespace, string $name, array $args ): bool { + global $wp_ability_post_extensions; + + $error = ''; + if ( ! doing_action( 'wp_abilities_api_extensions_init' ) ) { + /* translators: %s: wp_abilities_api_extensions_init */ + $error = sprintf( __( 'Ability extensions must be registered on the %s action.' ), 'wp_abilities_api_extensions_init' ); + } elseif ( ! preg_match( '/^[a-z0-9-]+$/', $extension_namespace ) ) { + $error = __( 'The namespace must contain only lowercase letters, digits, and dashes.' ); + } elseif ( ! preg_match( '/^[a-z0-9_-]+$/', $name ) ) { + $error = __( 'The name must contain only lowercase letters, digits, dashes, and underscores.' ); + } elseif ( isset( $wp_ability_post_extensions[ $kind ][ $extension_namespace ][ $name ] ) ) { + $error = __( 'An extension with this namespace and name is already registered.' ); + } elseif ( empty( $args['schema'] ) || ! is_array( $args['schema'] ) ) { + /* translators: %s: schema */ + $error = sprintf( __( 'The %s argument must be a non-empty array.' ), 'schema' ); + } elseif ( ! isset( $args[ $callback_key ] ) || ! is_callable( $args[ $callback_key ] ) ) { + /* translators: %s: Argument name. */ + $error = sprintf( __( 'The %s argument must be a valid callback.' ), '' . $callback_key . '' ); + } elseif ( isset( $args['object_types'] ) && ( ! is_array( $args['object_types'] ) || array_filter( $args['object_types'], 'is_string' ) !== $args['object_types'] ) ) { + /* translators: %s: object_types */ + $error = sprintf( __( 'The %s argument must be an array of post type names.' ), 'object_types' ); + } + + if ( '' !== $error ) { + _doing_it_wrong( $function_name, $error, '7.3.0' ); + return false; + } + + $wp_ability_post_extensions[ $kind ][ $extension_namespace ][ $name ] = array( + 'schema' => $args['schema'], + 'callback' => $args[ $callback_key ], + 'object_types' => array_values( $args['object_types'] ?? array() ), + ); + + return true; +} + +/** + * Returns the registered post fields or post query filters for content abilities. + * + * @since 7.3.0 + * @access private + * + * @global array $wp_ability_post_extensions Registered post fields and query filters. + * + * @param string $kind The kind of extension: `fields` or `query_filters`. + * @return array, callback: callable, object_types: list}>> + * The extensions, keyed by namespace, then name. + */ +function _wp_get_ability_post_extensions( string $kind ): array { + global $wp_ability_post_extensions; + + return $wp_ability_post_extensions[ $kind ] ?? array(); +} diff --git a/src/wp-includes/abilities-api/class-wp-abilities-registry.php b/src/wp-includes/abilities-api/class-wp-abilities-registry.php index dc0b30835d9d1..152d6bf095959 100644 --- a/src/wp-includes/abilities-api/class-wp-abilities-registry.php +++ b/src/wp-includes/abilities-api/class-wp-abilities-registry.php @@ -320,6 +320,17 @@ public static function get_instance(): ?self { // before abilities that depend on them. WP_Ability_Categories_Registry::get_instance(); + /** + * Fires before abilities are registered, so that extensions to them can be registered. + * + * Post fields and post query filters must be registered on this action with + * wp_register_ability_post_field() and wp_register_ability_post_query_filter(), since + * the abilities that return posts read them when they are registered. + * + * @since 7.3.0 + */ + do_action( 'wp_abilities_api_extensions_init' ); + /** * Fires when preparing abilities registry. * diff --git a/src/wp-includes/abilities/class-wp-abilities-content.php b/src/wp-includes/abilities/class-wp-abilities-content.php index a8d9954e30965..9ceae14b043c0 100644 --- a/src/wp-includes/abilities/class-wp-abilities-content.php +++ b/src/wp-includes/abilities/class-wp-abilities-content.php @@ -68,12 +68,13 @@ final class WP_Abilities_Content { * Requests that include any of these, directly or through their whole object, prime * the post meta and term caches for the page. Rendered excerpts and content may read * either, and permalinks read terms when the permalink structure contains `%category%`. + * Fields that plugins add under `extensions` often read meta or terms too. * Other fields, such as the rendered title, do not need that cache priming. * * @since 7.2.0 * @var list */ - private const CACHE_PRIMING_FIELDS = array( 'link', 'excerpt.rendered', 'content.rendered' ); + private const CACHE_PRIMING_FIELDS = array( 'link', 'excerpt.rendered', 'content.rendered', 'extensions' ); /** * Default field paths returned when the caller does not request a field subset. @@ -638,6 +639,15 @@ private function execute_content_query( $input = array() ) { return $this->prepare_output( array(), 0, 0 ); } + /* + * Query filters change the arguments before the query runs, so the count query of + * get_query_total(), which starts from the same arguments, applies them too. + */ + $query_args = $this->apply_extension_query_filters( $query_args, $where, $post_type_object ); + if ( is_wp_error( $query_args ) ) { + return $query_args; + } + $query = new WP_Query( $query_args ); $total = $this->get_query_total( $query, $query_args, $page ); @@ -775,6 +785,102 @@ private function get_query_total( WP_Query $query, array $query_args, int $page return (int) $count_query->found_posts; } + /** + * Applies the query filters that plugins registered to the query arguments. + * + * Each filter given in `where.extensions` returns a limited set of query arguments, + * which are joined with the arguments of the other filters, so a post must match all + * of them, and no filter can undo another. A filter that is not registered, or does not + * apply to the post type, is refused rather than ignored, as other unsupported filters + * are: ignoring it would widen the query. + * + * @since 7.3.0 + * + * @param array $query_args The query arguments. + * @param array $where The `where` input. + * @param WP_Post_Type $post_type_object The queried post type. + * @return array|WP_Error The query arguments, or a WP_Error when a filter + * cannot be applied or refuses the query. + */ + private function apply_extension_query_filters( array $query_args, array $where, WP_Post_Type $post_type_object ) { + if ( ! array_key_exists( 'extensions', $where ) ) { + return $query_args; + } + + $input = $this->get_input_object( $where, 'extensions' ); + if ( null === $input ) { + return $this->invalid_filter_error( 'where[extensions]', __( 'The extensions filter must be an object.' ) ); + } + + $query_filters = _wp_get_ability_post_extensions( 'query_filters' ); + foreach ( $input as $namespace => $values ) { + $values = $this->get_input_object( $input, (string) $namespace ); + if ( null === $values ) { + return $this->invalid_filter_error( "where[extensions][{$namespace}]", __( 'The filters of a namespace must be an object.' ) ); + } + + foreach ( $values as $name => $value ) { + $param = "where[extensions][{$namespace}][{$name}]"; + $query_filter = $query_filters[ $namespace ][ $name ] ?? null; + if ( null === $query_filter ) { + return $this->invalid_filter_error( $param, __( 'The filter is not registered.' ) ); + } + + if ( ! empty( $query_filter['object_types'] ) && ! in_array( $post_type_object->name, $query_filter['object_types'], true ) ) { + return $this->invalid_filter_error( $param, __( 'The filter is not supported for this post type.' ) ); + } + + $clauses = call_user_func( $query_filter['callback'], $value, $post_type_object ); + if ( is_wp_error( $clauses ) ) { + return $clauses; + } + + $allowed = array( 'meta_query', 'tax_query', 'post__in', 'post__not_in' ); + if ( ! is_array( $clauses ) || array_diff_key( $clauses, array_flip( $allowed ) ) ) { + return new WP_Error( + 'ability_invalid_query_filter', + /* translators: %s: Parameter. */ + sprintf( __( 'The %s filter returned invalid query arguments.' ), $param ), + array( 'status' => 500 ) + ); + } + + foreach ( array( 'meta_query', 'tax_query' ) as $key ) { + if ( ! empty( $clauses[ $key ] ) ) { + // Nested as one clause, so its own relation cannot change how the other clauses join. + $query_args[ $key ][] = $clauses[ $key ]; + } + } + + if ( isset( $clauses['post__in'] ) ) { + $ids = array_map( 'absint', (array) $clauses['post__in'] ); + + $query_args['post__in'] = isset( $query_args['post__in'] ) ? array_intersect( $query_args['post__in'], $ids ) : $ids; + $query_args['post__in'] = array_values( array_filter( $query_args['post__in'] ) ); + + // WP_Query ignores an empty `post__in`, which would return every post. + if ( empty( $query_args['post__in'] ) ) { + $query_args['post__in'] = array( 0 ); + } + } + + if ( ! empty( $clauses['post__not_in'] ) ) { + $query_args['post__not_in'] = array_values( array_unique( array_merge( $query_args['post__not_in'] ?? array(), array_map( 'absint', (array) $clauses['post__not_in'] ) ) ) ); + } + } + } + + // WP_Query ignores `post__not_in` when `post__in` is set, so apply the exclusions to the inclusions. + if ( ! empty( $query_args['post__in'] ) && ! empty( $query_args['post__not_in'] ) ) { + $query_args['post__in'] = array_values( array_diff( $query_args['post__in'], $query_args['post__not_in'] ) ); + if ( empty( $query_args['post__in'] ) ) { + $query_args['post__in'] = array( 0 ); + } + } + + return $query_args; + } + /** * Checks whether requested fields benefit from page-level cache priming. * @@ -971,7 +1077,7 @@ private function normalize_fields( array $input ): array { * @return array Post field definitions. */ private function get_post_properties(): array { - return array( + $properties = array( 'id' => array( 'type' => 'integer', 'description' => __( 'The post ID.' ), @@ -1104,6 +1210,16 @@ private function get_post_properties(): array { 'description' => __( 'The parent post ID. Present for hierarchical post types.' ), ), ); + + $extensions = $this->get_extensions_schema( + _wp_get_ability_post_extensions( 'fields' ), + __( 'The fields that plugins add to the post, keyed by plugin namespace, then field name. Present when a requested extension field applies to the post type.' ) + ); + if ( null !== $extensions ) { + $properties['extensions'] = $extensions; + } + + return $properties; } /** @@ -1123,8 +1239,15 @@ private function get_field_paths(): array { foreach ( $this->get_post_properties() as $name => $schema ) { $paths[] = $name; - foreach ( array_keys( $schema['properties'] ?? array() ) as $sub_field ) { + foreach ( $schema['properties'] ?? array() as $sub_field => $sub_schema ) { $paths[] = "{$name}.{$sub_field}"; + + // Extension fields are nested one level deeper, under their namespace. + if ( 'extensions' === $name ) { + foreach ( array_keys( $sub_schema['properties'] ) as $extension_field ) { + $paths[] = "{$name}.{$sub_field}.{$extension_field}"; + } + } } } @@ -1171,7 +1294,7 @@ private function get_fields_input_schema(): array { * @return array The input JSON Schema. */ private function get_content_query_input_schema( array $post_types, array $statuses ): array { - return array( + $schema = array( 'type' => 'object', 'additionalProperties' => false, 'required' => array( 'where' ), @@ -1270,6 +1393,51 @@ private function get_content_query_input_schema( array $post_types, array $statu ), ), ); + + $extensions = $this->get_extensions_schema( + _wp_get_ability_post_extensions( 'query_filters' ), + __( 'The filters that plugins add, keyed by plugin namespace, then filter name. A post must match every given filter. A filter is refused for post types it does not apply to.' ) + ); + if ( null !== $extensions ) { + $schema['properties']['where']['properties']['extensions'] = $extensions; + } + + return $schema; + } + + /** + * Builds the schema of the `extensions` object of post fields or query filters. + * + * Each namespace is an object that holds its fields or filters, and every object sets + * `additionalProperties: false`, so an unregistered extension fails validation. + * + * @since 7.3.0 + * + * @param array>> $extensions The registered extensions, + * keyed by namespace, then name. + * @param string $description The description of the object. + * @return array|null The `extensions` JSON Schema, or null when none is registered. + */ + private function get_extensions_schema( array $extensions, string $description ): ?array { + if ( empty( $extensions ) ) { + return null; + } + + $properties = array(); + foreach ( $extensions as $namespace => $items ) { + $properties[ $namespace ] = array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => wp_list_pluck( $items, 'schema' ), + ); + } + + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => $properties, + 'description' => $description, + ); } /** @@ -1537,6 +1705,21 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit $data['parent'] = (int) $post->post_parent; } + $extensions = array(); + foreach ( _wp_get_ability_post_extensions( 'fields' ) as $namespace => $extension_fields ) { + foreach ( $extension_fields as $name => $extension_field ) { + if ( ! empty( $extension_field['object_types'] ) && ! in_array( $post_type, $extension_field['object_types'], true ) ) { + continue; + } + if ( $this->is_field_requested( "extensions.{$namespace}.{$name}", $fields ) ) { + $extensions[ $namespace ][ $name ] = call_user_func( $extension_field['callback'], $post ); + } + } + } + if ( ! empty( $extensions ) ) { + $data['extensions'] = $extensions; + } + return $data; } diff --git a/tests/phpunit/tests/abilities-api/wpRegisterAbilityPostExtensions.php b/tests/phpunit/tests/abilities-api/wpRegisterAbilityPostExtensions.php new file mode 100644 index 0000000000000..189659af8b02e --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterAbilityPostExtensions.php @@ -0,0 +1,741 @@ + + */ + private static $post_ids = array(); + + /** + * Shared administrator ID. + * + * @var int + */ + private static $admin_id = 0; + + /** + * Creates shared posts in two languages, and a page. + * + * @param WP_UnitTest_Factory $factory The unit test factory. + */ + public static function wpSetUpBeforeClass( $factory ): void { + self::$admin_id = $factory->user->create( array( 'role' => 'administrator' ) ); + + $languages = array( + 'en_1' => 'en', + 'en_2' => 'en', + 'en_3' => 'en', + 'fi_1' => 'fi', + 'fi_2' => 'fi', + ); + foreach ( $languages as $key => $language ) { + self::$post_ids[ $key ] = $factory->post->create( + array( + 'post_status' => 'publish', + 'meta_input' => array( self::LANGUAGE_KEY => $language ), + ) + ); + } + + self::$post_ids['page_en'] = $factory->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'publish', + 'meta_input' => array( self::LANGUAGE_KEY => 'en' ), + ) + ); + } + + /** + * Logs in, and sets up the content ability category. + */ + public function set_up(): void { + parent::set_up(); + + wp_set_current_user( self::$admin_id ); + + if ( wp_has_ability( 'core/content-query' ) ) { + wp_unregister_ability( 'core/content-query' ); + } + + if ( ! wp_has_ability_category( 'content' ) ) { + $this->in_action( + 'wp_abilities_api_categories_init', + static function (): void { + wp_register_ability_category( + 'content', + array( + 'label' => 'Content', + 'description' => 'Content.', + ) + ); + } + ); + } + } + + /** + * Removes the ability, its category, and the registered extensions. + */ + public function tear_down(): void { + if ( wp_has_ability( 'core/content-query' ) ) { + wp_unregister_ability( 'core/content-query' ); + } + + if ( wp_has_ability_category( 'content' ) ) { + wp_unregister_ability_category( 'content' ); + } + + unset( $GLOBALS['wp_ability_post_extensions'] ); + + parent::tear_down(); + } + + /** + * Runs a callback as if the given action were firing. + * + * @param string $action The action name. + * @param callable $callback The callback to run. + * @return mixed The callback result. + */ + private function in_action( string $action, callable $callback ) { + global $wp_current_filter; + $wp_current_filter[] = $action; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it. + + try { + return $callback(); + } finally { + array_pop( $wp_current_filter ); + } + } + + /** + * Registers the core/content-query ability. + */ + private function register_ability(): void { + $this->in_action( + 'wp_abilities_api_init', + static function (): void { + ( new WP_Abilities_Content() )->register(); + } + ); + } + + /** + * Registers a `test/language` field and query filter that read the language from post meta. + * + * @param list $object_types The post types the field and filter apply to. + */ + private function register_language_extensions( array $object_types = array() ): void { + $this->in_action( + 'wp_abilities_api_extensions_init', + static function () use ( $object_types ): void { + wp_register_ability_post_field( + 'test', + 'language', + array( + 'schema' => array( 'type' => array( 'string', 'null' ) ), + 'get_callback' => static function ( WP_Post $post ): ?string { + $language = get_post_meta( $post->ID, self::LANGUAGE_KEY, true ); + return '' !== $language ? $language : null; + }, + 'object_types' => $object_types, + ) + ); + wp_register_ability_post_query_filter( + 'test', + 'language', + array( + 'schema' => array( + 'type' => 'string', + 'minLength' => 1, + ), + 'callback' => static function ( string $language ): array { + return array( + 'meta_query' => array( + array( + 'key' => self::LANGUAGE_KEY, + 'value' => $language, + ), + ), + ); + }, + 'object_types' => $object_types, + ) + ); + } + ); + } + + /** + * Registers a `test/` query filter with the given callback. + * + * @param string $name The filter name. + * @param callable $callback The filter callback. + */ + private function register_query_filter( string $name, callable $callback ): void { + $this->in_action( + 'wp_abilities_api_extensions_init', + static function () use ( $name, $callback ): void { + wp_register_ability_post_query_filter( + 'test', + $name, + array( + 'schema' => array( 'type' => 'boolean' ), + 'callback' => $callback, + ) + ); + } + ); + } + + /** + * Runs core/content-query with the given input. + * + * @param array $input The ability input. + * @return mixed The ability result. + */ + private function query( array $input ) { + return wp_get_ability( 'core/content-query' )->execute( $input ); + } + + /** + * Without registered extensions, the schemas do not change. + * + * @ticket 66550 + */ + public function test_schemas_have_no_extensions_without_registrations(): void { + $this->register_ability(); + $ability = wp_get_ability( 'core/content-query' ); + + $this->assertArrayNotHasKey( 'extensions', $ability->get_input_schema()['properties']['where']['properties'], 'The where filter should not list extensions.' ); + $this->assertArrayNotHasKey( 'extensions', $ability->get_output_schema()['properties']['items']['items']['properties'], 'The post output should not list extensions.' ); + $this->assertNotContains( 'extensions', $ability->get_input_schema()['properties']['fields']['items']['enum'], 'The fields enum should not list extensions.' ); + } + + /** + * Registered extensions are added to the input and output schemas and to the field paths. + * + * @ticket 66550 + */ + public function test_schemas_list_registered_extensions(): void { + $this->register_language_extensions(); + $this->register_ability(); + $ability = wp_get_ability( 'core/content-query' ); + + $where = $ability->get_input_schema()['properties']['where']['properties']; + $this->assertSame( array( 'test' ), array_keys( $where['extensions']['properties'] ), 'The where filter should list the namespace.' ); + $this->assertFalse( $where['extensions']['additionalProperties'], 'The extensions filter should stay closed.' ); + $this->assertSame( 'string', $where['extensions']['properties']['test']['properties']['language']['type'], 'The filter schema should be used.' ); + + $post = $ability->get_output_schema()['properties']['items']['items']['properties']; + $this->assertSame( array( 'string', 'null' ), $post['extensions']['properties']['test']['properties']['language']['type'], 'The field schema should be used.' ); + + $enum = $ability->get_input_schema()['properties']['fields']['items']['enum']; + foreach ( array( 'extensions', 'extensions.test', 'extensions.test.language' ) as $path ) { + $this->assertContains( $path, $enum, "The fields enum should list {$path}." ); + } + } + + /** + * A requested extension field is returned, and is not returned by default. + * + * @ticket 66550 + * + * @dataProvider data_extension_field_paths + * + * @param string $path A field path that includes the extension field. + */ + public function test_returns_requested_extension_field( string $path ): void { + $this->register_language_extensions(); + $this->register_ability(); + + $where = array( + 'type' => 'post', + 'ids' => array( self::$post_ids['fi_1'] ), + ); + + $result = $this->query( + array( + 'where' => $where, + 'fields' => array( $path ), + ) + ); + $this->assertNotWPError( $result ); + $this->assertSame( array( 'test' => array( 'language' => 'fi' ) ), $result['items'][0]['extensions'], 'The field should be returned under its namespace.' ); + + $result = $this->query( array( 'where' => $where ) ); + $this->assertArrayNotHasKey( 'extensions', $result['items'][0], 'Extension fields should not be returned by default.' ); + } + + /** + * Data provider. + * + * @return array + */ + public static function data_extension_field_paths(): array { + return array( + 'the field' => array( 'extensions.test.language' ), + 'the namespace' => array( 'extensions.test' ), + 'all' => array( 'extensions' ), + ); + } + + /** + * An extension field is left out of posts of post types it does not apply to. + * + * @ticket 66550 + */ + public function test_extension_field_is_left_out_for_other_post_types(): void { + $this->register_language_extensions( array( 'post' ) ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'page', + 'ids' => array( self::$post_ids['page_en'] ), + ), + 'fields' => array( 'extensions' ), + ) + ); + + $this->assertNotWPError( $result ); + $this->assertSame( array( 'id' => self::$post_ids['page_en'] ), $result['items'][0], 'Only the ID should be returned.' ); + } + + /** + * A query filter limits the results and the totals, on every page. + * + * @ticket 66550 + */ + public function test_query_filter_limits_results_and_totals(): void { + $this->register_language_extensions(); + $this->register_ability(); + + $input = array( + 'where' => array( + 'type' => 'post', + 'extensions' => array( 'test' => array( 'language' => 'en' ) ), + ), + 'fields' => array( 'extensions.test.language' ), + 'pagination' => array( 'per_page' => 2 ), + ); + + $first = $this->query( $input ); + $this->assertNotWPError( $first ); + $this->assertSame( + array( + 'total' => 3, + 'total_pages' => 2, + ), + $first['pagination'], + 'The totals should only count posts in the language.' + ); + + $input['pagination']['page'] = 2; + + $second = $this->query( $input ); + $this->assertNotWPError( $second ); + $this->assertCount( 1, $second['items'], 'The last page should hold the remaining post.' ); + + $ids = array_merge( wp_list_pluck( $first['items'], 'id' ), wp_list_pluck( $second['items'], 'id' ) ); + $this->assertEqualSets( array( self::$post_ids['en_1'], self::$post_ids['en_2'], self::$post_ids['en_3'] ), $ids, 'Only the posts in the language should be returned.' ); + } + + /** + * Query filters join with the core filters and with each other, so a post must match all. + * + * @ticket 66550 + */ + public function test_query_filters_join_with_and(): void { + $this->register_language_extensions(); + $this->register_query_filter( + 'only_first', + static function (): array { + return array( 'post__in' => array( self::$post_ids['en_1'], self::$post_ids['fi_1'] ) ); + } + ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'ids' => array( self::$post_ids['en_1'], self::$post_ids['en_2'], self::$post_ids['fi_1'] ), + 'extensions' => array( + 'test' => array( + 'language' => 'en', + 'only_first' => true, + ), + ), + ), + ) + ); + + $this->assertNotWPError( $result ); + $this->assertSame( array( self::$post_ids['en_1'] ), wp_list_pluck( $result['items'], 'id' ), 'Only the post that matches every filter should be returned.' ); + $this->assertSame( 1, $result['pagination']['total'], 'The total should count only that post.' ); + } + + /** + * Exclusions from a query filter apply to the IDs that `where.ids` and other filters allow. + * + * @ticket 66550 + * + * @dataProvider data_exclusion_orders + * + * @param list $order The order the filters are given in. + */ + public function test_query_filter_exclusions_apply_to_inclusions( array $order ): void { + $this->register_query_filter( + 'exclude_first', + static function (): array { + return array( 'post__not_in' => array( self::$post_ids['en_1'] ) ); + } + ); + $this->register_query_filter( + 'include_two', + static function (): array { + return array( 'post__in' => array( self::$post_ids['en_1'], self::$post_ids['en_2'] ) ); + } + ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'ids' => array( self::$post_ids['en_1'], self::$post_ids['en_2'], self::$post_ids['en_3'] ), + 'extensions' => array( 'test' => array_fill_keys( $order, true ) ), + ), + ) + ); + + $this->assertNotWPError( $result ); + $this->assertSame( array( self::$post_ids['en_2'] ), wp_list_pluck( $result['items'], 'id' ), 'The excluded post should be left out.' ); + $this->assertSame( 1, $result['pagination']['total'], 'The total should not count the excluded post.' ); + } + + /** + * Data provider. + * + * @return array}> + */ + public static function data_exclusion_orders(): array { + return array( + 'exclusion first' => array( array( 'exclude_first', 'include_two' ) ), + 'inclusion first' => array( array( 'include_two', 'exclude_first' ) ), + ); + } + + /** + * A query filter receives its value converted to its schema type. + * + * @ticket 66550 + */ + public function test_query_filter_receives_value_of_its_schema_type(): void { + $received = null; + $this->in_action( + 'wp_abilities_api_extensions_init', + static function () use ( &$received ): void { + wp_register_ability_post_query_filter( + 'test', + 'languages', + array( + 'schema' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'callback' => static function ( array $languages ) use ( &$received ): array { + $received = $languages; + return array(); + }, + ) + ); + } + ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'extensions' => array( 'test' => array( 'languages' => 'en,fi' ) ), + ), + ) + ); + + $this->assertNotWPError( $result ); + $this->assertSame( array( 'en', 'fi' ), $received, 'A list given as a string should reach the callback as an array.' ); + } + + /** + * Exclusions that remove every allowed ID match no post. + * + * @ticket 66550 + */ + public function test_query_filter_exclusions_can_remove_every_id(): void { + $this->register_query_filter( + 'exclude_all', + static function (): array { + return array( 'post__not_in' => array( self::$post_ids['en_1'] ) ); + } + ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'ids' => array( self::$post_ids['en_1'] ), + 'extensions' => array( 'test' => array( 'exclude_all' => true ) ), + ), + ) + ); + + $this->assertNotWPError( $result ); + $this->assertSame( array(), $result['items'], 'No post should be returned.' ); + $this->assertSame( 0, $result['pagination']['total'], 'The total should be zero.' ); + } + + /** + * A query filter that allows no ID matches no post, rather than every post. + * + * @ticket 66550 + */ + public function test_query_filter_with_empty_post__in_matches_no_post(): void { + $this->register_query_filter( + 'none', + static function (): array { + return array( 'post__in' => array() ); + } + ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'extensions' => array( 'test' => array( 'none' => true ) ), + ), + ) + ); + + $this->assertNotWPError( $result ); + $this->assertSame( array(), $result['items'], 'No post should be returned.' ); + $this->assertSame( 0, $result['pagination']['total'], 'The total should be zero.' ); + } + + /** + * A query filter that a post type does not support is refused. + * + * @ticket 66550 + */ + public function test_refuses_query_filter_for_other_post_types(): void { + $this->register_language_extensions( array( 'post' ) ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'page', + 'extensions' => array( 'test' => array( 'language' => 'en' ) ), + ), + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'content_invalid_filter', $result->get_error_code() ); + } + + /** + * A query filter that is not registered fails input validation. + * + * @ticket 66550 + */ + public function test_unregistered_query_filter_fails_validation(): void { + $this->register_language_extensions(); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'extensions' => array( 'test' => array( 'missing' => 'en' ) ), + ), + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'ability_invalid_input', $result->get_error_code() ); + } + + /** + * A query filter can refuse the query with a WP_Error. + * + * @ticket 66550 + */ + public function test_query_filter_can_refuse_the_query(): void { + $this->register_query_filter( + 'refuse', + static function (): WP_Error { + return new WP_Error( 'test_refused', 'Refused.' ); + } + ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'extensions' => array( 'test' => array( 'refuse' => true ) ), + ), + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'test_refused', $result->get_error_code() ); + } + + /** + * A query filter that returns other query arguments fails the query. + * + * @ticket 66550 + */ + public function test_query_filter_cannot_return_other_query_args(): void { + $this->register_query_filter( + 'widen', + static function (): array { + return array( 'post_status' => 'any' ); + } + ); + $this->register_ability(); + + $result = $this->query( + array( + 'where' => array( + 'type' => 'post', + 'extensions' => array( 'test' => array( 'widen' => true ) ), + ), + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'ability_invalid_query_filter', $result->get_error_code() ); + } + + /** + * Extensions can only be registered on the `wp_abilities_api_extensions_init` action. + * + * @ticket 66550 + * + * @expectedIncorrectUsage wp_register_ability_post_field + */ + public function test_field_registration_requires_the_extensions_action(): void { + $result = wp_register_ability_post_field( + 'test', + 'language', + array( + 'schema' => array( 'type' => 'string' ), + 'get_callback' => '__return_empty_string', + ) + ); + + $this->assertFalse( $result ); + } + + /** + * Invalid registrations are rejected. + * + * @ticket 66550 + * + * @dataProvider data_invalid_registrations + * + * @expectedIncorrectUsage wp_register_ability_post_query_filter + * + * @param string $extension_namespace The namespace. + * @param string $name The filter name. + * @param array $args The filter arguments. + */ + public function test_rejects_invalid_registrations( string $extension_namespace, string $name, array $args ): void { + $result = $this->in_action( + 'wp_abilities_api_extensions_init', + static function () use ( $extension_namespace, $name, $args ): bool { + return wp_register_ability_post_query_filter( $extension_namespace, $name, $args ); + } + ); + + $this->assertFalse( $result ); + $this->assertSame( array(), _wp_get_ability_post_extensions( 'query_filters' ) ); + } + + /** + * Data provider. + * + * @return array}> + */ + public static function data_invalid_registrations(): array { + $valid = array( + 'schema' => array( 'type' => 'string' ), + 'callback' => '__return_empty_array', + ); + + return array( + 'namespace with a dot' => array( 'my.plugin', 'language', $valid ), + 'uppercase name' => array( 'test', 'Language', $valid ), + 'missing schema' => array( 'test', 'language', array( 'callback' => '__return_empty_array' ) ), + 'invalid callback' => array( 'test', 'language', array_merge( $valid, array( 'callback' => 'not_a_function' ) ) ), + 'invalid object types' => array( 'test', 'language', array_merge( $valid, array( 'object_types' => 'post' ) ) ), + 'non-string object types' => array( 'test', 'language', array_merge( $valid, array( 'object_types' => array( 1 ) ) ) ), + ); + } + + /** + * An extension cannot be registered twice. + * + * @ticket 66550 + * + * @expectedIncorrectUsage wp_register_ability_post_query_filter + */ + public function test_rejects_duplicate_registration(): void { + $this->register_language_extensions(); + + $result = $this->in_action( + 'wp_abilities_api_extensions_init', + static function (): bool { + return wp_register_ability_post_query_filter( + 'test', + 'language', + array( + 'schema' => array( 'type' => 'string' ), + 'callback' => '__return_empty_array', + ) + ); + } + ); + + $this->assertFalse( $result ); + } +}