From c20d3ff4604908d7f2c906ea9f37b055bbb14209 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Tue, 17 Nov 2026 22:00:57 +0000 Subject: [PATCH] Abilities API: Add the `core/settings-update` ability. Adds `core/settings-update`, which updates the settings exposed with the `show_in_abilities` argument and returns the saved values of the settings named in the call. A `null` value deletes the stored value of a setting, which then reads as its default when it has one. A setting whose schema sets `readonly` to true can be read with `core/settings-get`, but is left out of the update input. The ability requires the `manage_options` capability, and changing the privacy policy page also requires `manage_privacy_options`. See #64616. --- src/wp-includes/abilities.php | 3 +- .../abilities/class-wp-abilities-settings.php | 258 ++- src/wp-includes/option.php | 6 +- .../testcase-settings-ability.php | 160 ++ .../wpRegisterCoreSettingsGetAbility.php | 203 +- .../wpRegisterCoreSettingsUpdateAbility.php | 1683 +++++++++++++++++ .../wpRestAbilitiesSettingsController.php | 177 +- 7 files changed, 2300 insertions(+), 190 deletions(-) create mode 100644 tests/phpunit/tests/abilities-api/testcase-settings-ability.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index 835c19e04f949..2372ff00ef64b 100644 --- a/src/wp-includes/abilities.php +++ b/src/wp-includes/abilities.php @@ -50,6 +50,7 @@ function wp_register_core_ability_categories(): void { * * @since 6.9.0 * @since 7.2.0 Added the `core/content-query`, `core/settings-get`, and `core/users-query` abilities. + * @since 7.3.0 Added the `core/settings-update` ability. * * @global wpdb $wpdb WordPress database abstraction object. */ @@ -371,7 +372,7 @@ function wp_register_core_abilities(): void { ) ); - // Register the settings abilities (currently the read-only `core/settings-get`). + // Register the settings abilities (get and update). ( new WP_Abilities_Settings() )->register(); // Register the user abilities (currently the read-only `core/users-query`). diff --git a/src/wp-includes/abilities/class-wp-abilities-settings.php b/src/wp-includes/abilities/class-wp-abilities-settings.php index 3beb82570ccfe..37de13ac63d4e 100644 --- a/src/wp-includes/abilities/class-wp-abilities-settings.php +++ b/src/wp-includes/abilities/class-wp-abilities-settings.php @@ -12,15 +12,14 @@ /** * Core class used to register settings-related abilities. * - * Provides the read-only `core/settings-get` ability and the shared building blocks - * (exposed-settings discovery and schema generation) that are intended to also back a - * future write-oriented `core/settings-update` ability. + * Provides the `core/settings-get` and `core/settings-update` abilities and the building + * blocks they share (exposed-settings discovery, schema generation and reading the values). * * Unlike the core abilities registered directly in wp_register_core_abilities() as * self-contained closures, the settings abilities live in a dedicated class * because they share state: the set of exposed settings is computed once at registration - * and reused by the input schema, the output schema, and the execute callback, and the - * same helpers are meant to be shared with the future write ability. + * and reused by the input schemas, the output schemas, and the execute callbacks of both + * abilities. * * The exposed settings are captured when the ability registers, the first time the abilities * registry is used in a request. Settings registered later in that request are not exposed. @@ -32,6 +31,7 @@ * checks permissions before running them. * * @since 7.2.0 + * @since 7.3.0 Added the `core/settings-update` ability. * * @access private */ @@ -51,7 +51,15 @@ final class WP_Abilities_Settings { * @since 7.2.0 * @var array}> */ - private $exposed_settings = array(); + private array $exposed_settings = array(); + + /** + * Exposed settings that `core/settings-update` can write, computed once at registration. + * + * @since 7.3.0 + * @var array}> + */ + private array $writable_settings = array(); /** * Registers all settings abilities. @@ -60,6 +68,7 @@ final class WP_Abilities_Settings { * exposed to abilities. * * @since 7.2.0 + * @since 7.3.0 Registers the `core/settings-update` ability. */ public function register(): void { $this->exposed_settings = $this->get_exposed_settings(); @@ -67,7 +76,17 @@ public function register(): void { return; } + /* + * Intentionally strict: a setting whose schema is read-only cannot be updated, so naming + * it is refused like any unknown name. + */ + $this->writable_settings = array_filter( + $this->exposed_settings, + static fn( array $setting ): bool => empty( $setting['schema']['readonly'] ) + ); + $this->register_settings_get(); + $this->register_settings_update(); } /** @@ -85,7 +104,7 @@ private function register_settings_get(): void { '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(), + 'output_schema' => $this->get_settings_output_schema( __( 'A map of setting name to its current value.' ) ), 'execute_callback' => function ( $input = array() ): array { return $this->execute_settings_get( $input ); }, @@ -102,6 +121,119 @@ private function register_settings_get(): void { ); } + /** + * Registers the `core/settings-update` ability. + * + * Registers nothing when no exposed setting is writable. + * + * @since 7.3.0 + */ + private function register_settings_update(): void { + if ( empty( $this->writable_settings ) ) { + return; + } + + wp_register_ability( + 'core/settings-update', + array( + 'label' => __( 'Update Settings' ), + 'description' => __( 'Updates WordPress settings and returns the saved values of the settings named in the call. A null value deletes the stored value of a setting, which then reads as its default when it has one. Requires an authenticated user who can manage options.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_settings_update_input_schema(), + 'output_schema' => $this->get_settings_output_schema( __( 'A map of setting name to its value after the update.' ) ), + 'execute_callback' => function ( $input ) { + return $this->execute_settings_update( $input ); + }, + 'required_capabilities' => array( 'manage_options' ), + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => false, + 'idempotent' => true, + ), + 'public' => true, + ), + ) + ); + } + + /** + * Executes the `core/settings-update` ability. + * + * Every check runs before the first write, so a call that ends in an error changes nothing. + * The output holds only the settings named in the call, read the same way as for + * `core/settings-get`. + * + * @since 7.3.0 + * + * @param array{data: array} $input The ability input, as prepared by WP_Ability::execute(). + * @return array|WP_Error Map of the named setting names to their values after the update, + * or an error when the update is refused. + */ + private function execute_settings_update( array $input ) { + // A permission filter can grant the call to a user who cannot manage options, who must still not write. + if ( ! current_user_can( 'manage_options' ) ) { + return new WP_Error( + 'settings_cannot_update', + __( 'Sorry, you are not allowed to manage options for this site.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + $data = $input['data']; + $named = array_intersect_key( $this->writable_settings, $data ); + + // A setting unregistered since the abilities initialized is neither checked, written nor returned. + $registered = get_registered_settings(); + $named = array_filter( + $named, + static fn( array $setting ): bool => isset( $registered[ $setting['option'] ] ) + ); + + /* + * Intentionally strict: the whole call is refused, instead of leaving this one setting out + * of the update. The rule belongs to the option, whatever name exposes it. + */ + if ( in_array( 'wp_page_for_privacy_policy', array_column( $named, 'option' ), true ) && ! current_user_can( 'manage_privacy_options' ) ) { + return new WP_Error( + 'settings_cannot_manage_privacy_options', + __( 'Sorry, you are not allowed to manage privacy options on this site.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + /* + * Intentionally strict: every null value is checked before the first write, so a refused + * call changes nothing. A null value is refused while the stored value does not match the + * setting's schema. + */ + foreach ( $named as $exposed_name => $setting ) { + if ( null !== $data[ $exposed_name ] ) { + continue; + } + + if ( is_wp_error( rest_validate_value_from_schema( $this->get_stored_value( $setting, false ), $setting['schema'] ) ) ) { + return new WP_Error( + 'settings_invalid_stored_value', + /* translators: %s: Property name. */ + sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $exposed_name ), + array( 'status' => 500 ) + ); + } + } + + foreach ( $named as $exposed_name => $setting ) { + if ( null === $data[ $exposed_name ] ) { + delete_option( $setting['option'] ); + continue; + } + + update_option( $setting['option'], $data[ $exposed_name ] ); + } + + return $this->get_setting_values( $named ); + } + /** * Executes the `core/settings-get` ability. * @@ -115,7 +247,7 @@ private function execute_settings_get( $input = array() ): array { $group = isset( $input['group'] ) && is_string( $input['group'] ) ? $input['group'] : ''; $fields = rest_sanitize_array( $input['fields'] ?? array() ); - $result = array(); + $requested = array(); foreach ( $this->exposed_settings as $exposed_name => $setting ) { if ( '' !== $group && $setting['group'] !== $group ) { continue; @@ -124,21 +256,35 @@ private function execute_settings_get( $input = array() ): array { continue; } + $requested[ $exposed_name ] = $setting; + } + + return $this->get_setting_values( $requested ); + } + + /** + * Reads the current values of the given exposed settings. + * + * A setting without a value, or whose value does not match its schema, is left out. + * + * @since 7.3.0 + * + * @param array}> $settings Exposed settings, keyed by exposed name. + * @return array Map of exposed setting name to current value. + */ + private function get_setting_values( array $settings ): array { + $result = array(); + foreach ( $settings as $exposed_name => $setting ) { /* * 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'] ); + $value = $this->get_stored_value( $setting, $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. @@ -159,6 +305,75 @@ private function execute_settings_get( $input = array() ): array { return $result; } + /** + * Reads the stored value of an exposed setting. + * + * @since 7.3.0 + * + * @param array{option: string, group: string, default: mixed, schema: array} $setting The exposed setting. + * @param mixed $default_value The value to return when the option does not exist. + * @return mixed The stored value, or the default value. + */ + private function get_stored_value( array $setting, $default_value ) { + $value = get_option( $setting['option'], $default_value ); + + // WordPress stores false as '', which the boolean schema rejects. + if ( '' === $value && 'boolean' === $setting['schema']['type'] ) { + return false; + } + + return $value; + } + + /** + * Builds the input schema for the `core/settings-update` ability. + * + * Each writable setting accepts a value of its own schema, or null. + * + * @since 7.3.0 + * + * @return array The input JSON Schema. + */ + private function get_settings_update_input_schema(): array { + return array( + 'type' => 'object', + 'properties' => array( + 'data' => array( + 'type' => 'object', + 'description' => __( 'Settings to update, keyed by setting name. A null value deletes the stored value of a setting.' ), + 'properties' => array_map( + fn( array $schema ): array => $this->nullable_schema( $schema ), + wp_list_pluck( $this->writable_settings, 'schema' ) + ), + 'additionalProperties' => false, + 'minProperties' => 1, + ), + ), + 'required' => array( 'data' ), + 'additionalProperties' => false, + ); + } + + /** + * Allows null in a setting's value schema. + * + * Adds `null` to the type, and to the allowed values when the schema lists them. Nested + * schemas are not changed. + * + * @since 7.3.0 + * + * @param array $schema The value JSON Schema. + * @return array The value JSON Schema that also accepts null. + */ + private function nullable_schema( array $schema ): array { + $schema['type'] = array( $schema['type'], 'null' ); + if ( isset( $schema['enum'] ) ) { + $schema['enum'][] = null; + } + + return $schema; + } + /** * Builds the input schema for the `core/settings-get` ability: optional filters by group and/or name. * @@ -196,19 +411,22 @@ private function get_settings_get_input_schema( array $groups, array $field_name } /** - * Builds the output schema for the `core/settings-get` ability. + * Builds the output schema shared by the settings abilities. * - * 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. + * No setting is marked required because both abilities return a subset: `core/settings-get` + * the settings its `group` and `fields` inputs ask for, and `core/settings-update` the settings + * named in the call. A setting without a value, or whose value does not match its schema, is + * also left out. * - * @since 7.2.0 + * @since 7.3.0 * + * @param string $description The description of the output. * @return array The output JSON Schema. */ - private function get_settings_get_output_schema(): array { + private function get_settings_output_schema( string $description ): array { return array( 'type' => 'object', - 'description' => __( 'A map of setting name to its current value.' ), + 'description' => $description, 'properties' => wp_list_pluck( $this->exposed_settings, 'schema' ), 'additionalProperties' => false, ); diff --git a/src/wp-includes/option.php b/src/wp-includes/option.php index e53aedeb47ba7..75e52d638bbd6 100644 --- a/src/wp-includes/option.php +++ b/src/wp-includes/option.php @@ -3039,6 +3039,7 @@ function _wp_register_initial_settings_for_abilities(): void { * Please consider writing more inclusive code. * @since 6.6.0 Added the `label` argument. * @since 7.2.0 Added the `show_in_abilities` argument. + * @since 7.3.0 Settings exposed with the `show_in_abilities` argument can be updated through the Abilities API. * * @global array $new_allowed_options * @global array $wp_registered_settings @@ -3061,10 +3062,13 @@ function _wp_register_initial_settings_for_abilities(): void { * @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. + * @type bool|array $show_in_abilities Whether this setting should be exposed through the Abilities API, + * where users who can manage options can read and update it. * 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. + * A setting whose schema sets 'readonly' to true can be read but + * not updated. * Settings registered after abilities initialize are not exposed. * @type mixed $default Default value when calling `get_option()`. * } diff --git a/tests/phpunit/tests/abilities-api/testcase-settings-ability.php b/tests/phpunit/tests/abilities-api/testcase-settings-ability.php new file mode 100644 index 0000000000000..c33b1579e1d7a --- /dev/null +++ b/tests/phpunit/tests/abilities-api/testcase-settings-ability.php @@ -0,0 +1,160 @@ +get_name() ); + } + foreach ( wp_get_ability_categories() as $ability_category ) { + wp_unregister_ability_category( $ability_category->get_slug() ); + } + + static::unregister_test_settings(); + + global $wp_registered_settings; + $wp_registered_settings = self::$registered_settings_backup; + } + + /** + * Restores the settings registered for the class and the settings abilities after each test. + * + * A test can register or unregister settings and register the abilities again without + * cleaning up after itself, even when it fails halfway. + * + * @since 7.3.0 + */ + public function tear_down(): void { + global $wp_registered_settings, $new_allowed_options; + + $wp_registered_settings = self::$class_registered_settings; + $new_allowed_options = self::$class_allowed_options; + $this->register_ability(); + + parent::tear_down(); + } + + /** + * Registers the settings a test class needs before the abilities register. + * + * @since 7.3.0 + */ + protected static function register_test_settings(): void {} + + /** + * Unregisters the settings registered by register_test_settings(). + * + * @since 7.3.0 + */ + protected static function unregister_test_settings(): void {} + + /** + * Registers the settings abilities again inside a faked init action. + * + * The class setup has already registered them through wp_register_core_abilities(), so + * the existing copies are unregistered first. + */ + protected function register_ability(): void { + foreach ( array( 'core/settings-get', 'core/settings-update' ) as $name ) { + if ( wp_has_ability( $name ) ) { + wp_unregister_ability( $name ); + } + } + + 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. + */ + protected function become_admin(): void { + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php index cfdc6677fff8f..ff6a477dce1e8 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php @@ -2,6 +2,8 @@ declare( strict_types=1 ); +require_once __DIR__ . '/testcase-settings-ability.php'; + /** * Tests for the core/settings-get ability shipped with the Abilities API. * @@ -11,32 +13,14 @@ * * @group abilities-api */ -class Tests_Abilities_API_WpRegisterCoreSettingsGetAbility extends WP_UnitTestCase { - - /** - * Backup of the `$wp_registered_settings` global, restored after the class. - * - * @var array|null - */ - private static $registered_settings_backup; +class Tests_Abilities_API_WpRegisterCoreSettingsGetAbility extends WP_Abilities_Settings_UnitTestCase { /** - * Registers the core abilities before the class. - * - * The ability is registered under the ordering that used to break it: no settings - * registered yet and `rest_api_init` never fired, as on cron, WP-CLI, or any request - * that uses the Abilities API before the REST server loads. Core must register its - * initial settings when abilities initialize (see _wp_register_initial_settings_for_abilities()). + * Registers a non-core setting flagged for the Abilities API before the abilities register. * - * @since 7.2.0 + * @since 7.3.0 */ - public static function wpSetUpBeforeClass(): void { - global $wp_registered_settings, $wp_actions; - self::$registered_settings_backup = $wp_registered_settings; - $rest_api_init_count = $wp_actions['rest_api_init'] ?? null; - $wp_registered_settings = array(); - unset( $wp_actions['rest_api_init'] ); - + protected static function register_test_settings(): void { // A non-core setting flagged for the Abilities API, to verify that any registered // setting (not just the core ones) is exposed by the ability. register_setting( @@ -50,70 +34,15 @@ public static function wpSetUpBeforeClass(): void { '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. + * Unregisters the setting registered by register_test_settings(). * - * @since 7.2.0 + * @since 7.3.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() ); - } - + protected static function unregister_test_settings(): void { 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' ) ) ); } /** @@ -144,8 +73,6 @@ public function test_core_settings_get_exposes_initial_settings_without_rest_api 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. @@ -153,21 +80,12 @@ public function test_register_preserves_new_allowed_options(): void { '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; - } - } + _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.' ); } /** @@ -178,19 +96,10 @@ public function test_register_preserves_new_allowed_options(): void { 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(); + $wp_registered_settings = array(); + $this->register_ability(); - 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(); - } + $this->assertFalse( wp_has_ability( 'core/settings-get' ), 'The settings ability should not be registered when no setting is exposed.' ); } /** @@ -263,18 +172,12 @@ public function test_core_settings_get_inherits_rest_api_exposure(): void { ) ); - 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(); - } + $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.' ); } /** @@ -302,16 +205,10 @@ public function test_core_settings_get_warns_about_a_duplicate_exposed_name(): v ) ); - try { - $this->register_ability(); - $properties = wp_get_ability( 'core/settings-get' )->get_output_schema()['properties']; + $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(); - } + $this->assertSame( 'integer', $properties['core_settings_get_ability_duplicate_name']['type'], 'The setting registered later should be the one exposed under the shared name.' ); } /** @@ -480,14 +377,9 @@ public function test_core_settings_get_skips_a_setting_only_shown_in_rest(): voi ) ); - try { - $this->register_ability(); + $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(); - } + $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.' ); } /** @@ -535,15 +427,10 @@ public function test_core_settings_get_reads_stored_values( string $type, $store ); update_option( $option, $stored ); - try { - $this->register_ability(); - $this->become_admin(); + $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(); - } + $result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $option ) ) ); $this->assertSame( $expected, isset( $result[ $option ] ) ? wp_json_encode( $result[ $option ] ) : null, 'The stored value should be read as expected, or left out.' ); } @@ -596,15 +483,10 @@ public function test_core_settings_get_reads_a_setting_that_was_never_saved( arr register_setting( 'general', $option, $args + array( 'show_in_abilities' => true ) ); - try { - $this->register_ability(); - $this->become_admin(); + $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(); - } + $result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $option ) ) ); $this->assertSame( $expected, isset( $result[ $option ] ) ? wp_json_encode( $result[ $option ] ) : null, 'The setting should read as its registered default, or be left out.' ); } @@ -646,17 +528,12 @@ public function test_core_settings_get_skips_a_setting_with_an_unsupported_type( ); update_option( $option, 'value' ); - try { - $this->register_ability(); - $this->become_admin(); + $this->register_ability(); + $this->become_admin(); - $ability = wp_get_ability( 'core/settings-get' ); + $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(); - } + $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.' ); } } diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php new file mode 100644 index 0000000000000..2a7d89d9a3afc --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php @@ -0,0 +1,1683 @@ + + */ + private static $user_ids = array(); + + /** + * Number of calls of the sanitize callback of the test setting. + * + * @var int + */ + private static $sanitize_calls = 0; + + /** + * Creates a user for each role without `manage_options`. + * + * @since 7.3.0 + * + * @param WP_UnitTest_Factory $factory The unit test factory. + */ + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void { + parent::wpSetUpBeforeClass( $factory ); + + foreach ( array( 'subscriber', 'contributor', 'author', 'editor' ) as $role ) { + self::$user_ids[ $role ] = $factory->user->create( array( 'role' => $role ) ); + } + } + + /** + * Registers plugin settings exposed to abilities before the abilities register. + * + * @since 7.3.0 + */ + protected static function register_test_settings(): void { + register_setting( + 'general', + 'settings_update_test_array', + array( + 'type' => 'array', + 'show_in_abilities' => array( + 'schema' => array( + 'items' => array( 'type' => 'integer' ), + ), + ), + ) + ); + register_setting( + 'general', + 'settings_update_test_object', + array( + 'type' => 'object', + 'show_in_abilities' => array( + 'schema' => array( + 'properties' => array( + 'a' => array( 'type' => 'integer' ), + 'n' => array( + 'type' => 'object', + 'properties' => array( + 'b' => array( 'type' => 'number' ), + ), + ), + ), + ), + ), + ) + ); + register_setting( + 'general', + 'settings_update_test_email_option', + array( + 'type' => 'string', + 'show_in_abilities' => array( + 'name' => 'settings_update_test_email', + 'schema' => array( 'format' => 'email' ), + ), + ) + ); + register_setting( + 'general', + 'settings_update_test_uri', + array( + 'type' => 'string', + 'show_in_abilities' => array( + 'schema' => array( 'format' => 'uri' ), + ), + ) + ); + register_setting( + 'general', + 'settings_update_test_numeric_option', + array( + 'type' => 'integer', + 'show_in_abilities' => array( 'name' => '456' ), + ) + ); + register_setting( + 'general', + 'settings_update_test_mixed_case_option', + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => 'Mixed_Case_Name' ), + ) + ); + register_setting( + 'general', + 'settings_update_test_readonly', + array( + 'type' => 'string', + 'show_in_abilities' => array( + 'schema' => array( 'readonly' => true ), + ), + ) + ); + register_setting( + 'general', + 'settings_update_test_readonly_false', + array( + 'type' => 'string', + 'show_in_abilities' => array( + 'schema' => array( 'readonly' => false ), + ), + ) + ); + } + + /** + * Unregisters the settings registered by register_test_settings(). + * + * @since 7.3.0 + */ + protected static function unregister_test_settings(): void { + unregister_setting( 'general', 'settings_update_test_array' ); + unregister_setting( 'general', 'settings_update_test_object' ); + unregister_setting( 'general', 'settings_update_test_email_option' ); + unregister_setting( 'general', 'settings_update_test_uri' ); + unregister_setting( 'general', 'settings_update_test_numeric_option' ); + unregister_setting( 'general', 'settings_update_test_mixed_case_option' ); + unregister_setting( 'general', 'settings_update_test_readonly' ); + unregister_setting( 'general', 'settings_update_test_readonly_false' ); + } + + /** + * Sanitize callback of a test setting: counts its calls and upper-cases the value. + * + * @since 7.3.0 + * + * @param mixed $value The value to sanitize. + * @return string The upper-cased value. + */ + public static function sanitize_test_value( $value ): string { + ++self::$sanitize_calls; + return strtoupper( (string) $value ); + } + + /** + * Runs the ability with the given `data`. + * + * @param array $data The settings to update. + * @return mixed The result of the ability. + */ + private function update( array $data ) { + return wp_get_ability( self::ABILITY )->execute( array( 'data' => $data ) ); + } + + /** + * Returns the stored rows of every registered setting, read from the database. + * + * An option without a row is absent from the result. + * + * @return array Raw option values keyed by option name. + */ + private function snapshot(): array { + global $wpdb; + + $options = array_map( 'strval', array_keys( get_registered_settings() ) ); + $in = implode( ', ', array_fill( 0, count( $options ), '%s' ) ); + $rows = $wpdb->get_results( + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- The placeholders are built above. + $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name IN ( {$in} )", $options ), + ARRAY_A + ); + + $snapshot = array_column( $rows, 'option_value', 'option_name' ); + ksort( $snapshot ); + return $snapshot; + } + + /** + * Returns the raw stored value of one option, read from the database. + * + * @param string $option The option name. + * @return string|null The raw value, or null when there is no row. + */ + private function raw_row( string $option ): ?string { + global $wpdb; + + return $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option ) ); + } + + /** + * Asserts that two snapshots hold the same rows, whatever the order of their keys. + * + * @param array $expected The expected rows. + * @param array $actual The actual rows. + * @param string $message The assertion message. + */ + private function assert_snapshot( array $expected, array $actual, string $message ): void { + ksort( $expected ); + ksort( $actual ); + $this->assertSame( $expected, $actual, $message ); + } + + /** + * Stores a raw value for an option directly in the database, or removes its row. + * + * @param string $option The option name. + * @param mixed $value The value to store, or null to remove the row. + */ + private function store_raw( string $option, $value ): void { + global $wpdb; + + $wpdb->delete( $wpdb->options, array( 'option_name' => $option ) ); + if ( null !== $value ) { + $wpdb->insert( + $wpdb->options, + array( + 'option_name' => $option, + 'option_value' => maybe_serialize( $value ), + 'autoload' => 'on', + ) + ); + } + + wp_cache_delete( 'alloptions', 'options' ); + wp_cache_delete( 'notoptions', 'options' ); + wp_cache_delete( $option, 'options' ); + } + + /** + * Logs in as an administrator who can also set the privacy policy page when the setting needs it. + * + * @param string $name The exposed setting name the test writes. + */ + private function become_admin_for( string $name ): void { + $this->become_admin(); + if ( is_multisite() && 'page_for_privacy_policy' === $name ) { + grant_super_admin( get_current_user_id() ); + } + } + + /** + * Adds a filter that takes `manage_privacy_options` away from every user. + */ + private function deny_privacy_capability(): void { + add_filter( + 'map_meta_cap', + static function ( $caps, $cap ) { + return 'manage_privacy_options' === $cap ? array( 'do_not_allow' ) : $caps; + }, + 10, + 2 + ); + } + + /** + * Asserts that a result is an error with the given code. + * + * @param mixed $result The result of the ability. + * @param string $code The expected error code. + */ + private function assert_error_code( $result, string $code ): void { + $this->assertWPError( $result, "The call should fail with {$code}." ); + $this->assertSame( $code, $result->get_error_code(), 'The call should fail with the expected error code.' ); + } + + /** + * Asserts that a result is an error with the given code, status and message. + * + * @param mixed $result The result of the ability. + * @param string $code The expected error code. + * @param int $status The expected status. + * @param string $message The expected message. + */ + private function assert_error( $result, string $code, int $status, string $message ): void { + $this->assert_error_code( $result, $code ); + $this->assertSame( $message, $result->get_error_message(), 'The error should use the expected message.' ); + $this->assertSame( array( 'status' => $status ), $result->get_error_data(), 'The error data should hold only the expected status.' ); + } + + /** + * The ability is registered with its label and category. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_is_registered_with_label_and_category(): void { + $ability = wp_get_ability( self::ABILITY ); + + $this->assertInstanceOf( WP_Ability::class, $ability, 'The ability should be registered.' ); + $this->assertSame( 'Update Settings', $ability->get_label(), 'The ability should use a verb-first label.' ); + $this->assertSame( 'site', $ability->get_category(), 'The ability should use the site category.' ); + $this->assertNotEmpty( $ability->get_description(), 'The ability should have a description.' ); + $this->assertStringNotContainsString( '`', $ability->get_description(), 'The description should not use backticks.' ); + } + + /** + * The ability is flagged as a non-destructive, idempotent write, with the other meta of + * core/settings-get. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_annotations_and_meta(): void { + $meta = wp_get_ability( self::ABILITY )->get_meta(); + $annotations = $meta['annotations']; + $get_meta = wp_get_ability( 'core/settings-get' )->get_meta(); + unset( $meta['annotations'], $get_meta['annotations'] ); + + $this->assertFalse( $annotations['readonly'], 'The ability should not be marked read-only.' ); + $this->assertFalse( $annotations['destructive'], 'The ability should not be marked destructive.' ); + $this->assertTrue( $annotations['idempotent'], 'The ability should be marked idempotent.' ); + $this->assertSame( $get_meta, $meta, 'The other meta should match core/settings-get.' ); + } + + /** + * The ability requires `manage_options`. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_requires_manage_options(): void { + $this->assertSame( array( 'manage_options' ), wp_get_ability( self::ABILITY )->get_required_capabilities() ); + } + + /** + * The input is an object with a required, non-empty `data` object keyed by the exposed names. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_input_schema_shape(): void { + $schema = wp_get_ability( self::ABILITY )->get_input_schema(); + $data = $schema['properties']['data']; + + $this->assertSame( 'object', $schema['type'], 'The input should be an object.' ); + $this->assertFalse( $schema['additionalProperties'], 'The input should reject other keys.' ); + $this->assertSame( array( 'data' ), $schema['required'], 'The input should require data.' ); + $this->assertSame( array( 'data' ), array_keys( $schema['properties'] ), 'The input should only accept data.' ); + $this->assertArrayNotHasKey( 'default', $schema, 'The input should have no default.' ); + $this->assertSame( 'object', $data['type'], 'The data should be an object.' ); + $this->assertFalse( $data['additionalProperties'], 'The data should reject names that are not exposed.' ); + $this->assertSame( 1, $data['minProperties'], 'The data should name at least one setting.' ); + $this->assertArrayNotHasKey( 'default', $data, 'The data should have no default.' ); + $this->assertSameSets( + array_diff( array_map( 'strval', array_keys( wp_get_ability( 'core/settings-get' )->get_output_schema()['properties'] ) ), array( 'settings_update_test_readonly' ) ), + array_map( 'strval', array_keys( $data['properties'] ) ), + 'The data should accept exactly the exposed settings that are not read-only.' + ); + } + + /** + * Each setting in the input accepts its value schema or null. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_input_schema_property_allows_null(): void { + $properties = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties']; + + $this->assertSame( + array( + 'type' => array( 'string', 'null' ), + 'format' => 'uri', + ), + $properties['settings_update_test_uri'], + 'A setting should accept a value of its schema or null.' + ); + $this->assertSame( array( 'string', 'null' ), $properties['default_ping_status']['type'], 'A setting that lists its allowed values should accept null too.' ); + $this->assertSame( array( 'open', 'closed', null ), $properties['default_ping_status']['enum'], 'Null should be added to the allowed values.' ); + } + + /** + * The output describes the same settings as the output of core/settings-get. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_output_schema_matches_settings_get(): void { + $schema = wp_get_ability( self::ABILITY )->get_output_schema(); + + $this->assertSame( 'object', $schema['type'], 'The output should be an object.' ); + $this->assertFalse( $schema['additionalProperties'], 'The output should reject other keys.' ); + $this->assertArrayNotHasKey( 'required', $schema, 'No setting should be required in the output.' ); + $this->assertSame( wp_get_ability( 'core/settings-get' )->get_output_schema()['properties'], $schema['properties'], 'The output should describe the settings as core/settings-get does.' ); + } + + /** + * The ability is not registered when no setting is exposed to abilities. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_not_registered_without_exposed_settings(): void { + global $wp_registered_settings; + + $wp_registered_settings = array(); + $this->register_ability(); + + $this->assertFalse( wp_has_ability( self::ABILITY ) ); + } + + /** + * The update ability is not registered when every exposed setting is read-only, while + * core/settings-get still is. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_not_registered_with_only_read_only_settings(): void { + global $wp_registered_settings; + + $wp_registered_settings = array( + 'settings_update_test_readonly' => $wp_registered_settings['settings_update_test_readonly'], + ); + $this->register_ability(); + + $this->assertFalse( wp_has_ability( self::ABILITY ), 'The update ability should not be registered without a writable setting.' ); + $this->assertTrue( wp_has_ability( 'core/settings-get' ), 'The get ability should still be registered.' ); + } + + /** + * A read-only setting is left out of the input, but is still described in the output and read + * by core/settings-get. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_read_only_setting_is_not_writable_but_still_read(): void { + $name = 'settings_update_test_readonly'; + $this->store_raw( $name, 'Locked' ); + $this->become_admin(); + + $input_properties = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties']; + $read = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $name ) ) ); + + $this->assertArrayNotHasKey( $name, $input_properties, 'The read-only setting should not be in the input schema.' ); + $this->assertArrayHasKey( $name, wp_get_ability( self::ABILITY )->get_output_schema()['properties'], 'The read-only setting should stay in the output schema of the update ability.' ); + $this->assertArrayHasKey( $name, wp_get_ability( 'core/settings-get' )->get_output_schema()['properties'], 'The read-only setting should stay in the output schema of the get ability.' ); + $this->assertSame( array( $name => 'Locked' ), $read, 'The get ability should still return the read-only setting.' ); + } + + /** + * A setting registered without `show_in_abilities` cannot be written. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_setting_without_show_in_abilities_is_not_accepted(): void { + $option = 'settings_update_test_hidden'; + + register_setting( 'general', $option, array( 'type' => 'string' ) ); + $this->register_ability(); + $this->become_admin(); + $before = $this->snapshot(); + + $properties = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties']; + $result = $this->update( array( $option => 'x' ) ); + $after = $this->snapshot(); + + $this->assertArrayNotHasKey( $option, $properties, 'The setting should not be in the input schema.' ); + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assert_snapshot( $before, $after, 'Nothing should be written.' ); + } + + /** + * A setting registered after the ability cannot be written. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_setting_registered_after_the_ability_is_not_accepted(): void { + $option = 'settings_update_test_late'; + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_abilities' => true, + ) + ); + $this->become_admin(); + $before = $this->snapshot(); + + $properties = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties']; + $result = $this->update( array( $option => 'x' ) ); + $after = $this->snapshot(); + + $this->assertArrayNotHasKey( $option, $properties, 'The setting should not be in the input schema.' ); + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assert_snapshot( $before, $after, 'Nothing should be written.' ); + } + + /** + * The provider of settings covers every exposed core setting. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_provider_covers_every_exposed_core_setting(): void { + $exposed = array_diff( + array_map( 'strval', array_keys( wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties'] ) ), + self::TEST_SETTING_NAMES + ); + $covered = array_diff( array_column( self::data_settings(), 0 ), self::TEST_SETTING_NAMES ); + + $this->assertSameSets( $exposed, $covered, 'Every exposed core setting should be covered.' ); + } + + /** + * Users without `manage_options` cannot update settings. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_roles_without_manage_options + * + * @param string|null $role The role of the user, or null when logged out. + */ + public function test_users_without_manage_options_cannot_update( ?string $role ): void { + wp_set_current_user( null === $role ? 0 : self::$user_ids[ $role ] ); + $before = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Changed title', + 'posts_per_page' => 3, + ) + ); + + $this->assert_error_code( $result, 'ability_invalid_permissions' ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Roles without `manage_options`, null when logged out. + */ + public static function data_roles_without_manage_options(): array { + return array( + 'subscriber' => array( 'subscriber' ), + 'contributor' => array( 'contributor' ), + 'author' => array( 'author' ), + 'editor' => array( 'editor' ), + 'logged out' => array( null ), + ); + } + + /** + * The permission check refuses users without `manage_options` whatever the raw input. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_roles_and_raw_inputs + * + * @param string|null $role The role of the user, or null when logged out. + * @param mixed $input The raw input. + */ + public function test_check_permissions_refuses_raw_input( ?string $role, $input ): void { + wp_set_current_user( null === $role ? 0 : self::$user_ids[ $role ] ); + + $this->assertFalse( wp_get_ability( self::ABILITY )->check_permissions( $input ) ); + } + + /** + * Data provider. + * + * @return array Roles and raw inputs. + */ + public static function data_roles_and_raw_inputs(): array { + $inputs = array( + 'valid input' => array( 'data' => array( 'title' => 'Changed title' ) ), + 'a string' => 'not-an-object', + 'null' => null, + 'an option name inside' => array( 'data' => array( 'blogname' => 'Changed title' ) ), + ); + + $data = array(); + foreach ( self::data_roles_without_manage_options() as $role_label => $role ) { + foreach ( $inputs as $input_label => $input ) { + $data[ "{$role_label}, {$input_label}" ] = array( $role[0], $input ); + } + } + return $data; + } + + /** + * An administrator passes the permission check whatever the raw input. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_check_permissions_allows_administrator_with_raw_input(): void { + $this->become_admin(); + $ability = wp_get_ability( self::ABILITY ); + + $this->assertTrue( $ability->check_permissions( 'not-an-object' ), 'A string input should not change the permission check.' ); + $this->assertTrue( $ability->check_permissions( null ), 'A null input should not change the permission check.' ); + } + + /** + * A user without `manage_options` cannot update settings even when a filter grants permission. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_users_granted_permission + * + * @param string|null $role The role of the user, or null when logged out. + * @param int $status The expected status. + */ + public function test_granted_permission_without_manage_options_cannot_update( ?string $role, int $status ): void { + wp_set_current_user( null === $role ? 0 : self::$user_ids[ $role ] ); + add_filter( 'wp_ability_permission_result', '__return_true' ); + $before = $this->snapshot(); + + $result = $this->update( array( 'title' => 'Changed title' ) ); + + $this->assert_error( $result, 'settings_cannot_update', $status, self::CANNOT_UPDATE_MESSAGE ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Roles, null when logged out, and the expected status. + */ + public static function data_users_granted_permission(): array { + return array( + 'subscriber' => array( 'subscriber', 403 ), + 'editor' => array( 'editor', 403 ), + 'logged out' => array( null, 401 ), + ); + } + + /** + * A site administrator cannot set or reset the privacy policy page on multisite, and the other + * settings of the call are not written either. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_privacy_policy_page_values + * + * @param int|null $value The privacy policy page to set, or null to reset it. + */ + public function test_site_administrator_cannot_set_privacy_policy_page( ?int $value ): void { + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Changed title', + 'page_for_privacy_policy' => $value, + ) + ); + + $this->assert_error( $result, 'settings_cannot_manage_privacy_options', 403, self::CANNOT_MANAGE_PRIVACY_MESSAGE ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * An administrator without `manage_privacy_options` cannot set or reset the privacy policy page, + * and the other settings of the call are not written either. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_privacy_policy_page_values + * + * @param int|null $value The privacy policy page to set, or null to reset it. + */ + public function test_privacy_policy_page_refused_without_capability( ?int $value ): void { + $this->become_admin_for( 'page_for_privacy_policy' ); + $this->deny_privacy_capability(); + $before = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Changed title', + 'page_for_privacy_policy' => $value, + ) + ); + + $this->assert_error( $result, 'settings_cannot_manage_privacy_options', 403, self::CANNOT_MANAGE_PRIVACY_MESSAGE ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Privacy policy page values. + */ + public static function data_privacy_policy_page_values(): array { + return array( + 'a page ID' => array( 5 ), + 'null' => array( null ), + ); + } + + /** + * The privacy policy page rule holds when the option is exposed under another name, and does + * not apply once the setting is unregistered, since nothing is written for it then. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_privacy_page_under_another_name + * + * @param bool $unregister Whether the setting is unregistered before the call. + * @param string|null $code The expected error code, or null when the call succeeds. + */ + public function test_privacy_rule_follows_the_option_under_another_name( bool $unregister, ?string $code ): void { + register_setting( + 'reading', + 'wp_page_for_privacy_policy', + array( + 'type' => 'integer', + 'show_in_abilities' => array( 'name' => 'settings_update_test_privacy_page' ), + ) + ); + $this->register_ability(); + if ( $unregister ) { + unregister_setting( 'reading', 'wp_page_for_privacy_policy' ); + } + $this->become_admin_for( 'page_for_privacy_policy' ); + $this->deny_privacy_capability(); + $before = $this->snapshot(); + + $result = $this->update( array( 'settings_update_test_privacy_page' => 5 ) ); + $after = $this->snapshot(); + + if ( null === $code ) { + $this->assertSame( array(), $result, 'The unregistered setting should be left out of the output.' ); + } else { + $this->assert_error( $result, $code, 403, self::CANNOT_MANAGE_PRIVACY_MESSAGE ); + } + $this->assert_snapshot( $before, $after, 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Whether the setting is unregistered, and the expected error code. + */ + public static function data_privacy_page_under_another_name(): array { + return array( + 'registered' => array( false, 'settings_cannot_manage_privacy_options' ), + 'unregistered before the call' => array( true, null ), + ); + } + + /** + * Input that does not match the input schema is refused and nothing is written. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_invalid_input + * + * @param mixed $input The input. + */ + public function test_rejects_invalid_input( $input ): void { + $this->store_raw( 'settings_update_test_readonly', 'Locked' ); + $this->become_admin(); + $before = $this->snapshot(); + + $result = wp_get_ability( self::ABILITY )->execute( $input ); + + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Invalid inputs. + */ + public static function data_invalid_input(): array { + return array( + 'an unknown name' => array( array( 'data' => array( 'settings_update_test_unknown' => 'x' ) ) ), + 'an option name instead of the setting name' => array( array( 'data' => array( 'blogname' => 'x' ) ) ), + 'a name in another case' => array( array( 'data' => array( 'Title' => 'x' ) ) ), + 'a read-only setting' => array( array( 'data' => array( 'settings_update_test_readonly' => 'x' ) ) ), + 'null for a read-only setting' => array( array( 'data' => array( 'settings_update_test_readonly' => null ) ) ), + 'a read-only setting with a writable one' => array( + array( + 'data' => array( + 'title' => 'Changed title', + 'settings_update_test_readonly' => 'x', + ), + ), + ), + 'a mixed-case name in lower case' => array( array( 'data' => array( 'mixed_case_name' => 'x' ) ) ), + 'a numeric key that is not a setting name' => array( array( 'data' => array( 0 => 'x' ) ) ), + 'a nested key' => array( array( 'data' => array( 'title' => array( 'blogname' => 'x' ) ) ) ), + 'another top-level key' => array( + array( + 'data' => array( 'title' => 'x' ), + 'fields' => array( 'title' ), + ), + ), + 'a string input' => array( 'title' ), + 'no data' => array( array() ), + 'null data' => array( array( 'data' => null ) ), + 'a string for data' => array( array( 'data' => 'title' ) ), + 'an empty array for data' => array( array( 'data' => array() ) ), + 'an empty object for data' => array( array( 'data' => new stdClass() ) ), + 'an object for a string' => array( array( 'data' => array( 'title' => array( 'rendered' => 'x' ) ) ) ), + 'a float for an integer' => array( array( 'data' => array( 'posts_per_page' => 12.5 ) ) ), + 'true for an integer' => array( array( 'data' => array( 'posts_per_page' => true ) ) ), + 'an empty string for an integer' => array( array( 'data' => array( 'posts_per_page' => '' ) ) ), + 'a word for a boolean' => array( array( 'data' => array( 'use_smilies' => 'yes' ) ) ), + 'an empty string for a boolean' => array( array( 'data' => array( 'use_smilies' => '' ) ) ), + 'a value in another case for an enum' => array( array( 'data' => array( 'default_ping_status' => 'OPEN' ) ) ), + 'an empty string for an enum' => array( array( 'data' => array( 'default_ping_status' => '' ) ) ), + 'two values for an enum' => array( array( 'data' => array( 'default_ping_status' => 'open&closed' ) ) ), + 'an invalid email address' => array( array( 'data' => array( 'settings_update_test_email' => 'not-an-email' ) ) ), + 'an invalid array item' => array( array( 'data' => array( 'settings_update_test_array' => array( 'invalid' ) ) ) ), + 'an unknown object property' => array( + array( + 'data' => array( + 'settings_update_test_object' => array( + 'a' => 1, + 'b' => 2, + ), + ), + ), + ), + 'an unknown nested object property' => array( + array( + 'data' => array( + 'settings_update_test_object' => array( + 'n' => array( + 'b' => 1, + 'c' => 1, + ), + ), + ), + ), + ), + 'an invalid object property' => array( array( 'data' => array( 'settings_update_test_object' => array( 'a' => 'invalid' ) ) ) ), + 'a valid setting before an invalid one' => array( + array( + 'data' => array( + 'title' => 'Changed title', + 'posts_per_page' => 'abc', + ), + ), + ), + ); + } + + /** + * The site address and the administration email address cannot be written on multisite. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @group ms-required + * + * @dataProvider data_single_site_settings + * + * @param string $name The setting name. + * @param string $value A valid value. + */ + public function test_rejects_url_and_email_on_multisite( string $name, string $value ): void { + $this->become_admin(); + $before = $this->snapshot(); + + $properties = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties']; + $result = $this->update( array( $name => $value ) ); + + $this->assertArrayNotHasKey( $name, $properties, 'The setting should not be in the input schema.' ); + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Setting names and valid values. + */ + public static function data_single_site_settings(): array { + return array( + 'url' => array( 'url', 'https://acme.example' ), + 'email' => array( 'email', 'owner@acme.example' ), + ); + } + + /** + * Each setting is written, read back, and stored. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_settings + * + * @param string $name The exposed setting name. + * @param string $option The option name. + * @param mixed $value A valid value. + * @param string $output The expected output value as JSON. + * @param string $raw The expected raw stored value. + */ + public function test_updates_each_setting( string $name, string $option, $value, string $output, string $raw ): void { + $this->become_admin_for( $name ); + $expected = $this->snapshot(); + + $result = $this->update( array( $name => $value ) ); + + $this->assertNotWPError( $result, 'The setting should be written.' ); + $this->assertSameSets( array( $name ), array_map( 'strval', array_keys( $result ) ), 'The output should hold only the setting named in the call.' ); + $this->assertSame( $output, wp_json_encode( $result[ $name ] ), 'The output should show the saved value.' ); + + $read = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $name ) ) ); + $this->assertSame( $output, wp_json_encode( $read[ $name ] ), 'The saved value should be read back the same way.' ); + + wp_cache_delete( 'alloptions', 'options' ); + $expected[ $option ] = $raw; + $this->assert_snapshot( $expected, $this->snapshot(), 'Only the option of the named setting should change.' ); + + $read = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $name ) ) ); + $this->assertSame( $output, wp_json_encode( $read[ $name ] ), 'The saved value should be read back the same way from the database.' ); + } + + /** + * A null value deletes the stored value of each setting, which then reads as its default or + * is left out. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_settings + * + * @param string $name The exposed setting name. + * @param string $option The option name. + * @param mixed $value A valid value. + * @param string $output The expected output value as JSON. + * @param string $raw The expected raw stored value. + * @param string|null $after_null The output value after a null value as JSON, or null when it is left out. + */ + public function test_null_deletes_each_setting( string $name, string $option, $value, string $output, string $raw, ?string $after_null ): void { + update_option( $option, $value ); + $this->become_admin_for( $name ); + $expected = $this->snapshot(); + unset( $expected[ $option ] ); + + $result = $this->update( array( $name => null ) ); + + $this->assertNotWPError( $result, 'The stored value should be deleted.' ); + $this->assertSame( null === $after_null ? '[]' : '{"' . $name . '":' . $after_null . '}', wp_json_encode( $result ), 'The setting should read as its default, or be left out.' ); + $this->assert_snapshot( $expected, $this->snapshot(), 'Only the row of the named setting should be deleted.' ); + } + + /** + * Data provider. + * + * Every exposed core setting, plus the settings this class registers. + * + * @return array Settings with a valid value. + */ + public static function data_settings(): array { + $data = array( + 'title' => array( 'title', 'blogname', 'Acme Robotics', '"Acme Robotics"', 'Acme Robotics', null ), + 'description' => array( 'description', 'blogdescription', 'Robots for everyone', '"Robots for everyone"', 'Robots for everyone', null ), + 'url' => array( 'url', 'siteurl', 'https://acme.example', '"https:\/\/acme.example"', 'https://acme.example', null ), + 'email' => array( 'email', 'admin_email', 'owner@acme.example', '"owner@acme.example"', 'owner@acme.example', null ), + 'timezone' => array( 'timezone', 'timezone_string', 'Europe/Lisbon', '"Europe\/Lisbon"', 'Europe/Lisbon', null ), + 'date_format' => array( 'date_format', 'date_format', 'Y-m-d', '"Y-m-d"', 'Y-m-d', null ), + 'time_format' => array( 'time_format', 'time_format', 'H:i', '"H:i"', 'H:i', null ), + 'start_of_week' => array( 'start_of_week', 'start_of_week', 3, '3', '3', null ), + 'language' => array( 'language', 'WPLANG', 'de_DE', '"de_DE"', 'de_DE', '"en_US"' ), + 'use_smilies' => array( 'use_smilies', 'use_smilies', false, 'false', '', 'true' ), + 'default_category' => array( 'default_category', 'default_category', 7, '7', '7', null ), + 'default_post_format' => array( 'default_post_format', 'default_post_format', 'aside', '"aside"', 'aside', null ), + 'posts_per_page' => array( 'posts_per_page', 'posts_per_page', 12, '12', '12', '10' ), + 'show_on_front' => array( 'show_on_front', 'show_on_front', 'page', '"page"', 'page', null ), + 'page_on_front' => array( 'page_on_front', 'page_on_front', 5, '5', '5', null ), + 'page_for_posts' => array( 'page_for_posts', 'page_for_posts', 6, '6', '6', null ), + 'page_for_privacy_policy' => array( 'page_for_privacy_policy', 'wp_page_for_privacy_policy', 8, '8', '8', null ), + 'default_ping_status' => array( 'default_ping_status', 'default_ping_status', 'closed', '"closed"', 'closed', null ), + 'default_comment_status' => array( 'default_comment_status', 'default_comment_status', 'closed', '"closed"', 'closed', null ), + 'an array setting' => array( 'settings_update_test_array', 'settings_update_test_array', array( '1', '2' ), '[1,2]', 'a:2:{i:0;i:1;i:1;i:2;}', null ), + 'an empty array setting' => array( 'settings_update_test_array', 'settings_update_test_array', array(), '[]', 'a:0:{}', null ), + 'an object setting' => array( 'settings_update_test_object', 'settings_update_test_object', array( 'a' => 1 ), '{"a":1}', 'a:1:{s:1:"a";i:1;}', null ), + 'an empty object setting' => array( 'settings_update_test_object', 'settings_update_test_object', array(), '{}', 'a:0:{}', null ), + 'a setting with numeric name' => array( '456', 'settings_update_test_numeric_option', 9, '9', '9', null ), + 'a setting with mixed-case name' => array( 'Mixed_Case_Name', 'settings_update_test_mixed_case_option', 'Mixed', '"Mixed"', 'Mixed', null ), + 'a setting with readonly false' => array( 'settings_update_test_readonly_false', 'settings_update_test_readonly_false', 'Open', '"Open"', 'Open', null ), + ); + + if ( is_multisite() ) { + unset( $data['url'], $data['email'] ); + } + + return $data; + } + + /** + * Input values are converted to the type of the setting and sanitized when they are saved, and + * the output shows the value that was saved, not the value that was sent. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_saved_values + * + * @param string $name The exposed setting name. + * @param string $option The option name. + * @param mixed $stored The raw value stored before the call. + * @param mixed $value The value to write. + * @param string $output The expected output value as JSON. + * @param string $raw The expected raw stored value. + */ + public function test_output_shows_the_saved_value( string $name, string $option, $stored, $value, string $output, string $raw ): void { + $this->store_raw( $option, $stored ); + $this->become_admin(); + $expected = $this->snapshot(); + + $result = $this->update( array( $name => $value ) ); + + $this->assertNotWPError( $result, 'The setting should be written.' ); + $this->assertSameSets( array( $name ), array_map( 'strval', array_keys( $result ) ), 'The output should hold only the setting named in the call.' ); + $this->assertSame( $output, wp_json_encode( $result[ $name ] ), 'The output should show the value that was saved.' ); + + $expected[ $option ] = $raw; + $this->assert_snapshot( $expected, $this->snapshot(), 'Only the option of the named setting should hold the saved value.' ); + } + + /** + * Data provider. + * + * @return array Values that are converted or saved differently. + */ + public static function data_saved_values(): array { + return array( + 'a numeric string for an integer' => array( 'posts_per_page', 'posts_per_page', '10', '12', '12', '12' ), + 'a whole float for an integer' => array( 'posts_per_page', 'posts_per_page', '10', 12.0, '12', '12' ), + '"true" for a boolean' => array( 'use_smilies', 'use_smilies', '', 'true', 'true', '1' ), + '"false" for a boolean' => array( 'use_smilies', 'use_smilies', '1', 'false', 'false', '' ), + '1 for a boolean' => array( 'use_smilies', 'use_smilies', '', 1, 'true', '1' ), + '0 for a boolean' => array( 'use_smilies', 'use_smilies', '1', 0, 'false', '' ), + '"1" for a boolean' => array( 'use_smilies', 'use_smilies', '', '1', 'true', '1' ), + '"0" for a boolean' => array( 'use_smilies', 'use_smilies', '1', '0', 'false', '' ), + 'an empty string for a string' => array( 'title', 'blogname', 'Old title', '', '""', '' ), + 'a script URI for a URI' => array( 'settings_update_test_uri', 'settings_update_test_uri', 'https://old.example', 'javascript:alert(1)', '""', '' ), + 'an ampersand in the title' => array( 'title', 'blogname', 'Old title', 'A & B', '"A & B"', 'A & B' ), + 'tags in the title' => array( 'title', 'blogname', 'Old title', 'x', '"<b>x<\/b>"', '<b>x</b>' ), + 'zero posts per page' => array( 'posts_per_page', 'posts_per_page', '10', 0, '1', '1' ), + 'a negative number of posts per page' => array( 'posts_per_page', 'posts_per_page', '10', -5, '5', '5' ), + 'all posts per page' => array( 'posts_per_page', 'posts_per_page', '10', -1, '-1', '-1' ), + 'a negative start of the week' => array( 'start_of_week', 'start_of_week', '1', -3, '3', '3' ), + 'tags in the date format' => array( 'date_format', 'date_format', 'F j, Y', 'Y', '"Y"', 'Y' ), + 'an unknown timezone' => array( 'timezone', 'timezone_string', 'Europe/Lisbon', 'Mars/Olympus', '"Europe\/Lisbon"', 'Europe/Lisbon' ), + 'a language that is not installed' => array( 'language', 'WPLANG', 'de_DE', 'xx_XX', '"de_DE"', 'de_DE' ), + 'English as a locale' => array( 'language', 'WPLANG', 'de_DE', 'en_US', '"de_DE"', 'de_DE' ), + 'English as an empty language' => array( 'language', 'WPLANG', 'de_DE', '', '""', '' ), + ); + } + + /** + * The same call twice succeeds and returns the same output. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_same_call_twice(): void { + $this->become_admin(); + $data = array( + 'title' => 'Twice', + 'posts_per_page' => 12, + ); + + $first = $this->update( $data ); + $second = $this->update( $data ); + + $this->assertNotWPError( $second, 'Writing unchanged values should not fail.' ); + $this->assertSame( $first, $second, 'The second call should return the same output.' ); + } + + /** + * A call that names several settings writes and deletes exactly those, and returns only those. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_updates_several_settings(): void { + $this->store_raw( 'use_smilies', '' ); + $this->become_admin(); + $expected = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Acme Robotics', + 'posts_per_page' => 12, + 'use_smilies' => null, + ) + ); + + $this->assertNotWPError( $result, 'The settings should be written.' ); + $this->assertSameSets( array( 'title', 'posts_per_page', 'use_smilies' ), array_keys( $result ), 'The output should hold only the settings named in the call.' ); + $this->assertSame( 'Acme Robotics', $result['title'], 'The output should show the new title.' ); + $this->assertSame( 12, $result['posts_per_page'], 'The output should show the new number of posts per page.' ); + $this->assertTrue( $result['use_smilies'], 'The deleted setting should read as its default.' ); + + $expected['blogname'] = 'Acme Robotics'; + $expected['posts_per_page'] = '12'; + unset( $expected['use_smilies'] ); + $this->assert_snapshot( $expected, $this->snapshot(), 'Only the named settings should change.' ); + } + + /** + * A `pre_option_{$option}` filter shows in the output, while the value is still written. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_pre_option_filter_shows_in_output(): void { + $this->become_admin(); + add_filter( + 'pre_option_blogname', + static function () { + return 'Filtered title'; + } + ); + $expected = $this->snapshot(); + + $result = $this->update( array( 'title' => 'Written title' ) ); + + $this->assertSame( array( 'title' => 'Filtered title' ), $result, 'The output should show the filtered value.' ); + $expected['blogname'] = 'Written title'; + $this->assert_snapshot( $expected, $this->snapshot(), 'The value should still be written.' ); + } + + /** + * A `pre_option_{$option}` filter counts as the stored value when a null value is checked. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_pre_option_filter_counts_for_the_stored_value_check(): void { + $this->store_raw( 'posts_per_page', '12' ); + $this->become_admin(); + add_filter( + 'pre_option_posts_per_page', + static function () { + return 'ten'; + } + ); + $before = $this->snapshot(); + + $result = $this->update( array( 'posts_per_page' => null ) ); + + $this->assert_error( $result, 'settings_invalid_stored_value', 500, sprintf( self::INVALID_STORED_VALUE_MESSAGE, 'posts_per_page' ) ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be deleted.' ); + } + + /** + * The sanitize callback of a setting runs once, while the value is saved. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_sanitize_callback_runs_inside_the_save(): void { + $option = 'settings_update_test_sanitized'; + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_abilities' => true, + 'sanitize_callback' => array( self::class, 'sanitize_test_value' ), + ) + ); + $this->register_ability(); + $this->store_raw( $option, 'seed' ); + $this->become_admin(); + self::$sanitize_calls = 0; + + $result = $this->update( array( $option => 'abc' ) ); + $after = $this->snapshot(); + + $this->assertSame( array( $option => 'ABC' ), $result, 'The output should show the sanitized value.' ); + $this->assertSame( 1, self::$sanitize_calls, 'The sanitize callback should run once.' ); + $this->assertSame( 'ABC', $after[ $option ], 'The sanitized value should be stored.' ); + } + + /** + * A null value is refused when the stored value does not match the schema of the setting, + * and nothing is deleted. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_invalid_stored_values + * + * @param string $name The exposed setting name. + * @param string $option The option name. + * @param mixed $stored The raw value stored before the call, or null for no row. + */ + public function test_null_refuses_an_invalid_stored_value( string $name, string $option, $stored ): void { + $this->store_raw( $option, $stored ); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( array( $name => null ) ); + + $this->assert_error( $result, 'settings_invalid_stored_value', 500, sprintf( self::INVALID_STORED_VALUE_MESSAGE, $name ) ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be deleted.' ); + } + + /** + * Data provider. + * + * @return array Stored values that a null value cannot delete. + */ + public static function data_invalid_stored_values(): array { + return array( + 'a word for an integer' => array( 'posts_per_page', 'posts_per_page', 'ten' ), + 'an empty string for an integer' => array( 'posts_per_page', 'posts_per_page', '' ), + 'no value for an integer with a default' => array( 'posts_per_page', 'posts_per_page', null ), + 'another word for an enum' => array( 'default_ping_status', 'default_ping_status', 'maybe' ), + 'an empty string for an enum' => array( 'default_ping_status', 'default_ping_status', '' ), + 'an empty string for an email address' => array( 'settings_update_test_email', 'settings_update_test_email_option', '' ), + 'an array for a string' => array( 'title', 'blogname', array( 'A sneaky array!' ) ), + ); + } + + /** + * A null value deletes a stored value that matches the schema of the setting, including the + * forms in which a boolean is stored. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_valid_stored_values + * + * @param string $name The exposed setting name. + * @param string $option The option name. + * @param mixed $stored The raw value stored before the call, or null for no row. + * @param string $output The expected output as JSON. + */ + public function test_null_accepts_a_valid_stored_value( string $name, string $option, $stored, string $output ): void { + $this->store_raw( $option, $stored ); + $this->become_admin(); + $expected = $this->snapshot(); + unset( $expected[ $option ] ); + + $result = $this->update( array( $name => null ) ); + + $this->assertNotWPError( $result, 'The stored value should be deleted.' ); + $this->assertSame( $output, wp_json_encode( $result ), 'The setting should read as its default, or be left out.' ); + $this->assert_snapshot( $expected, $this->snapshot(), 'Only the row of the named setting should be deleted.' ); + } + + /** + * Data provider. + * + * @return array Stored values that a null value deletes, and the output as JSON. + */ + public static function data_valid_stored_values(): array { + return array( + 'a numeric string for an integer' => array( 'posts_per_page', 'posts_per_page', '12', '{"posts_per_page":10}' ), + 'an empty string for a string' => array( 'title', 'blogname', '', '[]' ), + 'an empty string for a boolean' => array( 'use_smilies', 'use_smilies', '', '{"use_smilies":true}' ), + '"0" for a boolean' => array( 'use_smilies', 'use_smilies', '0', '{"use_smilies":true}' ), + '"1" for a boolean' => array( 'use_smilies', 'use_smilies', '1', '{"use_smilies":true}' ), + 'no value for a boolean' => array( 'use_smilies', 'use_smilies', null, '{"use_smilies":true}' ), + ); + } + + /** + * Repeating a null value fails for an integer setting, which has no stored value left. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_repeated_null_fails_for_an_integer(): void { + $this->store_raw( 'posts_per_page', '12' ); + $this->become_admin(); + + $first = $this->update( array( 'posts_per_page' => null ) ); + $second = $this->update( array( 'posts_per_page' => null ) ); + + $this->assertSame( array( 'posts_per_page' => 10 ), $first, 'The first call should delete the stored value.' ); + $this->assert_error( $second, 'settings_invalid_stored_value', 500, sprintf( self::INVALID_STORED_VALUE_MESSAGE, 'posts_per_page' ) ); + } + + /** + * The stored-value error names the first failing setting in registration order, whatever the + * order of the input. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_stored_value_error_names_the_first_in_registration_order(): void { + $this->store_raw( 'start_of_week', 'ten' ); + $this->store_raw( 'posts_per_page', 'ten' ); + $this->become_admin(); + + $result = $this->update( + array( + 'posts_per_page' => null, + 'start_of_week' => null, + ) + ); + + $this->assert_error( $result, 'settings_invalid_stored_value', 500, sprintf( self::INVALID_STORED_VALUE_MESSAGE, 'start_of_week' ) ); + } + + /** + * Nothing is written or deleted when a later setting of the call fails its stored-value check. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_calls_failing_late + * + * @param array $data The settings to update. + */ + public function test_nothing_is_written_when_a_later_check_fails( array $data ): void { + $this->store_raw( 'use_smilies', '1' ); + $this->store_raw( 'posts_per_page', 'ten' ); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( $data ); + + $this->assert_error_code( $result, 'settings_invalid_stored_value' ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written or deleted.' ); + } + + /** + * Data provider. + * + * @return array}> Calls whose last setting has an invalid stored value. + */ + public static function data_calls_failing_late(): array { + return array( + 'a value first' => array( + array( + 'title' => 'Changed title', + 'posts_per_page' => null, + ), + ), + 'a deletion first' => array( + array( + 'use_smilies' => null, + 'posts_per_page' => null, + ), + ), + ); + } + + /** + * The capability check comes before the privacy policy page check. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_capability_check_comes_before_privacy_check(): void { + wp_set_current_user( self::$user_ids['subscriber'] ); + add_filter( 'wp_ability_permission_result', '__return_true' ); + + $result = $this->update( array( 'page_for_privacy_policy' => 5 ) ); + + $this->assert_error( $result, 'settings_cannot_update', 403, self::CANNOT_UPDATE_MESSAGE ); + } + + /** + * The privacy policy page check comes before the stored-value check. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_privacy_check_comes_before_stored_value_check(): void { + $this->store_raw( 'posts_per_page', 'ten' ); + $this->become_admin_for( 'page_for_privacy_policy' ); + $this->deny_privacy_capability(); + + $result = $this->update( + array( + 'posts_per_page' => null, + 'page_for_privacy_policy' => 5, + ) + ); + + $this->assert_error( $result, 'settings_cannot_manage_privacy_options', 403, self::CANNOT_MANAGE_PRIVACY_MESSAGE ); + } + + /** + * Invalid input is refused before the permission check, and nothing is written. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_roles_without_manage_options + * + * @param string|null $role The role of the user, or null when logged out. + */ + public function test_invalid_input_is_refused_before_the_permission_check( ?string $role ): void { + wp_set_current_user( null === $role ? 0 : self::$user_ids[ $role ] ); + $before = $this->snapshot(); + + $result = $this->update( array( 'posts_per_page' => 'abc' ) ); + + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * An administrator of another site of the network, who is not a member of the current site, + * cannot update its settings. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @group ms-required + */ + public function test_administrator_of_another_site_cannot_update(): void { + $user_id = self::factory()->user->create(); + remove_user_from_blog( $user_id, get_current_blog_id() ); + add_user_to_blog( self::factory()->blog->create(), $user_id, 'administrator' ); + wp_set_current_user( $user_id ); + $before = $this->snapshot(); + + $result = $this->update( array( 'title' => 'Changed title' ) ); + + $this->assert_error_code( $result, 'ability_invalid_permissions' ); + $this->assert_snapshot( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * A network administrator who is not a member of the current site can update its settings, + * including the privacy policy page. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @group ms-required + */ + public function test_network_administrator_without_membership_can_update(): void { + $user_id = self::factory()->user->create(); + remove_user_from_blog( $user_id, get_current_blog_id() ); + grant_super_admin( $user_id ); + wp_set_current_user( $user_id ); + $expected = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Network title', + 'page_for_privacy_policy' => 8, + ) + ); + + $this->assertNotWPError( $result, 'The settings should be written.' ); + $this->assertSameSets( array( 'title', 'page_for_privacy_policy' ), array_keys( $result ), 'The output should hold only the settings named in the call.' ); + $this->assertSame( 'Network title', $result['title'], 'The output should show the saved title.' ); + $this->assertSame( 8, $result['page_for_privacy_policy'], 'The output should show the saved privacy policy page.' ); + $expected['blogname'] = 'Network title'; + $expected['wp_page_for_privacy_policy'] = '8'; + $this->assert_snapshot( $expected, $this->snapshot(), 'Both settings should be saved.' ); + } + + /** + * A setting that is unregistered after the abilities register is neither written nor deleted, + * and is left out of the output, while the other settings of the call are written. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_unregistered_setting_calls + * + * @param array $data The settings to update. + * @param mixed $stored The raw value stored for the unregistered setting. + * @param string $output The expected output as JSON. + * @param array $written The raw values expected to be written, keyed by option name. + */ + public function test_unregistered_setting_is_dropped( array $data, $stored, string $output, array $written ): void { + $option = 'settings_update_test_unregistered'; + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_abilities' => true, + ) + ); + $this->register_ability(); + $this->store_raw( $option, $stored ); + unregister_setting( 'general', $option ); + $this->become_admin(); + $expected = $this->snapshot(); + $row = $this->raw_row( $option ); + + $result = $this->update( $data ); + $after = $this->snapshot(); + $after_row = $this->raw_row( $option ); + + $this->assertNotWPError( $result, 'The call should succeed.' ); + $this->assertSame( $output, wp_json_encode( $result ), 'The output should hold only the settings that are still registered.' ); + $this->assertSame( $row, $after_row, 'The row of the unregistered setting should not change.' ); + $this->assert_snapshot( array_merge( $expected, $written ), $after, 'Only the settings that are still registered should be written.' ); + } + + /** + * Data provider. + * + * @return array, 1: mixed, 2: string, 3: array}> Calls naming an unregistered setting. + */ + public static function data_unregistered_setting_calls(): array { + return array( + 'a value' => array( + array( 'settings_update_test_unregistered' => 'abc' ), + 'seed', + '[]', + array(), + ), + 'null with a stored value its schema rejects' => array( + array( 'settings_update_test_unregistered' => null ), + array( 'not', 'a', 'string' ), + '[]', + array(), + ), + 'a value with another setting' => array( + array( + 'settings_update_test_unregistered' => 'abc', + 'title' => 'Acme Robotics', + ), + 'seed', + '{"title":"Acme Robotics"}', + array( 'blogname' => 'Acme Robotics' ), + ), + ); + } + + /** + * A setting whose value read after the call does not match its schema is left out of the output, + * while the other settings of the call are present. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_output_leaves_out_a_value_its_schema_rejects(): void { + $this->become_admin(); + add_filter( + 'option_posts_per_page', + static function () { + return 'ten'; + } + ); + $expected = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Acme Robotics', + 'posts_per_page' => 12, + ) + ); + + $this->assertSame( array( 'title' => 'Acme Robotics' ), $result, 'The rejected value should be left out of the output.' ); + $expected['blogname'] = 'Acme Robotics'; + $expected['posts_per_page'] = '12'; + $this->assert_snapshot( $expected, $this->snapshot(), 'Both settings should still be written.' ); + } +} diff --git a/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php b/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php index 311672a5238db..b6d188af76ca1 100644 --- a/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php +++ b/tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php @@ -3,7 +3,7 @@ declare( strict_types=1 ); /** - * Tests for running the core/settings-get ability through the REST API. + * Tests for running the settings abilities through the REST API. * * @covers WP_Abilities_Settings * @@ -38,7 +38,14 @@ class Tests_REST_API_WpRestAbilitiesSettingsController extends WP_UnitTestCase { * * @var string */ - const RUN_ROUTE = '/wp-abilities/v1/abilities/core/settings-get/run'; + const GET_RUN_ROUTE = '/wp-abilities/v1/abilities/core/settings-get/run'; + + /** + * The run route for the core/settings-update ability. + * + * @var string + */ + const UPDATE_RUN_ROUTE = '/wp-abilities/v1/abilities/core/settings-update/run'; /** * Sets up users and registers the core abilities. @@ -129,11 +136,31 @@ public function tear_down(): void { * @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 = new WP_REST_Request( 'GET', self::GET_RUN_ROUTE ); $request->set_query_params( array( 'input' => $input ) ); return $request; } + /** + * Builds a run request for core/settings-update with the given ability input. + * + * A POST request carries the input in a JSON body, any other method in the query string. + * + * @param string $method The HTTP method. + * @param array $input The ability input. + * @return WP_REST_Request The request. + */ + private function update_request( string $method, array $input ): WP_REST_Request { + $request = new WP_REST_Request( $method, self::UPDATE_RUN_ROUTE ); + if ( 'POST' === $method ) { + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( wp_json_encode( array( 'input' => $input ) ) ); + } else { + $request->set_query_params( array( 'input' => $input ) ); + } + return $request; + } + /** * @ticket 64605 */ @@ -209,7 +236,7 @@ public function test_no_matching_setting_is_encoded_as_an_empty_object(): void { ), ); - $this->server->serve_request( self::RUN_ROUTE ); + $this->server->serve_request( self::GET_RUN_ROUTE ); $this->assertSame( 200, $this->server->status, 'Filters that match no setting should be accepted.' ); $this->assertSame( '{}', $this->server->sent_body, 'The empty result should be served as an empty object.' ); @@ -229,7 +256,7 @@ public function test_unknown_group_receives_400(): void { * @ticket 64605 */ public function test_wrong_http_method_returns_405(): void { - $request = new WP_REST_Request( 'POST', self::RUN_ROUTE ); + $request = new WP_REST_Request( 'POST', self::GET_RUN_ROUTE ); $request->set_header( 'Content-Type', 'application/json' ); $request->set_body( wp_json_encode( array( 'input' => array( 'group' => 'reading' ) ) ) ); @@ -238,4 +265,144 @@ public function test_wrong_http_method_returns_405(): void { $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.' ); } + + /** + * Users who cannot manage options cannot update settings, and nothing is written. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_update_refused_users + * + * @param string $user The user: 'logged out' or 'subscriber'. + * @param int $status The expected status. + */ + public function test_update_refused_for_users_without_manage_options( string $user, int $status ): void { + wp_set_current_user( 'subscriber' === $user ? self::$subscriber_id : 0 ); + $before = get_option( 'blogname' ); + + $response = $this->server->dispatch( $this->update_request( 'POST', array( 'data' => array( 'title' => 'Changed title' ) ) ) ); + + $this->assertSame( $status, $response->get_status(), 'The update should be refused with the expected status.' ); + $this->assertSame( 'rest_ability_cannot_execute', $response->get_data()['code'], 'The error should identify the refused permission.' ); + $this->assertSame( $before, get_option( 'blogname' ), 'The site title should not change.' ); + } + + /** + * Data provider. + * + * @return array Users and the expected status. + */ + public static function data_update_refused_users(): array { + return array( + 'logged out' => array( 'logged out', 401 ), + 'subscriber' => array( 'subscriber', 403 ), + ); + } + + /** + * The update runs only through POST. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_update_wrong_methods + * + * @param string $method The HTTP method. + */ + public function test_update_wrong_http_method_returns_405( string $method ): void { + $before = get_option( 'blogname' ); + + $response = $this->server->dispatch( $this->update_request( $method, array( 'data' => array( 'title' => 'Changed title' ) ) ) ); + + $this->assertSame( 405, $response->get_status(), 'The update should be rejected for this method.' ); + $this->assertSame( 'rest_ability_invalid_method', $response->get_data()['code'], 'The error should identify the invalid HTTP method.' ); + $this->assertSame( $before, get_option( 'blogname' ), 'The site title should not change.' ); + } + + /** + * Data provider. + * + * @return array HTTP methods other than POST. + */ + public static function data_update_wrong_methods(): array { + return array( + 'GET' => array( 'GET' ), + 'DELETE' => array( 'DELETE' ), + ); + } + + /** + * Invalid update input is refused, and nothing is written. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_update_invalid_input_receives_400(): void { + $before = get_option( 'blogname' ); + + $response = $this->server->dispatch( + $this->update_request( + 'POST', + array( + 'data' => array( + 'title' => 'Changed title', + 'posts_per_page' => 'abc', + ), + ) + ) + ); + + $this->assertSame( 400, $response->get_status(), 'Invalid input should be refused.' ); + $this->assertSame( 'ability_invalid_input', $response->get_data()['code'], 'The error should identify the invalid input.' ); + $this->assertSame( $before, get_option( 'blogname' ), 'The site title should not change.' ); + } + + /** + * An administrator updates settings and receives the saved values. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_update_admin_receives_saved_settings(): void { + $response = $this->server->dispatch( + $this->update_request( + 'POST', + array( + 'data' => array( + 'title' => 'Updated Site', + 'posts_per_page' => '12', + ), + ) + ) + ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status(), 'An administrator should update the settings.' ); + $this->assertSameSets( array( 'title', 'posts_per_page' ), array_keys( $data ), 'Only the updated settings should be returned.' ); + $this->assertSame( 'Updated Site', $data['title'], 'The saved site title should be returned.' ); + $this->assertSame( 12, $data['posts_per_page'], 'The saved number of posts per page should be returned as an integer.' ); + $this->assertSame( 'Updated Site', get_option( 'blogname' ), 'The site title should be saved.' ); + } + + /** + * A deleted setting without a default is left out, and the empty result is sent as an object. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_update_null_without_default_returns_an_empty_object(): void { + update_option( 'blogname', 'Site to reset' ); + + $response = $this->server->dispatch( $this->update_request( 'POST', array( 'data' => array( 'title' => null ) ) ) ); + + $this->assertSame( 200, $response->get_status(), 'An administrator should delete the stored value.' ); + $this->assertSame( '{}', wp_json_encode( $response->get_data() ), 'The empty result should be sent as an empty object.' ); + $this->assertFalse( get_option( 'blogname' ), 'The stored site title should be deleted.' ); + } }