diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index 1386c0deb7741..5fa42fea2befb 100644 --- a/src/wp-includes/abilities.php +++ b/src/wp-includes/abilities.php @@ -9,6 +9,8 @@ declare( strict_types = 1 ); +require_once __DIR__ . '/abilities/class-wp-abilities-settings.php'; + /** * Registers the core ability categories. * @@ -45,6 +47,7 @@ function wp_register_core_ability_categories(): void { * Registers the default core abilities. * * @since 6.9.0 + * @since 7.2.0 Added the `core/settings-get` ability. * * @global wpdb $wpdb WordPress database abstraction object. */ @@ -360,4 +363,7 @@ function wp_register_core_abilities(): void { ), ) ); + + // Register the settings abilities (currently the read-only `core/settings-get`). + ( new WP_Abilities_Settings() )->register(); } diff --git a/src/wp-includes/abilities/class-wp-abilities-settings.php b/src/wp-includes/abilities/class-wp-abilities-settings.php new file mode 100644 index 0000000000000..f9afdcd195c9c --- /dev/null +++ b/src/wp-includes/abilities/class-wp-abilities-settings.php @@ -0,0 +1,340 @@ +execute()`, which validates the input and + * checks permissions before running them. + * + * @since 7.2.0 + * + * @access private + */ +final class WP_Abilities_Settings { + + /** + * The ability category used for settings abilities. + * + * @since 7.2.0 + * @var string + */ + private const CATEGORY = 'site'; + + /** + * Settings exposed through the Abilities API, computed once at registration. + * + * @since 7.2.0 + * @var array}> + */ + private $exposed_settings = array(); + + /** + * Registers all settings abilities. + * + * Must run on the `wp_abilities_api_init` hook. Registers nothing when no setting is + * exposed to abilities. + * + * @since 7.2.0 + */ + public function register(): void { + $this->exposed_settings = $this->get_exposed_settings(); + if ( empty( $this->exposed_settings ) ) { + return; + } + + $this->register_settings_get(); + } + + /** + * Registers the read-only `core/settings-get` ability. + * + * @since 7.2.0 + */ + private function register_settings_get(): void { + $groups = array_values( array_unique( array_filter( array_column( $this->exposed_settings, 'group' ) ) ) ); + + wp_register_ability( + 'core/settings-get', + array( + 'label' => __( 'Get Settings' ), + 'description' => __( 'Returns WordPress settings as a flat map of setting name to value. By default returns all settings exposed to abilities, or optionally a subset filtered by settings group, by setting name, or both. A setting whose value does not match its schema is left out. Requires an authenticated user who can manage options.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_settings_get_input_schema( $groups, array_map( 'strval', array_keys( $this->exposed_settings ) ) ), + 'output_schema' => $this->get_settings_get_output_schema(), + 'execute_callback' => function ( $input = array() ): array { + return $this->execute_settings_get( $input ); + }, + 'permission_callback' => function (): bool { + return $this->check_permission(); + }, + 'meta' => array( + 'annotations' => array( + 'readonly' => true, + 'destructive' => false, + 'idempotent' => true, + ), + 'public' => true, + ), + ) + ); + } + + /** + * Executes the `core/settings-get` ability. + * + * @since 7.2.0 + * + * @param mixed $input Optional. The ability input. Default empty array. + * @return array Map of exposed setting name to current value. + */ + private function execute_settings_get( $input = array() ): array { + $input = rest_sanitize_object( $input ); + $group = isset( $input['group'] ) && is_string( $input['group'] ) ? $input['group'] : ''; + $fields = rest_sanitize_array( $input['fields'] ?? array() ); + + $result = array(); + foreach ( $this->exposed_settings as $exposed_name => $setting ) { + if ( '' !== $group && $setting['group'] !== $group ) { + continue; + } + if ( ! empty( $fields ) && ! in_array( (string) $exposed_name, $fields, true ) ) { + continue; + } + + /* + * As the settings endpoint does, read a setting that was never saved as its registered + * default, or leave it out when it has none: get_option() would return false, which a + * boolean schema accepts as a value and an array schema reads as an empty list. + */ + $value = get_option( $setting['option'], $setting['default'] ); + if ( null === $value ) { + continue; + } + + // WordPress stores false as '', which the boolean schema rejects. + if ( '' === $value && 'boolean' === $setting['schema']['type'] ) { + $value = false; + } + + /* + * Leave out a value its schema rejects, before sanitizing (which could make it pass) or + * after (which could make it fail), instead of failing output validation for every setting. + */ + if ( is_wp_error( rest_validate_value_from_schema( $value, $setting['schema'] ) ) ) { + continue; + } + + $value = rest_sanitize_value_from_schema( $value, $setting['schema'] ); + if ( is_wp_error( rest_validate_value_from_schema( $value, $setting['schema'] ) ) ) { + continue; + } + + // Object (not array()) so an empty object value is serialized as {}, consistent with type:object. + $result[ $exposed_name ] = 'object' === $setting['schema']['type'] ? (object) $value : $value; + } + + return $result; + } + + /** + * Permission callback for the settings abilities. + * + * The settings abilities read site options, so they are gated on the `manage_options` + * capability regardless of the input. + * + * @since 7.2.0 + * + * @return bool True if the current user can manage options. + */ + private function check_permission(): bool { + return current_user_can( 'manage_options' ); + } + + /** + * Builds the input schema for the `core/settings-get` ability: optional filters by group and/or name. + * + * Both `group` and `fields` are optional; supplying both narrows the response to their + * intersection, and supplying neither returns every exposed setting. + * + * @since 7.2.0 + * + * @param list $groups Available settings groups. + * @param list $field_names Available exposed setting names. + * @return array The input JSON Schema. + */ + private function get_settings_get_input_schema( array $groups, array $field_names ): array { + return array( + 'type' => 'object', + 'default' => array(), + 'properties' => array( + 'group' => array( + 'type' => 'string', + 'enum' => $groups, + 'description' => __( 'Return only settings that belong to this settings group. If omitted, settings of every group are returned.' ), + ), + 'fields' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'items' => array( + 'type' => 'string', + 'enum' => $field_names, + ), + 'description' => __( 'Return only the settings with these names. If omitted or empty, all settings allowed by the group filter are returned. When both filters are given, only settings matching both are returned.' ), + ), + ), + 'additionalProperties' => false, + ); + } + + /** + * Builds the output schema for the `core/settings-get` ability. + * + * No setting is marked required because the `group` and `fields` inputs let the caller + * request any subset, and a setting whose value does not match its schema is left out. + * + * @since 7.2.0 + * + * @return array The output JSON Schema. + */ + private function get_settings_get_output_schema(): array { + return array( + 'type' => 'object', + 'description' => __( 'A map of setting name to its current value.' ), + 'properties' => wp_list_pluck( $this->exposed_settings, 'schema' ), + 'additionalProperties' => false, + ); + } + + /** + * Returns the settings exposed through the Abilities API. + * + * Reads {@see get_registered_settings()} and keeps only settings flagged with a truthy + * `show_in_abilities` argument, of a type the settings endpoint supports. Each entry is + * keyed by its exposed name and carries the underlying option name, the settings group, + * the registered default (null when there is none), and a JSON Schema describing the value. + * + * Two settings exposed under the same name trigger a notice, and the later one is exposed. + * + * @since 7.2.0 + * + * @return array}> Settings keyed by exposed name. + */ + private function get_exposed_settings(): array { + $settings = array(); + + foreach ( get_registered_settings() as $option_name => $args ) { + if ( empty( $args['show_in_abilities'] ) ) { + continue; + } + + $show = $this->get_exposure_args( $args ); + + $schema = $this->value_schema( $args, $show ); + if ( ! in_array( $schema['type'], array( 'number', 'integer', 'string', 'boolean', 'array', 'object' ), true ) ) { + continue; + } + + $option_name = (string) $option_name; + $exposed_name = empty( $show['name'] ) ? $option_name : (string) $show['name']; + + if ( isset( $settings[ $exposed_name ] ) ) { + _doing_it_wrong( + __METHOD__, + sprintf( + /* translators: 1: Option name, 2: Setting name exposed to abilities, 3: Option name. */ + __( 'The "%1$s" setting is exposed to abilities as "%2$s", a name already used by the "%3$s" setting, which is no longer exposed.' ), + esc_html( $option_name ), + esc_html( $exposed_name ), + esc_html( $settings[ $exposed_name ]['option'] ) + ), + '7.2.0' + ); + } + + $settings[ $exposed_name ] = array( + 'option' => $option_name, + 'group' => $args['group'] ?? '', + 'default' => $args['default'] ?? null, + 'schema' => $schema, + ); + } + + return $settings; + } + + /** + * Returns the name and schema overrides used to expose a setting to abilities. + * + * When `show_in_abilities` is `true`, the setting is exposed the same way as in the + * REST API: it uses the `name` and `schema` from `show_in_rest`. An array is used + * as is. + * + * @since 7.2.0 + * + * @param array $args The setting registration arguments. + * @return array The exposure arguments, with optional `name` and `schema` keys. + */ + private function get_exposure_args( array $args ): array { + if ( is_array( $args['show_in_abilities'] ) ) { + return $args['show_in_abilities']; + } + + return is_array( $args['show_in_rest'] ) ? $args['show_in_rest'] : array(); + } + + /** + * Builds the JSON Schema describing a single setting's value. + * + * As in the settings endpoint, objects in the schema reject properties they do not declare, + * unless the schema allows them. + * + * @since 7.2.0 + * + * @param array $args The setting registration arguments. + * @param array $show The exposure arguments, see get_exposure_args(). + * @return array The value JSON Schema. + */ + private function value_schema( array $args, $show ): array { + $schema = array( + 'type' => $args['type'], + ); + if ( ! empty( $args['label'] ) ) { + $schema['title'] = $args['label']; + } + if ( ! empty( $args['description'] ) ) { + $schema['description'] = $args['description']; + } + if ( isset( $show['schema'] ) && is_array( $show['schema'] ) ) { + /** @var array $show_schema */ + $show_schema = $show['schema']; + $schema = array_merge( $schema, $show_schema ); + } + + return rest_default_additional_properties_to_false( $schema ); + } +} diff --git a/src/wp-includes/default-filters.php b/src/wp-includes/default-filters.php index fe93208adfaf2..cdeaa169af0cd 100644 --- a/src/wp-includes/default-filters.php +++ b/src/wp-includes/default-filters.php @@ -556,6 +556,7 @@ // Abilities API. add_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); +add_action( 'wp_abilities_api_init', '_wp_register_initial_settings_for_abilities', 1 ); add_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); // Connectors API. diff --git a/src/wp-includes/option.php b/src/wp-includes/option.php index 49ecfb65977f4..874e674d63067 100644 --- a/src/wp-includes/option.php +++ b/src/wp-includes/option.php @@ -2738,24 +2738,26 @@ function set_site_transient( $transient, $value, $expiration = 0 ) { /** * Registers default settings available in WordPress. * - * The settings registered here are primarily useful for the REST API, so this - * does not encompass all settings available in WordPress. + * The settings registered here are primarily useful for the REST API and the + * Abilities API, so this does not encompass all settings available in WordPress. * * @since 4.7.0 * @since 6.0.1 The `show_on_front`, `page_on_front`, and `page_for_posts` options were added. * @since 7.2.0 The `wp_page_for_privacy_policy` option was registered, exposed as `page_for_privacy_policy`. + * @since 7.2.0 Added `show_in_abilities` support for the exposed settings. */ function register_initial_settings() { register_setting( 'general', 'blogname', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'name' => 'title', ), - 'type' => 'string', - 'label' => __( 'Title' ), - 'description' => __( 'Site title.' ), + 'show_in_abilities' => true, + 'type' => 'string', + 'label' => __( 'Title' ), + 'description' => __( 'Site title.' ), ) ); @@ -2763,12 +2765,13 @@ function register_initial_settings() { 'general', 'blogdescription', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'name' => 'description', ), - 'type' => 'string', - 'label' => __( 'Tagline' ), - 'description' => __( 'Site tagline.' ), + 'show_in_abilities' => true, + 'type' => 'string', + 'label' => __( 'Tagline' ), + 'description' => __( 'Site tagline.' ), ) ); @@ -2777,14 +2780,15 @@ function register_initial_settings() { 'general', 'siteurl', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'name' => 'url', 'schema' => array( 'format' => 'uri', ), ), - 'type' => 'string', - 'description' => __( 'Site URL.' ), + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'The URL where WordPress core files are served. May differ from the public site URL.' ), ) ); } @@ -2794,14 +2798,15 @@ function register_initial_settings() { 'general', 'admin_email', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'name' => 'email', 'schema' => array( 'format' => 'email', ), ), - 'type' => 'string', - 'description' => __( 'This address is used for admin purposes, like new user notification.' ), + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'This address is used for admin purposes, like new user notification.' ), ) ); } @@ -2810,11 +2815,12 @@ function register_initial_settings() { 'general', 'timezone_string', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'name' => 'timezone', ), - 'type' => 'string', - 'description' => __( 'A city in the same timezone as you.' ), + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'A city in the same timezone as you.' ), ) ); @@ -2822,9 +2828,10 @@ function register_initial_settings() { 'general', 'date_format', array( - 'show_in_rest' => true, - 'type' => 'string', - 'description' => __( 'A date format for all date strings.' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'A date format for all date strings.' ), ) ); @@ -2832,9 +2839,10 @@ function register_initial_settings() { 'general', 'time_format', array( - 'show_in_rest' => true, - 'type' => 'string', - 'description' => __( 'A time format for all time strings.' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'A time format for all time strings.' ), ) ); @@ -2842,9 +2850,10 @@ function register_initial_settings() { 'general', 'start_of_week', array( - 'show_in_rest' => true, - 'type' => 'integer', - 'description' => __( 'A day number of the week that the week should start on.' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'integer', + 'description' => __( 'A day number of the week that the week should start on.' ), ) ); @@ -2852,12 +2861,13 @@ function register_initial_settings() { 'general', 'WPLANG', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'name' => 'language', ), - 'type' => 'string', - 'description' => __( 'WordPress locale code.' ), - 'default' => 'en_US', + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'WordPress locale code.' ), + 'default' => 'en_US', ) ); @@ -2865,10 +2875,11 @@ function register_initial_settings() { 'writing', 'use_smilies', array( - 'show_in_rest' => true, - 'type' => 'boolean', - 'description' => __( 'Convert emoticons like :-) and :-P to graphics on display.' ), - 'default' => true, + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'boolean', + 'description' => __( 'Convert emoticons like :-) and :-P to graphics on display.' ), + 'default' => true, ) ); @@ -2876,9 +2887,10 @@ function register_initial_settings() { 'writing', 'default_category', array( - 'show_in_rest' => true, - 'type' => 'integer', - 'description' => __( 'Default post category.' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'integer', + 'description' => __( 'Default post category.' ), ) ); @@ -2886,9 +2898,10 @@ function register_initial_settings() { 'writing', 'default_post_format', array( - 'show_in_rest' => true, - 'type' => 'string', - 'description' => __( 'Default post format.' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'Default post format.' ), ) ); @@ -2896,11 +2909,12 @@ function register_initial_settings() { 'reading', 'posts_per_page', array( - 'show_in_rest' => true, - 'type' => 'integer', - 'label' => __( 'Maximum posts per page' ), - 'description' => __( 'Blog pages show at most.' ), - 'default' => 10, + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'integer', + 'label' => __( 'Maximum posts per page' ), + 'description' => __( 'Blog pages show at most.' ), + 'default' => 10, ) ); @@ -2908,10 +2922,11 @@ function register_initial_settings() { 'reading', 'show_on_front', array( - 'show_in_rest' => true, - 'type' => 'string', - 'label' => __( 'Show on front' ), - 'description' => __( 'What to show on the front page' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'string', + 'label' => __( 'Show on front' ), + 'description' => __( 'What to show on the front page' ), ) ); @@ -2919,10 +2934,11 @@ function register_initial_settings() { 'reading', 'page_on_front', array( - 'show_in_rest' => true, - 'type' => 'integer', - 'label' => __( 'Page on front' ), - 'description' => __( 'The ID of the page that should be displayed on the front page' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'integer', + 'label' => __( 'Page on front' ), + 'description' => __( 'The ID of the page that should be displayed on the front page' ), ) ); @@ -2930,9 +2946,10 @@ function register_initial_settings() { 'reading', 'page_for_posts', array( - 'show_in_rest' => true, - 'type' => 'integer', - 'description' => __( 'The ID of the page that should display the latest posts' ), + 'show_in_rest' => true, + 'show_in_abilities' => true, + 'type' => 'integer', + 'description' => __( 'The ID of the page that should display the latest posts' ), ) ); @@ -2940,11 +2957,12 @@ function register_initial_settings() { 'reading', 'wp_page_for_privacy_policy', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'name' => 'page_for_privacy_policy', ), - 'type' => 'integer', - 'description' => __( 'The ID of the page that should be displayed as the privacy policy page' ), + 'show_in_abilities' => true, + 'type' => 'integer', + 'description' => __( 'The ID of the page that should be displayed as the privacy policy page' ), ) ); @@ -2952,13 +2970,14 @@ function register_initial_settings() { 'discussion', 'default_ping_status', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'schema' => array( 'enum' => array( 'open', 'closed' ), ), ), - 'type' => 'string', - 'description' => __( 'Allow link notifications from other blogs (pingbacks and trackbacks) on new articles.' ), + 'show_in_abilities' => true, + 'type' => 'string', + 'description' => __( 'Allow link notifications from other blogs (pingbacks and trackbacks) on new articles.' ), ) ); @@ -2966,18 +2985,53 @@ function register_initial_settings() { 'discussion', 'default_comment_status', array( - 'show_in_rest' => array( + 'show_in_rest' => array( 'schema' => array( 'enum' => array( 'open', 'closed' ), ), ), - 'type' => 'string', - 'label' => __( 'Allow comments on new posts' ), - 'description' => __( 'Allow people to submit comments on new posts.' ), + 'show_in_abilities' => true, + 'type' => 'string', + 'label' => __( 'Allow comments on new posts' ), + 'description' => __( 'Allow people to submit comments on new posts.' ), ) ); } +/** + * Registers the default settings when the Abilities API initializes. + * + * The default settings are registered on `rest_api_init`, which fires lazily and + * independently of `wp_abilities_api_init`: on cron, WP-CLI, or any request where + * abilities are used before the REST server loads, it may not have fired, or may be + * mid-fire at a priority before register_initial_settings() runs. This makes sure the + * settings exist before the core abilities read them. Registering them again later on + * `rest_api_init` is harmless. + * + * @since 7.2.0 + * @access private + * + * @global array $new_allowed_options + */ +function _wp_register_initial_settings_for_abilities(): void { + global $new_allowed_options; + + if ( did_action( 'rest_api_init' ) && ! doing_action( 'rest_api_init' ) ) { + return; + } + + $allowed_options = $new_allowed_options; + + register_initial_settings(); + + /* + * Registering a setting also allows it on the options screen of its group. Restore + * the list, so saving Settings > General does not try to save `admin_email`, which + * that screen sends as `new_admin_email`. + */ + $new_allowed_options = $allowed_options; +} + /** * Registers a setting and its data. * @@ -2988,6 +3042,7 @@ function register_initial_settings() { * @since 5.5.0 `$new_whitelist_options` was renamed to `$new_allowed_options`. * Please consider writing more inclusive code. * @since 6.6.0 Added the `label` argument. + * @since 7.2.0 Added the `show_in_abilities` argument. * * @global array $new_allowed_options * @global array $wp_registered_settings @@ -3009,6 +3064,11 @@ function register_initial_settings() { * @type bool|array $show_in_rest Whether data associated with this setting should be included in the * REST API. When registering complex settings, this argument may * optionally be an array with a 'schema' key. + * @type bool|array $show_in_abilities Whether this setting should be exposed through the Abilities API. + * When true, it uses the same name and schema as `$show_in_rest`. + * It may also be an array with 'name' and 'schema' keys, used instead of + * `$show_in_rest` rather than merged with it. + * Settings registered after abilities initialize are not exposed. * @type mixed $default Default value when calling `get_option()`. * } */ @@ -3028,6 +3088,7 @@ function register_setting( $option_group, $option_name, $args = array() ) { 'description' => '', 'sanitize_callback' => null, 'show_in_rest' => false, + 'show_in_abilities' => false, ); // Back-compat: old sanitize callback is added. @@ -3211,6 +3272,7 @@ function unregister_setting( $option_group, $option_name, $deprecated = '' ) { * Retrieves an array of registered settings. * * @since 4.7.0 + * @since 7.2.0 Registered setting data includes the `show_in_abilities` argument. * * @global array $wp_registered_settings * @@ -3230,6 +3292,10 @@ function unregister_setting( $option_group, $option_name, $deprecated = '' ) { * @type bool|array $show_in_rest Whether data associated with this setting should be included in the * REST API. When registering complex settings, this argument may * optionally be an array with a 'schema' key. + * @type bool|array $show_in_abilities Whether this setting should be exposed through the Abilities API. + * When true, it uses the same name and schema as `$show_in_rest`. + * It may also be an array with 'name' and 'schema' keys, used + * instead of `$show_in_rest` rather than merged with it. * @type mixed $default Default value when calling `get_option()`. Only present when the * setting was registered with a default. * } diff --git a/tests/phpstan/baselines/argument.type.neon b/tests/phpstan/baselines/argument.type.neon index 193d2aa64f6f3..cdd8b0bac315e 100644 --- a/tests/phpstan/baselines/argument.type.neon +++ b/tests/phpstan/baselines/argument.type.neon @@ -429,7 +429,7 @@ parameters: count: 1 path: ../../../src/wp-content/themes/twentyeleven/inc/theme-options.php - - message: '#^Parameter \#3 \$args of function register_setting expects array\{type\?\: string, label\?\: string, description\?\: string, sanitize_callback\?\: \(callable\(\)\: mixed\)\|null, show_in_rest\?\: array\|bool, default\?\: mixed, \.\.\.\}, ''twentyeleven_theme…'' given\.$#' + message: '#^Parameter \#3 \$args of function register_setting expects array\{type\?\: string, label\?\: string, description\?\: string, sanitize_callback\?\: \(callable\(\)\: mixed\)\|null, show_in_rest\?\: array\|bool, show_in_abilities\?\: array\|bool, default\?\: mixed, \.\.\.\}, ''twentyeleven_theme…'' given\.$#' identifier: argument.type count: 1 path: ../../../src/wp-content/themes/twentyeleven/inc/theme-options.php diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php new file mode 100644 index 0000000000000..cfdc6677fff8f --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php @@ -0,0 +1,662 @@ + 'integer', + 'label' => 'Custom Ability Setting', + 'description' => 'A custom setting exposed through the Abilities API.', + 'show_in_abilities' => true, + 'default' => 42, + ) + ); + + // Temporarily remove the unhook functions so we can register core abilities. + remove_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); + remove_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); + + add_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); + add_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); + do_action( 'wp_abilities_api_categories_init' ); + do_action( 'wp_abilities_api_init' ); + + /* + * Restore the hooks and the `rest_api_init` count right away instead of after the class. + * The first test of a run snapshots the hooks and every test resets them to that snapshot, + * so changes left here would leak into every later test whenever this class runs first. + */ + remove_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); + remove_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); + add_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); + add_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); + if ( null !== $rest_api_init_count ) { + $wp_actions['rest_api_init'] = $rest_api_init_count; + } + } + + /** + * Cleans up registered abilities, categories and settings after the class. + * + * @since 7.2.0 + */ + public static function wpTearDownAfterClass(): void { + foreach ( wp_get_abilities() as $ability ) { + wp_unregister_ability( $ability->get_name() ); + } + foreach ( wp_get_ability_categories() as $ability_category ) { + wp_unregister_ability_category( $ability_category->get_slug() ); + } + + unregister_setting( 'general', 'core_settings_get_ability_test_option' ); + + global $wp_registered_settings; + $wp_registered_settings = self::$registered_settings_backup; + } + + /** + * Registers the core/settings-get ability again inside a faked init action. + * + * The class setup has already registered it through wp_register_core_abilities(), so + * the existing copy is unregistered first. + */ + private function register_ability(): void { + if ( wp_has_ability( 'core/settings-get' ) ) { + wp_unregister_ability( 'core/settings-get' ); + } + + 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_Settings() )->register(); + } + + /** + * Logs in as an administrator so abilities gated behind `manage_options` can run. + */ + private function become_admin(): void { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + } + + /** + * Core settings are exposed even when the abilities registry initializes in a request + * where `rest_api_init` (which registers core's initial settings) has never fired. + * + * The class setup registers the ability with no settings registered up front, so this + * asserts that core registered its initial settings when abilities initialized. + * + * @ticket 64605 + */ + public function test_core_settings_get_exposes_initial_settings_without_rest_api_init(): void { + $ability = wp_get_ability( 'core/settings-get' ); + + $this->assertArrayHasKey( 'title', $ability->get_output_schema()['properties'], 'The output schema should describe the site title, registered when abilities initialized.' ); + + $this->become_admin(); + $result = $ability->execute( array( 'fields' => array( 'title' ) ) ); + + $this->assertArrayHasKey( 'title', $result, 'The site title should be returned, registered when abilities initialized.' ); + } + + /** + * Tests that registering initial settings for abilities does not pollute $new_allowed_options. + * + * @ticket 64605 + */ + public function test_register_preserves_new_allowed_options(): void { + global $new_allowed_options; + + $prev_actions_count = $GLOBALS['wp_actions']['rest_api_init'] ?? null; + $prev_allowed_backup = $new_allowed_options; + unset( $GLOBALS['wp_actions']['rest_api_init'] ); + + // Simulate an existing custom setting already in $new_allowed_options. + $new_allowed_options = array( + 'general' => array( 'my_custom_option' ), + ); + + try { + _wp_register_initial_settings_for_abilities(); + + // 'admin_email' must NOT be in $new_allowed_options['general']. + $this->assertNotContains( 'admin_email', $new_allowed_options['general'], 'Registering the initial settings for abilities should not allow admin_email on the general options screen.' ); + // Prior allowed options must be preserved. + $this->assertContains( 'my_custom_option', $new_allowed_options['general'], 'The options allowed before should still be allowed.' ); + } finally { + $new_allowed_options = $prev_allowed_backup; + if ( null === $prev_actions_count ) { + unset( $GLOBALS['wp_actions']['rest_api_init'] ); + } else { + $GLOBALS['wp_actions']['rest_api_init'] = $prev_actions_count; + } + } + } + + /** + * Neither settings ability is registered when no setting is exposed to abilities. + * + * @ticket 64605 + */ + public function test_settings_abilities_are_not_registered_without_exposed_settings(): void { + global $wp_registered_settings; + + $registered_settings_backup = $wp_registered_settings; + $wp_registered_settings = array(); + + try { + $this->register_ability(); + + $this->assertFalse( wp_has_ability( 'core/settings-get' ), 'The settings ability should not be registered when no setting is exposed.' ); + } finally { + $wp_registered_settings = $registered_settings_backup; + + // Register the ability again for the tests that follow. + $this->register_ability(); + } + } + + /** + * The ability is registered in the `site` category and flagged read-only. + * + * @ticket 64605 + */ + public function test_core_settings_get_ability_is_registered(): void { + $ability = wp_get_ability( 'core/settings-get' ); + + $this->assertInstanceOf( WP_Ability::class, $ability, 'The settings ability should be registered.' ); + $this->assertSame( 'core/settings-get', $ability->get_name(), 'The registered ability should use the expected name.' ); + $this->assertSame( 'Get Settings', $ability->get_label(), 'The settings ability should use a verb-first label.' ); + $this->assertSame( 'site', $ability->get_category(), 'The settings ability should use the site category.' ); + $this->assertTrue( $ability->get_meta_item( 'public', false ), 'The settings ability should be marked public.' ); + $this->assertTrue( $ability->get_meta_item( 'show_in_rest', false ), 'The settings ability should be exposed over REST.' ); + + $annotations = $ability->get_meta_item( 'annotations', array() ); + $this->assertTrue( $annotations['readonly'], 'The settings ability should be marked read-only.' ); + $this->assertFalse( $annotations['destructive'], 'The settings ability should not be marked destructive.' ); + } + + /** + * Settings exposed with `show_in_abilities => true` use the same names as in the + * REST API settings endpoint. + * + * @ticket 64605 + */ + public function test_core_settings_get_uses_rest_api_setting_names(): void { + $properties = wp_get_ability( 'core/settings-get' )->get_output_schema()['properties']; + + foreach ( get_registered_settings() as $option_name => $args ) { + if ( empty( $args['show_in_abilities'] ) || empty( $args['show_in_rest'] ) ) { + continue; + } + + $rest_name = is_array( $args['show_in_rest'] ) && ! empty( $args['show_in_rest']['name'] ) ? $args['show_in_rest']['name'] : $option_name; + $this->assertArrayHasKey( $rest_name, $properties, "The {$option_name} setting should use its REST API name." ); + } + } + + /** + * A setting exposed with `show_in_abilities => true` reuses its REST API name and schema, + * while an array is used instead of the REST API arguments. + * + * @ticket 64605 + */ + public function test_core_settings_get_inherits_rest_api_exposure(): void { + register_setting( + 'general', + 'core_settings_get_inherit_test_option', + array( + 'show_in_rest' => array( + 'name' => 'inherited_name', + 'schema' => array( 'enum' => array( 'a', 'b' ) ), + ), + 'show_in_abilities' => true, + ) + ); + register_setting( + 'general', + 'core_settings_get_override_test_option', + array( + 'show_in_rest' => array( + 'name' => 'rest_name', + ), + 'show_in_abilities' => array( + 'name' => 'ability_name', + ), + ) + ); + + try { + $this->register_ability(); + $properties = wp_get_ability( 'core/settings-get' )->get_output_schema()['properties']; + + $this->assertSame( array( 'a', 'b' ), $properties['inherited_name']['enum'], 'A setting exposed with true should reuse its REST API schema.' ); + $this->assertArrayHasKey( 'ability_name', $properties, 'A setting exposed with an array should use the name from that array.' ); + $this->assertArrayNotHasKey( 'rest_name', $properties, 'A setting exposed with an array should not use its REST API name.' ); + } finally { + unregister_setting( 'general', 'core_settings_get_inherit_test_option' ); + unregister_setting( 'general', 'core_settings_get_override_test_option' ); + $this->register_ability(); + } + } + + /** + * Two settings exposed under the same name trigger a notice, and the later one is exposed. + * + * @ticket 64605 + * + * @expectedIncorrectUsage WP_Abilities_Settings::get_exposed_settings + */ + public function test_core_settings_get_warns_about_a_duplicate_exposed_name(): void { + register_setting( + 'general', + 'core_settings_get_ability_duplicate_test_option_a', + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => 'core_settings_get_ability_duplicate_name' ), + ) + ); + register_setting( + 'general', + 'core_settings_get_ability_duplicate_test_option_b', + array( + 'type' => 'integer', + 'show_in_abilities' => array( 'name' => 'core_settings_get_ability_duplicate_name' ), + ) + ); + + try { + $this->register_ability(); + $properties = wp_get_ability( 'core/settings-get' )->get_output_schema()['properties']; + + $this->assertSame( 'integer', $properties['core_settings_get_ability_duplicate_name']['type'], 'The setting registered later should be the one exposed under the shared name.' ); + } finally { + unregister_setting( 'general', 'core_settings_get_ability_duplicate_test_option_a' ); + unregister_setting( 'general', 'core_settings_get_ability_duplicate_test_option_b' ); + $this->register_ability(); + } + } + + /** + * The input schema exposes optional `group` and `fields` filters. + * + * @ticket 64605 + */ + public function test_core_settings_get_input_schema_exposes_group_and_fields_filters(): void { + $schema = wp_get_ability( 'core/settings-get' )->get_input_schema(); + + $this->assertSame( 'object', $schema['type'], 'The settings ability input schema should describe an object.' ); + $this->assertSame( array(), $schema['default'], 'The input should default to empty, which returns every exposed setting.' ); + $this->assertArrayNotHasKey( 'oneOf', $schema, 'The input schema should not model exclusive modes.' ); + + $this->assertContains( 'general', $schema['properties']['group']['enum'], 'The group enum should offer the general group.' ); + $this->assertContains( 'reading', $schema['properties']['group']['enum'], 'The group enum should offer the reading group.' ); + + $this->assertContains( 'title', $schema['properties']['fields']['items']['enum'], 'The fields enum should offer the site title.' ); + $this->assertContains( 'posts_per_page', $schema['properties']['fields']['items']['enum'], 'The fields enum should offer posts_per_page.' ); + $this->assertContains( 'page_for_privacy_policy', $schema['properties']['fields']['items']['enum'], 'The fields enum should offer page_for_privacy_policy.' ); + $this->assertTrue( $schema['properties']['fields']['uniqueItems'], 'The fields option should reject duplicate names.' ); + } + + /** + * Without input the ability returns a flat map of correctly typed setting values. + * + * @ticket 64605 + */ + public function test_core_settings_get_returns_flat_typed_values(): void { + $this->become_admin(); + + update_option( 'blogname', 'My Test Site' ); + update_option( 'posts_per_page', 7 ); + update_option( 'use_smilies', '1' ); + + $result = wp_get_ability( 'core/settings-get' )->execute( array() ); + + $this->assertIsArray( $result, 'The ability should return the settings.' ); + $this->assertSame( 'My Test Site', $result['title'], 'The site title should be returned as a string under its REST API name.' ); + $this->assertSame( 7, $result['posts_per_page'], 'An integer setting should be returned as an integer.' ); + $this->assertTrue( $result['use_smilies'], 'A boolean setting should be returned as a boolean.' ); + } + + /** + * The `group` filter narrows the response to a single settings group. + * + * @ticket 64605 + */ + public function test_core_settings_get_filters_by_group(): void { + $this->become_admin(); + + $result = wp_get_ability( 'core/settings-get' )->execute( array( 'group' => 'reading' ) ); + + $this->assertArrayHasKey( 'posts_per_page', $result, 'A setting of the requested group should be returned.' ); + $this->assertArrayNotHasKey( 'title', $result, 'A setting of another group should be left out.' ); + } + + /** + * The `fields` filter narrows the response to the requested setting names. + * + * @ticket 64605 + */ + public function test_core_settings_get_filters_by_fields(): void { + $this->become_admin(); + + $result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( 'title', 'posts_per_page' ) ) ); + + $this->assertEqualSets( array( 'title', 'posts_per_page' ), array_keys( $result ), 'Only the requested settings should be returned.' ); + } + + /** + * Supplying both `group` and `fields` narrows the response to their intersection. + * + * @ticket 64605 + */ + public function test_core_settings_get_combines_group_and_fields_filters(): void { + $this->become_admin(); + + // `title` is in the `general` group and `posts_per_page` in `reading`; only the + // latter satisfies both filters. + $result = wp_get_ability( 'core/settings-get' )->execute( + array( + 'group' => 'reading', + 'fields' => array( 'title', 'posts_per_page' ), + ) + ); + + $this->assertEqualSets( array( 'posts_per_page' ), array_keys( $result ), 'Only the requested setting of the requested group should be returned.' ); + } + + /** + * Input passed as an object is filtered like input passed as an array. + * + * @ticket 64605 + */ + public function test_core_settings_get_filters_object_input(): void { + $this->become_admin(); + + $result = wp_get_ability( 'core/settings-get' )->execute( (object) array( 'group' => 'reading' ) ); + + $this->assertArrayHasKey( 'posts_per_page', $result, 'A setting of the requested group should be returned for object input.' ); + $this->assertArrayNotHasKey( 'title', $result, 'A setting of another group should be left out for object input.' ); + } + + /** + * A `fields` list passed as a comma-separated string is filtered like a `fields` array. + * + * @ticket 64605 + */ + public function test_core_settings_get_filters_fields_passed_as_a_string(): void { + $this->become_admin(); + + $result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => 'title,posts_per_page' ) ); + + $this->assertEqualSets( array( 'title', 'posts_per_page' ), array_keys( $result ), 'A comma-separated fields string should select the requested settings.' ); + } + + /** + * Users without `manage_options` cannot run the ability. + * + * @ticket 64605 + */ + public function test_core_settings_get_requires_manage_options(): void { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) ); + + $result = wp_get_ability( 'core/settings-get' )->execute( array() ); + + $this->assertWPError( $result, 'A user without manage_options should be refused.' ); + $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), 'The refusal should use the invalid permissions error.' ); + } + + /** + * A setting registered with `show_in_abilities` (for example by a plugin) is exposed by the ability. + * + * @ticket 64605 + */ + public function test_core_settings_get_exposes_a_custom_registered_setting(): void { + $ability = wp_get_ability( 'core/settings-get' ); + + // Present in both the input `fields` enum and the output schema built at registration. + $this->assertContains( 'core_settings_get_ability_test_option', $ability->get_input_schema()['properties']['fields']['items']['enum'], 'A custom setting should be offered in the fields enum.' ); + $this->assertArrayHasKey( 'core_settings_get_ability_test_option', $ability->get_output_schema()['properties'], 'A custom setting should be described in the output schema.' ); + + // And returned, correctly typed, by execute. + $this->become_admin(); + update_option( 'core_settings_get_ability_test_option', 7 ); + + $result = $ability->execute( array( 'fields' => array( 'core_settings_get_ability_test_option' ) ) ); + + $this->assertSame( array( 'core_settings_get_ability_test_option' => 7 ), $result, 'A custom setting should be returned with its typed value.' ); + } + + /** + * A setting shown in the REST API without `show_in_abilities` is not exposed. + * + * @ticket 64605 + */ + public function test_core_settings_get_skips_a_setting_only_shown_in_rest(): void { + $option = 'core_settings_get_ability_rest_only_test_option'; + + register_setting( + 'general', + $option, + array( + 'show_in_rest' => true, + ) + ); + + try { + $this->register_ability(); + + $this->assertArrayNotHasKey( $option, wp_get_ability( 'core/settings-get' )->get_output_schema()['properties'], 'A setting only shown in the REST API should not be exposed.' ); + } finally { + unregister_setting( 'general', $option ); + $this->register_ability(); + } + } + + /** + * A value that does not match its schema is left out instead of failing the whole call. + * + * @ticket 64605 + */ + public function test_core_settings_get_drops_values_that_fail_their_schema(): void { + $this->become_admin(); + + // sanitize_option() only coerces '0' and '' to 'closed', so this out-of-enum value sticks. + update_option( 'default_ping_status', 'not-a-valid-status' ); + + $result = wp_get_ability( 'core/settings-get' )->execute( array() ); + + $this->assertNotWPError( $result, 'One bad value must not fail the whole ability.' ); + $this->assertArrayHasKey( 'title', $result, 'The other settings should still be returned.' ); + $this->assertArrayNotHasKey( 'default_ping_status', $result, 'Only the bad value should be left out.' ); + } + + /** + * Stored values are validated against their schema before and after sanitizing, and left out + * when it rejects them. + * + * @ticket 64605 + * + * @dataProvider data_stored_values + * + * @param string $type The setting type. + * @param mixed $stored The stored option value. + * @param string|null $expected The value as JSON, or null when it is left out. + * @param array $schema Optional. The `show_in_abilities` schema of the setting. Default empty array. + */ + public function test_core_settings_get_reads_stored_values( string $type, $stored, ?string $expected, array $schema = array() ): void { + // A numeric name, which PHP turns into an integer array key, must still match `fields`. + $option = '123'; + + register_setting( + 'general', + $option, + array( + 'type' => $type, + 'show_in_abilities' => array( 'schema' => $schema ), + ) + ); + update_option( $option, $stored ); + + try { + $this->register_ability(); + $this->become_admin(); + + $result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $option ) ) ); + } finally { + unregister_setting( 'general', $option ); + $this->register_ability(); + } + + $this->assertSame( $expected, isset( $result[ $option ] ) ? wp_json_encode( $result[ $option ] ) : null, 'The stored value should be read as expected, or left out.' ); + } + + /** + * Data provider. + * + * @return array}> Stored values, and the JSON they are read as. + */ + public static function data_stored_values(): array { + return array( + '"false" for a boolean' => array( 'boolean', 'false', 'false' ), + 'an empty string for a boolean' => array( 'boolean', '', 'false' ), + 'a stdClass for an object' => array( + 'object', + (object) array( 'a' => 1 ), + '{"a":1}', + array( 'properties' => array( 'a' => array( 'type' => 'integer' ) ) ), + ), + 'an undeclared property in an object' => array( 'object', array( 'a' => 1 ), null ), + 'an empty array for an object' => array( 'object', array(), '{}' ), + 'a list with gaps for an array' => array( + 'array', + array( + 0 => 'a', + 2 => 'b', + ), + '["a","b"]', + ), + 'a numeric string for an integer' => array( 'integer', '7', '7' ), + 'a non-numeric string for an integer' => array( 'integer', 'abc', null ), + 'an email that sanitizing breaks' => array( 'string', '%ab@x.co', null, array( 'format' => 'email' ) ), + ); + } + + /** + * A setting that was never saved reads as its registered default, or is left out when it has + * none, as the settings endpoint answers null for it, instead of reading the false that + * get_option() returns as a value. + * + * @ticket 64605 + * + * @dataProvider data_never_saved_settings + * + * @param array $args The setting registration arguments. + * @param string|null $expected The value as JSON, or null when it is left out. + */ + public function test_core_settings_get_reads_a_setting_that_was_never_saved( array $args, ?string $expected ): void { + $option = 'core_settings_get_ability_never_saved_test_option'; + + register_setting( 'general', $option, $args + array( 'show_in_abilities' => true ) ); + + try { + $this->register_ability(); + $this->become_admin(); + + $result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $option ) ) ); + } finally { + unregister_setting( 'general', $option ); + $this->register_ability(); + } + + $this->assertSame( $expected, isset( $result[ $option ] ) ? wp_json_encode( $result[ $option ] ) : null, 'The setting should read as its registered default, or be left out.' ); + } + + /** + * Data provider. + * + * @return array, 1: string|null}> Registration arguments, and the JSON the setting is read as. + */ + public static function data_never_saved_settings(): array { + return array( + 'a boolean without a default' => array( array( 'type' => 'boolean' ), null ), + 'an array without a default' => array( array( 'type' => 'array' ), null ), + 'a boolean with a default of false' => array( + array( + 'type' => 'boolean', + 'default' => false, + ), + 'false', + ), + ); + } + + /** + * A setting of a type the settings endpoint does not support is not exposed. + * + * @ticket 64605 + */ + public function test_core_settings_get_skips_a_setting_with_an_unsupported_type(): void { + $option = 'core_settings_get_ability_type_test_option'; + + register_setting( + 'general', + $option, + array( + 'type' => 'foo', + 'show_in_abilities' => true, + ) + ); + update_option( $option, 'value' ); + + try { + $this->register_ability(); + $this->become_admin(); + + $ability = wp_get_ability( 'core/settings-get' ); + + $this->assertArrayNotHasKey( $option, $ability->get_output_schema()['properties'], 'A setting of an unsupported type should not be described in the output schema.' ); + $this->assertArrayNotHasKey( $option, $ability->execute( array() ), 'A setting of an unsupported type should not be returned.' ); + } finally { + unregister_setting( 'general', $option ); + $this->register_ability(); + } + } +} diff --git a/tests/phpunit/tests/option/registration.php b/tests/phpunit/tests/option/registration.php index 850376498e91a..48ee025d2536d 100644 --- a/tests/phpunit/tests/option/registration.php +++ b/tests/phpunit/tests/option/registration.php @@ -20,6 +20,7 @@ public function test_register() { // Check defaults. $this->assertSame( 'string', $args['type'] ); $this->assertFalse( $args['show_in_rest'] ); + $this->assertFalse( $args['show_in_abilities'] ); $this->assertSame( '', $args['description'] ); } diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php new file mode 100644 index 0000000000000..278041158ef90 --- /dev/null +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php @@ -0,0 +1,222 @@ +user->create( array( 'role' => 'administrator' ) ); + self::$subscriber_id = $factory->user->create( array( 'role' => 'subscriber' ) ); + + $rest_api_init_count = $wp_actions['rest_api_init'] ?? null; + unset( $wp_actions['rest_api_init'] ); + + remove_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); + remove_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); + + foreach ( wp_get_abilities() as $ability ) { + wp_unregister_ability( $ability->get_name() ); + } + foreach ( wp_get_ability_categories() as $ability_category ) { + wp_unregister_ability_category( $ability_category->get_slug() ); + } + + add_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); + add_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); + do_action( 'wp_abilities_api_categories_init' ); + do_action( 'wp_abilities_api_init' ); + + /* + * Restore the hooks and the `rest_api_init` count right away instead of after the + * class. The first test of a run snapshots the hooks and every test resets them to + * that snapshot, so changes left here would leak into every later test whenever this + * class runs first. + */ + remove_action( 'wp_abilities_api_categories_init', 'wp_register_core_ability_categories' ); + remove_action( 'wp_abilities_api_init', 'wp_register_core_abilities' ); + add_action( 'wp_abilities_api_categories_init', '_unhook_core_ability_categories_registration', 1 ); + add_action( 'wp_abilities_api_init', '_unhook_core_abilities_registration', 1 ); + if ( null !== $rest_api_init_count ) { + $wp_actions['rest_api_init'] = $rest_api_init_count; + } + } + + /** + * Cleans up registered abilities and categories. + * + * @since 7.2.0 + */ + public static function wpTearDownAfterClass(): void { + foreach ( wp_get_abilities() as $ability ) { + wp_unregister_ability( $ability->get_name() ); + } + foreach ( wp_get_ability_categories() as $ability_category ) { + wp_unregister_ability_category( $ability_category->get_slug() ); + } + } + + public function set_up(): void { + parent::set_up(); + + global $wp_rest_server; + $wp_rest_server = new WP_REST_Server(); + $this->server = $wp_rest_server; + do_action( 'rest_api_init' ); + + wp_set_current_user( self::$admin_id ); + } + + public function tear_down(): void { + global $wp_rest_server; + $wp_rest_server = null; + + parent::tear_down(); + } + + /** + * Builds a GET run request with the given ability input. + * + * @param array $input The ability input. + * @return WP_REST_Request The request. + */ + private function run_request( array $input ): WP_REST_Request { + $request = new WP_REST_Request( 'GET', self::RUN_ROUTE ); + $request->set_query_params( array( 'input' => $input ) ); + return $request; + } + + /** + * @ticket 64605 + */ + public function test_logged_out_user_receives_401(): void { + wp_set_current_user( 0 ); + + $response = $this->server->dispatch( $this->run_request( array() ) ); + + $this->assertSame( 401, $response->get_status(), 'A logged-out request should be rejected as unauthorized.' ); + } + + /** + * @ticket 64605 + */ + public function test_subscriber_receives_403(): void { + wp_set_current_user( self::$subscriber_id ); + + $response = $this->server->dispatch( $this->run_request( array() ) ); + + $this->assertSame( 403, $response->get_status(), 'A user who cannot manage options should be rejected as forbidden.' ); + } + + /** + * @ticket 64605 + */ + public function test_admin_receives_typed_settings(): void { + update_option( 'blogname', 'REST Settings Site' ); + update_option( 'posts_per_page', 7 ); + + $response = $this->server->dispatch( $this->run_request( array() ) ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status(), 'An administrator should read the settings.' ); + $this->assertSame( 'REST Settings Site', $data['title'], 'The site title should be returned under its REST API name.' ); + $this->assertSame( 7, $data['posts_per_page'], 'An integer setting should keep its type.' ); + } + + /** + * @ticket 64605 + */ + public function test_group_filter_limits_settings(): void { + $response = $this->server->dispatch( $this->run_request( array( 'group' => 'reading' ) ) ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status(), 'A group filter should be accepted.' ); + $this->assertArrayHasKey( 'posts_per_page', $data, 'A setting of the requested group should be returned.' ); + $this->assertArrayNotHasKey( 'title', $data, 'A setting of another group should be left out.' ); + } + + /** + * A GET request delivers a list as a comma-separated string. + * + * @ticket 64605 + */ + public function test_fields_filter_from_query_string_limits_settings(): void { + $response = $this->server->dispatch( $this->run_request( array( 'fields' => 'title,posts_per_page' ) ) ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status(), 'A comma-separated fields string should be accepted.' ); + $this->assertEqualSets( array( 'title', 'posts_per_page' ), array_keys( $data ), 'Only the settings from the comma-separated list should be returned.' ); + } + + /** + * @ticket 64605 + */ + public function test_unknown_group_receives_400(): void { + $response = $this->server->dispatch( $this->run_request( array( 'group' => 'not-a-group' ) ) ); + + $this->assertSame( 400, $response->get_status(), 'An unknown group should fail input validation.' ); + $this->assertSame( 'ability_invalid_input', $response->get_data()['code'], 'The error should identify the invalid input.' ); + } + + /** + * @ticket 64605 + */ + public function test_wrong_http_method_returns_405(): void { + $request = new WP_REST_Request( 'POST', self::RUN_ROUTE ); + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( wp_json_encode( array( 'input' => array( 'group' => 'reading' ) ) ) ); + + $response = $this->server->dispatch( $request ); + + $this->assertSame( 405, $response->get_status(), 'A POST request to the read-only ability should be rejected.' ); + $this->assertSame( 'rest_ability_invalid_method', $response->get_data()['code'], 'The error should identify the invalid HTTP method.' ); + } +} diff --git a/tests/qunit/fixtures/wp-api-generated.js b/tests/qunit/fixtures/wp-api-generated.js index 5d209f1c79820..dba0cd776b59f 100644 --- a/tests/qunit/fixtures/wp-api-generated.js +++ b/tests/qunit/fixtures/wp-api-generated.js @@ -11153,7 +11153,7 @@ mockedApiResponse.Schema = { }, "url": { "title": "", - "description": "Site URL.", + "description": "The URL where WordPress core files are served. May differ from the public site URL.", "type": "string", "format": "uri", "required": false