diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index 835c19e04f949..245ccbd094713 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 (`core/settings-get` and `core/settings-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 5729103846917..33d079c9aa79b 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 */ @@ -45,6 +45,29 @@ final class WP_Abilities_Settings { */ private const CATEGORY = 'site'; + /** + * Options that `core/settings-update` cannot write, whatever name exposes them. + * + * The WordPress address, the site address and the administration email address are left to + * Settings > General, which confirms a new administration email address before it is used. + * + * @since 7.3.0 + * @var string[] + */ + private const READ_ONLY_OPTIONS = array( 'siteurl', 'home', 'admin_email' ); + + /** + * Options that `core/settings-update` cannot reset with a null value, whatever name exposes them. + * + * They have no registered default, so a reset would delete them, and Core needs a value: + * without one, dates and times show as empty strings, and new posts get no category. They + * can still be updated with a value. + * + * @since 7.3.0 + * @var string[] + */ + private const NON_RESETTABLE_OPTIONS = array( 'date_format', 'time_format', 'default_category' ); + /** * Settings exposed through the Abilities API, computed once at registration. * @@ -53,6 +76,14 @@ final class WP_Abilities_Settings { */ private $exposed_settings = array(); + /** + * Exposed settings that `core/settings-update` can write, computed once at registration. + * + * @since 7.3.0 + * @var array}> + */ + private $writable_settings = array(); + /** * Registers all settings abilities. * @@ -60,6 +91,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 +99,21 @@ public function register(): void { return; } + /* + * Intentional: every exposed setting can be updated, including the settings exposed + * before `core/settings-update` existed, except the options in READ_ONLY_OPTIONS and the + * settings whose schema sets `readonly` to true. Naming one of those is refused like any + * unknown name. Only `readonly` at the top level of the schema counts: a read-only + * property inside an object setting is written with the rest of the object. + */ + $this->writable_settings = array_filter( + $this->exposed_settings, + static fn( array $setting ): bool => empty( $setting['schema']['readonly'] ) + && ! in_array( strtolower( $setting['option'] ), self::READ_ONLY_OPTIONS, true ) + ); + $this->register_settings_get(); + $this->register_settings_update(); } /** @@ -85,7 +131,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( $this->exposed_settings, __( 'A map of setting name to its current value.' ) ), 'execute_callback' => function ( $input = array() ): array { return $this->execute_settings_get( $input ); }, @@ -102,6 +148,50 @@ private function register_settings_get(): void { ); } + /** + * Registers the `core/settings-update` ability. + * + * Registers nothing when no exposed setting is writable. + * + * The ability is marked destructive because a null value deletes the stored value of a + * setting without a default, see execute_settings_update(). It is not marked idempotent, + * although repeating a call has no further effect: an ability that is both destructive and + * idempotent runs with the DELETE method, and this ability updates settings. + * + * @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 resets a setting to its default, or deletes its stored value when it has no default, except for the date format, the time format and the default category, which cannot be reset. Read-only settings, such as the WordPress address and the administration email address, cannot be updated. Requires an authenticated user who can manage options, and who can also manage privacy options to set the privacy policy page.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_settings_update_input_schema(), + 'output_schema' => $this->get_settings_output_schema( $this->writable_settings, __( 'A map of setting name to its value after the update.' ) ), + 'execute_callback' => function ( $input ) { + return $this->execute_settings_update( $input ); + }, + 'permission_callback' => function ( $input = array() ): bool { + return $this->check_settings_update_permission( $input ); + }, + 'required_capabilities' => array( 'manage_options' ), + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => true, + 'idempotent' => false, + ), + 'public' => true, + ), + ) + ); + } + /** * Executes the `core/settings-get` ability. * @@ -115,7 +205,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,6 +214,265 @@ private function execute_settings_get( $input = array() ): array { continue; } + $requested[ $exposed_name ] = $setting; + } + + return $this->get_setting_values( $requested ); + } + + /** + * Checks the permission of the current user to update the settings named in a + * `core/settings-update` call. + * + * The `manage_options` capability is checked before, as a required capability of the ability. + * Setting or resetting the privacy policy page also requires the `manage_privacy_options` + * capability. + * + * 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. + * + * @since 7.3.0 + * + * @param mixed $input Optional. The ability input, which a direct call to + * WP_Ability::check_permissions() may pass unprepared. Default empty array. + * @return bool Whether the current user can update the named settings. + */ + private function check_settings_update_permission( $input = array() ): bool { + $input = rest_sanitize_object( $input ); + $named = array_intersect_key( $this->writable_settings, rest_sanitize_object( $input['data'] ?? array() ) ); + + return ! in_array( 'wp_page_for_privacy_policy', array_map( 'strtolower', array_column( $named, 'option' ) ), true ) + || current_user_can( 'manage_privacy_options' ); + } + + /** + * Executes the `core/settings-update` ability. + * + * The checks of the ability run before the first write, so a call they refuse changes nothing. + * A callback that runs while a value is saved, such as the sanitize callback of a setting, can + * still stop the call after the settings before it are saved. The output holds only the + * settings named in the call, read the same way as for `core/settings-get`. + * + * @since 7.3.0 + * + * @param mixed $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( $input ) { + $input = rest_sanitize_object( $input ); + $data = rest_sanitize_object( $input['data'] ?? array() ); + $named = array_intersect_key( $this->writable_settings, $data ); + + /* + * Intentionally strict: every value is checked before the first write, so a call refused + * here changes nothing. A value is refused when the setting cannot use it, instead of being + * saved as sent or silently replaced with the stored value. A null value is refused while + * the setting has a stored value that `core/settings-get` leaves out, because the value does + * not match the setting's schema: the caller cannot see what would be replaced or deleted. + * Unusable values are reported first. + * + * Intentional: a null value stores the default of a setting that has one, and deletes the + * stored value of a setting without one. A registered default only applies in requests that + * register the setting, and Core registers its own settings only in REST and abilities + * requests, so other requests would read a deleted value as false. A setting without a + * default then has no value, and is left out of the output and of `core/settings-get`, + * until a value is written again. + */ + $values = array(); + $invalid_params = array(); + $invalid_stored = array(); + foreach ( $named as $exposed_name => $setting ) { + $value = $data[ $exposed_name ] ?? $setting['default']; + + /* + * English is stored as an empty string. `en_US` is what the language reads as when + * none is stored, and sanitize_option() would replace it with the stored value. + */ + if ( 'wplang' === strtolower( $setting['option'] ) && 'en_US' === $value ) { + $value = ''; + } + + if ( null !== $data[ $exposed_name ] ) { + $message = $this->get_invalid_value_message( $setting['option'], $value, "data[{$exposed_name}]" ); + if ( null !== $message ) { + $invalid_params[ "data[{$exposed_name}]" ] = $message; + } + } elseif ( + // The stored value reads as null when there is none, and then there is nothing to replace. + null !== get_option( $setting['option'], null ) + && array() === $this->get_setting_values( array( $exposed_name => $setting ) ) + ) { + $invalid_stored[ "data[{$exposed_name}]" ] = sprintf( + /* translators: %s: Property name. */ + __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), + $exposed_name + ); + } + + $values[ $exposed_name ] = $value; + } + + if ( ! empty( $invalid_params ) ) { + return $this->get_refused_settings_error( + 'settings_invalid_value', + $invalid_params, + 400, + /* translators: %s: List of invalid parameters. */ + __( 'Invalid parameter(s): %s' ) + ); + } + + if ( ! empty( $invalid_stored ) ) { + return $this->get_refused_settings_error( + 'settings_invalid_stored_value', + $invalid_stored, + 500, + /* translators: %s: List of parameters. */ + __( 'These parameters have an invalid stored value, and cannot be updated to null: %s' ) + ); + } + + foreach ( $values as $exposed_name => $value ) { + $option = $named[ $exposed_name ]['option']; + if ( null === $value ) { + delete_option( $option ); + continue; + } + + update_option( $option, $value ); + + /* + * update_option() stores nothing when no value is stored and the sanitized value matches + * the default get_option() reads, so store that default. The stored value reads as null + * when there is none, while a stored false reads as false. + */ + if ( null === get_option( $option, null ) ) { + add_option( $option, get_option( $option ) ); + } + } + + return $this->get_setting_values( $named ); + } + + /** + * Builds the error for the settings a `core/settings-update` call refuses. + * + * The message is the message of the refused setting, or names every refused setting when + * there are several. The error data maps the input path of each refused setting to its + * message, so callers can tell which settings failed. + * + * @since 7.3.0 + * + * @param string $code The error code. + * @param array $params Messages keyed by the input path of each refused setting. + * @param int $status The HTTP status code. + * @param string $multiple_message The message when several settings are refused, with + * a placeholder for the list of their input paths. + * @return WP_Error The error. + */ + private function get_refused_settings_error( string $code, array $params, int $status, string $multiple_message ): WP_Error { + if ( 1 === count( $params ) ) { + $message = reset( $params ); + } else { + $message = sprintf( $multiple_message, implode( ', ', array_keys( $params ) ) ); + } + + return new WP_Error( + $code, + $message, + array( + 'status' => $status, + 'params' => $params, + ) + ); + } + + /** + * Checks a value that matches its schema against what the option can use. + * + * The rules belong to the option, whatever name exposes it: a timezone and a language must be + * empty or known to the site, a default post format must be `0`, empty or a post format, a page + * setting must be 0 or the ID of a page that is not in the trash or an auto-draft, and the + * default category must be the ID of a category. The option name is compared in lower case. + * + * @since 7.3.0 + * + * @param string $option The option name. + * @param mixed $value The value to save, which is not null. + * @param string $param The input path of the setting, used in the message. + * @return string|null The error message when the option cannot use the value, null otherwise. + */ + private function get_invalid_value_message( string $option, $value, string $param ): ?string { + switch ( strtolower( $option ) ) { + case 'timezone_string': + if ( '' !== $value && ! in_array( $value, timezone_identifiers_list( DateTimeZone::ALL_WITH_BC ), true ) ) { + return __( 'The timezone you have entered is not valid. Please select a valid timezone.' ); + } + break; + + case 'wplang': + $languages = get_available_languages(); + if ( '' !== $value && ! in_array( $value, $languages, true ) ) { + /* translators: 1: Parameter, 2: List of valid values. */ + return wp_sprintf( __( '%1$s is not one of %2$l.' ), $param, array_merge( array( 'en_US' ), $languages ) ); + } + break; + + case 'default_post_format': + // An empty value is the standard format, as `0` is. + if ( '0' !== $value && '' !== $value && ! in_array( $value, get_post_format_slugs(), true ) ) { + return __( 'Invalid post format.' ); + } + break; + + case 'page_on_front': + case 'page_for_posts': + case 'wp_page_for_privacy_policy': + /* + * The Settings screens never offer a page that is in the trash or an auto-draft. + * + * Known gap: a page in any other status is accepted, such as a draft, pending, private + * or scheduled page, which logged-out visitors cannot see. Settings > Reading offers only + * published pages for the front page and the page for posts, but only in its form: the + * Settings API has no rule for the status of these pages yet. + */ + if ( + 0 !== $value + && ( + ! is_int( $value ) + || 'page' !== get_post_type( $value ) + || in_array( get_post_status( $value ), array( 'trash', 'auto-draft' ), true ) + ) + ) { + return __( 'Invalid post ID.' ); + } + break; + + case 'default_category': + // A negative ID would be looked up as its absolute value. + if ( ! is_int( $value ) || $value <= 0 || ! term_exists( $value, 'category' ) ) { + return __( 'Invalid term ID.' ); + } + break; + } + + return null; + } + + /** + * 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 @@ -196,20 +545,127 @@ private function get_settings_get_input_schema( array $groups, array $field_name } /** - * Builds the output schema for the `core/settings-get` ability. + * 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 resets a setting to its default, or deletes its stored value when it has no default. The date format, the time format and the default category cannot be reset.' ), + 'properties' => array_map( array( $this, 'get_update_value_schema' ), $this->writable_settings ), + 'additionalProperties' => false, + 'minProperties' => 1, + ), + ), + 'required' => array( 'data' ), + 'additionalProperties' => false, + ); + } + + /** + * Returns the input schema of a writable setting. + * + * Removes the default, which is for reading a setting: a client that fills in defaults would + * otherwise write it on every call. Allows null, unless the option is one of + * NON_RESETTABLE_OPTIONS, see nullable_schema(). + * + * @since 7.3.0 + * + * @param array{option: string, group: string, default: mixed, schema: array} $setting The writable setting. + * @return array The input JSON Schema of the setting. + * + * @phpstan-param array{ + * option: string, + * schema: array{ + * type: non-empty-string, + * enum?: mixed[], + * default?: mixed, + * ... + * }, + * ... + * } $setting + */ + private function get_update_value_schema( array $setting ): array { + $schema = $setting['schema']; + unset( $schema['default'] ); + + return in_array( strtolower( $setting['option'] ), self::NON_RESETTABLE_OPTIONS, true ) ? $schema : $this->nullable_schema( $schema ); + } + + /** + * Allows null in a setting's value schema. + * + * Adds `null` to the type, and to the allowed values when the schema lists them. The type is + * a single type: get_exposed_settings() leaves out a setting whose type is a list. A schema + * with a top-level `anyOf` or `oneOf` is kept as is and listed with a null schema in an + * `anyOf` instead, because a null type would still be refused by its subschemas. Nested + * schemas are not changed. + * + * @since 7.3.0 + * + * @param array $schema The value JSON Schema, without a default. + * @return array The value JSON Schema that also accepts null. + * + * @phpstan-param array{ + * type: non-empty-string, + * enum?: mixed[], + * ... + * } $schema + * @phpstan-return array{ + * type: array{ non-empty-string, 'null' }, + * enum?: mixed[], + * ... + * }|array{ + * anyOf: array{ array, array{ type: 'null' } }, + * } + */ + private function nullable_schema( array $schema ): array { + if ( isset( $schema['anyOf'] ) || isset( $schema['oneOf'] ) ) { + return array( + 'anyOf' => array( + $schema, + array( 'type' => 'null' ), + ), + ); + } + + $schema['type'] = array( $schema['type'], 'null' ); + if ( isset( $schema['enum'] ) ) { + $schema['enum'][] = null; + } + + return $schema; + } + + /** + * Builds the output schema of a settings ability, from the settings it can return. * - * 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 Renamed from get_settings_get_output_schema(). Added the `$settings` and + * `$description` parameters. * + * @param array}> $settings Exposed settings the ability can return, keyed by exposed name. + * @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( array $settings, string $description ): array { return array( 'type' => 'object', - 'description' => __( 'A map of setting name to its current value.' ), - 'properties' => wp_list_pluck( $this->exposed_settings, 'schema' ), + 'description' => $description, + 'properties' => wp_list_pluck( $settings, 'schema' ), 'additionalProperties' => false, ); } @@ -266,7 +722,11 @@ private function get_exposed_settings(): array { * overrides the registered default. */ $settings[ $exposed_name ] = array( - 'option' => $option_name, + /* + * The options API trims the name and the database ignores its case, so the rules + * that name an option compare the trimmed name in lower case. + */ + 'option' => trim( $option_name ), 'group' => $args['group'] ?? '', 'default' => array_key_exists( 'default', $schema ) ? $schema['default'] : ( $args['default'] ?? null ), 'schema' => $schema, diff --git a/src/wp-includes/option.php b/src/wp-includes/option.php index e53aedeb47ba7..247e44da39121 100644 --- a/src/wp-includes/option.php +++ b/src/wp-includes/option.php @@ -3039,6 +3039,8 @@ 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, + * unless their schema sets 'readonly' to true. * * @global array $new_allowed_options * @global array $wp_registered_settings @@ -3061,10 +3063,17 @@ 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. + * The WordPress address, the site address and the administration + * email address cannot be updated, and the date format, the time + * format and the default category cannot be reset with a null value. * 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. Only 'readonly' at the top level of the schema + * counts, not inside the properties of an object setting. * 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..7fa735c103986 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/testcase-settings-ability.php @@ -0,0 +1,177 @@ +user->create( array( 'role' => 'administrator' ) ); + } + + /** + * Cleans up registered abilities, categories and settings after the class. + * + * @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() ); + } + + global $wp_registered_settings, $new_allowed_options; + $wp_registered_settings = self::$registered_settings_backup; + $new_allowed_options = self::$allowed_options_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. + * + * The settings need no cleanup: the registered settings and the allowed options are restored + * after the class. + * + * @since 7.3.0 + */ + protected static function register_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. + * + * @since 7.3.0 + */ + 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(); + array_pop( $wp_current_filter ); + } + + /** + * Logs in as an administrator so abilities gated behind `manage_options` can run. + * + * @since 7.3.0 + */ + protected function become_admin(): void { + wp_set_current_user( self::$admin_id ); + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsGetAbility.php index 016bca1b7a756..f66fe6584a5ef 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 { +class Tests_Abilities_API_WpRegisterCoreSettingsGetAbility extends WP_Abilities_Settings_UnitTestCase { /** - * Backup of the `$wp_registered_settings` global, restored after the class. + * Registers a non-core setting flagged for the Abilities API before the abilities register. * - * @var array|null + * @since 7.3.0 */ - private static $registered_settings_backup; - - /** - * 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()). - * - * @since 7.2.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,6 @@ 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. - * - * @since 7.2.0 - */ - public static function wpTearDownAfterClass(): void { - foreach ( wp_get_abilities() as $ability ) { - wp_unregister_ability( $ability->get_name() ); - } - foreach ( wp_get_ability_categories() as $ability_category ) { - wp_unregister_ability_category( $ability_category->get_slug() ); - } - - unregister_setting( 'general', 'core_settings_get_ability_test_option' ); - - global $wp_registered_settings; - $wp_registered_settings = self::$registered_settings_backup; - } - - /** - * Registers the core/settings-get ability again inside a faked init action. - * - * The class setup has already registered it through wp_register_core_abilities(), so - * the existing copy is unregistered first. - */ - private function register_ability(): void { - if ( wp_has_ability( 'core/settings-get' ) ) { - wp_unregister_ability( 'core/settings-get' ); - } - - global $wp_current_filter; - $wp_current_filter[] = 'wp_abilities_api_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it. - ( new WP_Abilities_Settings() )->register(); - } - - /** - * Logs in as an administrator so abilities gated behind `manage_options` can run. - */ - private function become_admin(): void { - wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); } /** @@ -144,8 +64,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 +71,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 +87,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 +163,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 +196,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 +368,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 +418,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 +474,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.' ); } @@ -677,16 +550,11 @@ public function test_core_settings_get_matches_the_settings_endpoint_for_a_schem ) ); - try { - $this->register_ability(); - $this->become_admin(); + $this->register_ability(); + $this->become_admin(); - $ability_result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $option ) ) ); - $rest_result = rest_get_server()->dispatch( new WP_REST_Request( 'GET', '/wp/v2/settings' ) )->get_data(); - } finally { - unregister_setting( 'general', $option ); - $this->register_ability(); - } + $ability_result = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( $option ) ) ); + $rest_result = rest_get_server()->dispatch( new WP_REST_Request( 'GET', '/wp/v2/settings' ) )->get_data(); $this->assertSame( 'from-rest-schema', $rest_result[ $option ] ?? null, 'The settings endpoint should read the REST API schema default.' ); $this->assertSame( $rest_result[ $option ] ?? null, $ability_result[ $option ] ?? null, 'The ability should read the same default as the settings endpoint.' ); @@ -710,17 +578,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..05cbd396deae0 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php @@ -0,0 +1,2176 @@ + + */ + const STORED_DEFAULTS = array( + 'WPLANG' => '', + 'use_smilies' => '1', + 'posts_per_page' => '10', + ); + + /** + * User IDs keyed by role. + * + * @var array + */ + private static $user_ids = array(); + + /** + * IDs of a page, a post, a category and a tag, keyed by kind. + * + * @var array + */ + private static $fixture_ids = array(); + + /** + * Creates a subscriber and an editor, who cannot manage options, and the content the ID settings point to. + * + * @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', 'editor' ) as $role ) { + self::$user_ids[ $role ] = $factory->user->create( array( 'role' => $role ) ); + } + + self::$fixture_ids = array( + 'page' => $factory->post->create( array( 'post_type' => 'page' ) ), + 'post' => $factory->post->create(), + 'category' => $factory->category->create(), + 'tag' => $factory->tag->create(), + ); + } + + /** + * 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 ), + ), + ) + ); + register_setting( + 'general', + 'settings_update_test_boolean', + array( + 'type' => 'boolean', + 'show_in_abilities' => true, + ) + ); + } + + /** + * 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 + ); + + return array_column( $rows, 'option_value', 'option_name' ); + } + + /** + * 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 the error for a value a setting cannot use, which names the setting. + * + * @param mixed $result The result of the ability. + * @param string $name The exposed setting name. + */ + private function assert_invalid_value_error( $result, string $name ): void { + $this->assert_refused_setting_error( $result, 'settings_invalid_value', 400, $name ); + } + + /** + * Asserts that a result is an error that refuses one setting, and names it. + * + * @param mixed $result The result of the ability. + * @param string $code The expected error code. + * @param int $status The expected status. + * @param string $name The exposed setting name. + */ + private function assert_refused_setting_error( $result, string $code, int $status, string $name ): void { + $this->assert_error_code( $result, $code ); + $this->assertNotSame( '', $result->get_error_message(), "The error for {$name} should have a message." ); + $this->assertSame( + array( + 'status' => $status, + 'params' => array( "data[{$name}]" => $result->get_error_message() ), + ), + $result->get_error_data(), + "The error data should map {$name} to the message." + ); + } + + /** + * 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 destructive write that is not idempotent, 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->assertTrue( $annotations['destructive'], 'The ability should be marked destructive, since a null value deletes the stored value of a setting without a default.' ); + $this->assertFalse( $annotations['idempotent'], 'The ability should not be marked idempotent, since a destructive and idempotent ability runs with the DELETE method.' ); + $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 ability should require the manage_options capability.' ); + } + + /** + * 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'] ) ), self::READ_ONLY_NAMES ), + 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.' ); + } + + /** + * A setting whose schema lists its allowed schemas in a top-level `anyOf` or `oneOf` accepts + * a value of one of them or null, and refuses any other value. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_combining_keywords + * + * @param string $keyword The keyword that lists the allowed schemas. + */ + public function test_setting_with_allowed_schemas_accepts_null( string $keyword ): void { + $option = 'settings_update_test_allowed_schemas'; + $schema = array( + $keyword => array( + array( + 'type' => 'string', + 'enum' => array( 'a', 'b' ), + ), + array( + 'type' => 'string', + 'pattern' => '^x', + ), + ), + ); + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_abilities' => array( 'schema' => $schema ), + ) + ); + $this->register_ability(); + $this->become_admin(); + + $property = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties'][ $option ]; + $value = $this->update( array( $option => 'a' ) ); + $stored = $this->snapshot()[ $option ] ?? null; + $other = $this->update( array( $option => 'c' ) ); + $reset = $this->update( array( $option => null ) ); + + $this->assertSame( + array( + 'anyOf' => array( + array( 'type' => 'string' ) + $schema, + array( 'type' => 'null' ), + ), + ), + $property, + 'The input should list the schema of the setting and a null schema.' + ); + $this->assertSame( array( $option => 'a' ), $value, 'A value of an allowed schema should be saved.' ); + $this->assertSame( 'a', $stored, 'The value should be stored.' ); + $this->assert_error_code( $other, 'ability_invalid_input' ); + $this->assertSame( array(), $reset, 'Null should delete the stored value of a setting without a default.' ); + $this->assertArrayNotHasKey( $option, $this->snapshot(), 'The stored value should be deleted.' ); + } + + /** + * Data provider. + * + * @return array Keywords that list allowed schemas. + */ + public static function data_combining_keywords(): array { + return array( + 'anyOf' => array( 'anyOf' ), + 'oneOf' => array( 'oneOf' ), + ); + } + + /** + * The default of a setting's schema is left out of the input, so a client that fills in + * defaults does not write it on every call. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_input_schema_property_drops_the_default(): void { + $option = 'settings_update_test_default'; + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_abilities' => array( + 'schema' => array( 'default' => 'Fallback' ), + ), + ) + ); + $this->register_ability(); + $ability = wp_get_ability( self::ABILITY ); + + $this->assertSame( array( 'type' => array( 'string', 'null' ) ), $ability->get_input_schema()['properties']['data']['properties'][ $option ], 'The input should not hold the default.' ); + $this->assertSame( 'Fallback', $ability->get_output_schema()['properties'][ $option ]['default'], 'The output should still describe the default.' ); + } + + /** + * The output describes the settings the ability can write, as core/settings-get describes them. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_output_schema_describes_the_writable_settings(): void { + $schema = wp_get_ability( self::ABILITY )->get_output_schema(); + $expected = array_diff_key( wp_get_ability( 'core/settings-get' )->get_output_schema()['properties'], array_flip( self::READ_ONLY_NAMES ) ); + + $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( $expected, $schema['properties'], 'The output should describe every setting but the read-only ones, 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 should not be registered when no setting is exposed.' ); + } + + /** + * 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 and the output of the update ability, but is + * still described 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->assertArrayNotHasKey( $name, wp_get_ability( self::ABILITY )->get_output_schema()['properties'], 'The read-only setting should not be 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->assertSameSetsWithIndex( $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->assertSameSetsWithIndex( $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->assertSameSetsWithIndex( $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' ), + 'editor' => array( 'editor' ), + 'logged out' => array( null ), + ); + } + + /** + * 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 string|null $kind The kind of content whose ID is the privacy policy page, or null to reset it. + */ + public function test_privacy_policy_page_refused_without_capability( ?string $kind ): void { + // On multisite, a site administrator lacks the capability even without the filter. + $this->become_admin(); + $this->deny_privacy_capability(); + $before = $this->snapshot(); + $data = array( + 'title' => 'Changed title', + 'page_for_privacy_policy' => null === $kind ? null : self::$fixture_ids[ $kind ], + ); + + $permission = wp_get_ability( self::ABILITY )->check_permissions( array( 'data' => $data ) ); + $result = $this->update( $data ); + + $this->assertFalse( $permission, 'The permission check should refuse the call.' ); + $this->assert_error_code( $result, 'ability_invalid_permissions' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Kinds of content whose ID is the privacy policy page, or null. + */ + public static function data_privacy_policy_page_values(): array { + return array( + 'a page ID' => array( 'page' ), + 'null' => array( null ), + ); + } + + /** + * The privacy policy page rule holds when the option is exposed under another name, also + * when its name is registered in another case, which the database ignores. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_privacy_policy_page_options + * + * @param string $option The name the option is registered with. + */ + public function test_privacy_rule_follows_the_option_under_another_name( string $option ): void { + register_setting( + 'reading', + $option, + array( + 'type' => 'integer', + 'show_in_abilities' => array( 'name' => 'settings_update_test_privacy_page' ), + ) + ); + $this->register_ability(); + $this->become_admin(); + $this->deny_privacy_capability(); + $before = $this->snapshot(); + + $result = $this->update( array( 'settings_update_test_privacy_page' => self::$fixture_ids['page'] ) ); + + $this->assert_error_code( $result, 'ability_invalid_permissions' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Names that the privacy policy page option is registered with. + */ + public static function data_privacy_policy_page_options(): array { + return array( + 'the option name' => array( 'wp_page_for_privacy_policy' ), + 'the option in upper case' => array( 'WP_PAGE_FOR_PRIVACY_POLICY' ), + ); + } + + /** + * A `wp_ability_permission_result` filter that grants the call lets a user without + * `manage_options` update settings. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_permission_filter_grants_the_update(): void { + wp_set_current_user( self::$user_ids['subscriber'] ); + add_filter( 'wp_ability_permission_result', '__return_true' ); + $expected = $this->snapshot(); + $expected['blogname'] = 'Granted title'; + + $result = $this->update( array( 'title' => 'Granted title' ) ); + + $this->assertSame( array( 'title' => 'Granted title' ), $result, 'The output should show the saved value.' ); + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'The setting should be stored.' ); + } + + /** + * A `wp_ability_permission_result` filter that grants the call lets a user without + * `manage_privacy_options` set the privacy policy page. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_permission_filter_grants_the_privacy_policy_page(): void { + $this->become_admin(); + $this->deny_privacy_capability(); + add_filter( 'wp_ability_permission_result', '__return_true' ); + $page_id = self::$fixture_ids['page']; + + $result = $this->update( array( 'page_for_privacy_policy' => $page_id ) ); + + $this->assertSame( array( 'page_for_privacy_policy' => $page_id ), $result, 'The output should show the saved page.' ); + $this->assertSame( (string) $page_id, $this->snapshot()['wp_page_for_privacy_policy'], 'The page should be stored.' ); + } + + /** + * The permission check accepts input that was not prepared, as a direct call to + * check_permissions() may pass, and leaves the refusal of invalid input to execute(). + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_unprepared_input + * + * @param mixed $input The input. + */ + public function test_permission_check_accepts_unprepared_input( $input ): void { + $this->become_admin(); + + $this->assertTrue( wp_get_ability( self::ABILITY )->check_permissions( $input ), 'The permission check should allow an administrator.' ); + } + + /** + * Data provider. + * + * @return array Inputs that were not prepared. + */ + public static function data_unprepared_input(): array { + return array( + 'no input' => array( null ), + 'a string input' => array( 'title' ), + 'a string for data' => array( array( 'data' => 'title' ) ), + 'an object input' => array( (object) array( 'data' => (object) array( 'title' => 'x' ) ) ), + ); + } + + /** + * 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->assertSameSetsWithIndex( $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 numeric key that is not a setting name' => array( array( 'data' => array( 0 => '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 ) ), + 'an empty array for data' => array( array( 'data' => array() ) ), + 'an empty object for data' => array( array( 'data' => new stdClass() ) ), + 'an empty string for an integer' => array( array( 'data' => array( 'posts_per_page' => '' ) ) ), + 'an empty string for a boolean' => array( array( 'data' => array( 'use_smilies' => '' ) ) ), + 'an empty string for an enum' => array( array( 'data' => array( 'default_ping_status' => '' ) ) ), + '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, + ), + ), + ), + ), + ), + 'a valid setting before an invalid one' => array( + array( + 'data' => array( + 'title' => 'Changed title', + 'posts_per_page' => 'abc', + ), + ), + ), + ); + } + + /** + * The WordPress address and the administration email address cannot be updated. On single site + * core/settings-get still reads them, and on multisite they are not exposed. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_read_only_core_settings + * + * @param string $name The setting name. + * @param string|null $value A valid value, or null. + */ + public function test_url_and_email_cannot_be_updated( 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 ) ); + $read = wp_get_ability( 'core/settings-get' )->execute( array() ); + + $this->assertArrayNotHasKey( $name, $properties, 'The setting should not be in the input schema.' ); + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + $this->assertSame( ! is_multisite(), isset( $read[ $name ] ), 'core/settings-get should read the setting on single site only.' ); + } + + /** + * Data provider. + * + * @return array Setting names, and valid values or null. + */ + public static function data_read_only_core_settings(): array { + return array( + 'url' => array( 'url', 'https://acme.example' ), + 'null for url' => array( 'url', null ), + 'email' => array( 'email', 'owner@acme.example' ), + 'null for email' => array( 'email', null ), + ); + } + + /** + * The read-only rule holds for each read-only option, also when a plugin exposes it under + * another name, or registers its name with surrounding spaces, which the options API trims, + * or in another case, which the database ignores. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_read_only_options + * + * @param string $option The name the option is registered with. + */ + public function test_read_only_rule_follows_the_option_under_another_name( string $option ): void { + $name = 'settings_update_test_read_only_option'; + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => $name ), + ) + ); + $this->register_ability(); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( array( $name => 'https://acme.example' ) ); + + $this->assertArrayNotHasKey( $name, wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties'], 'The option should not be writable under another name.' ); + $this->assertArrayHasKey( $name, wp_get_ability( 'core/settings-get' )->get_output_schema()['properties'], 'The option should still be read under another name.' ); + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Names that read-only options are registered with. + */ + public static function data_read_only_options(): array { + return array( + 'the WordPress address' => array( 'siteurl' ), + 'the site address' => array( 'home' ), + 'the administration email address' => array( 'admin_email' ), + 'the WordPress address with spaces' => array( ' siteurl ' ), + 'the site address with a trailing tab' => array( "home\t" ), + 'the WordPress address in another case' => array( 'SiteURL' ), + 'the administration email address in another case' => array( ' Admin_Email ' ), + ); + } + + /** + * 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, or the kind of content whose ID is the 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 { + // A data provider runs before the content exists, so it names the kind of content instead of its ID. + if ( in_array( $option, self::ID_OPTIONS, true ) ) { + $value = self::$fixture_ids[ $value ]; + $output = (string) $value; + $raw = (string) $value; + } + + $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.' ); + + $expected[ $option ] = $raw; + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'Only the option of the named setting should change.' ); + + wp_cache_delete( 'alloptions', 'options' ); + $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 stores the default of each setting that has one, and deletes the stored value + * of the others, which are then left out. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_resettable_settings + * + * @param string $name The exposed setting name. + * @param string $option The option name. + * @param mixed $value A valid value, or the kind of content whose ID is the 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_resets_each_setting( string $name, string $option, $value, string $output, string $raw, ?string $after_null ): void { + update_option( $option, in_array( $option, self::ID_OPTIONS, true ) ? self::$fixture_ids[ $value ] : $value ); + $this->become_admin_for( $name ); + $expected = $this->expected_after_null( $option ); + + $result = $this->update( array( $name => null ) ); + + $this->assertNotWPError( $result, 'The setting should be reset.' ); + $this->assertSame( null === $after_null ? '[]' : '{"' . $name . '":' . $after_null . '}', wp_json_encode( $result ), 'The setting should read as its default, or be left out.' ); + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'Only the row of the named setting should hold its default or be deleted.' ); + } + + /** + * Returns the stored rows expected after a null value for the given option. + * + * @param string $option The option name. + * @return array Raw option values keyed by option name. + */ + private function expected_after_null( string $option ): array { + $expected = $this->snapshot(); + unset( $expected[ $option ] ); + if ( isset( self::STORED_DEFAULTS[ $option ] ) ) { + $expected[ $option ] = self::STORED_DEFAULTS[ $option ]; + } + + return $expected; + } + + /** + * Data provider. + * + * Every core setting the ability can update, plus the settings this class registers. A setting that holds the + * ID of a page or a category names the kind of content, and the tests fill in the ID. + * + * @return array Settings with a valid value. + */ + public static function data_settings(): array { + return 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 ), + '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', '""' ), + 'use_smilies' => array( 'use_smilies', 'use_smilies', false, 'false', '', 'true' ), + 'default_category' => array( 'default_category', 'default_category', 'category', '', '', 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', 'page', '', '', null ), + 'page_for_posts' => array( 'page_for_posts', 'page_for_posts', 'page', '', '', null ), + 'page_for_privacy_policy' => array( 'page_for_privacy_policy', 'wp_page_for_privacy_policy', 'page', '', '', 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 ), + ); + } + + /** + * Data provider. + * + * The settings of data_settings() that a null value can reset. + * + * @return array Settings with a valid value. + */ + public static function data_resettable_settings(): array { + return array_filter( + self::data_settings(), + static fn( array $setting ): bool => ! in_array( $setting[1], self::NON_RESETTABLE_OPTIONS, true ) + ); + } + + /** + * A null value is refused for the date format, the time format and the default category, + * and nothing is written. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_non_resettable_core_settings + * + * @param string $name The exposed setting name. + * @param string $option The option name. + */ + public function test_null_is_refused_for_a_setting_that_cannot_be_reset( string $name, string $option ): void { + $this->become_admin(); + $before = $this->snapshot(); + + $property = wp_get_ability( self::ABILITY )->get_input_schema()['properties']['data']['properties'][ $name ]; + $result = $this->update( array( $name => null ) ); + + $this->assertArrayHasKey( $option, $before, 'The option should have a stored value before the call.' ); + $this->assertNotContains( 'null', (array) $property['type'], 'The setting should not accept null.' ); + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Setting names and option names. + */ + public static function data_non_resettable_core_settings(): array { + return array( + 'date_format' => array( 'date_format', 'date_format' ), + 'time_format' => array( 'time_format', 'time_format' ), + 'default_category' => array( 'default_category', 'default_category' ), + ); + } + + /** + * The reset rule holds for each option that cannot be reset, also when a plugin exposes it + * under another name, or registers its name with surrounding spaces, which the options API + * trims, or in another case, which the database ignores. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_non_resettable_options + * + * @param string $option The name the option is registered with. + * @param string $type The type the option is registered with. + */ + public function test_reset_rule_follows_the_option_under_another_name( string $option, string $type ): void { + $name = 'settings_update_test_non_resettable_option'; + + register_setting( + 'general', + $option, + array( + 'type' => $type, + 'show_in_abilities' => array( 'name' => $name ), + ) + ); + $this->register_ability(); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( array( $name => null ) ); + + $this->assert_error_code( $result, 'ability_invalid_input' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Names and types that options that cannot be reset are registered with. + */ + public static function data_non_resettable_options(): array { + return array( + 'the date format' => array( 'date_format', 'string' ), + 'the time format' => array( 'time_format', 'string' ), + 'the default category' => array( 'default_category', 'integer' ), + 'the date format with spaces' => array( ' date_format ', 'string' ), + 'the date format in another case' => array( 'Date_Format', 'string' ), + 'the default category in upper case' => array( 'DEFAULT_CATEGORY', 'integer' ), + ); + } + + /** + * 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->assertSameSetsWithIndex( $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' ), + '"false" for a boolean' => array( 'use_smilies', 'use_smilies', '1', 'false', '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' ), + 'zero posts per page' => array( 'posts_per_page', 'posts_per_page', '10', 0, '1', '1' ), + 'English as an empty language' => array( 'language', 'WPLANG', 'de_DE', '', '""', '' ), + ); + } + + /** + * A value that matches the schema, but that the setting cannot use, is refused. The error names + * the setting, and the other settings of the call are not written either. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_unusable_values + * + * @param string $name The exposed setting name. + * @param string|int $value The value to write. + */ + public function test_refuses_a_value_the_setting_cannot_use( string $name, $value ): void { + $this->become_admin_for( $name ); + $before = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Changed title', + $name => $value, + ) + ); + + $this->assert_invalid_value_error( $result, $name ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Setting names, and values that match the schema but cannot be used. + */ + public static function data_unusable_values(): array { + return array( + 'an unknown timezone' => array( 'timezone', 'Mars/Olympus' ), + 'a UTC offset as the timezone' => array( 'timezone', 'UTC+2' ), + 'a language that is not installed' => array( 'language', 'xx_XX' ), + 'an unknown post format' => array( 'default_post_format', 'banana' ), + 'a front page that does not exist' => array( 'page_on_front', 999999 ), + 'a negative front page' => array( 'page_on_front', -1 ), + 'a page for posts that does not exist' => array( 'page_for_posts', 999999 ), + 'a privacy policy page that does not exist' => array( 'page_for_privacy_policy', 999999 ), + 'a default category that does not exist' => array( 'default_category', 999999 ), + 'no default category' => array( 'default_category', 0 ), + 'a negative default category' => array( 'default_category', -1 ), + ); + } + + /** + * Every value the settings cannot use is reported, before an invalid stored value. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_reports_every_value_the_settings_cannot_use(): void { + $this->store_raw( 'start_of_week', 'Monday' ); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( + array( + 'timezone' => 'Mars/Olympus', + 'start_of_week' => null, + 'language' => 'xx_XX', + ) + ); + + $this->assert_error_code( $result, 'settings_invalid_value' ); + $this->assertSame( 'Invalid parameter(s): data[timezone], data[language]', $result->get_error_message(), 'The message should name every refused setting.' ); + $this->assertSame( 400, $result->get_error_data()['status'], 'The error should be a client error.' ); + $this->assertSameSets( array( 'data[timezone]', 'data[language]' ), array_keys( $result->get_error_data()['params'] ), 'The error data should name every refused setting.' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * The ID of content of another kind is refused: a post is not a page, and a tag is not a category. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_refuses_the_id_of_another_kind_of_content(): void { + $this->become_admin(); + $before = $this->snapshot(); + + $post = $this->update( array( 'page_on_front' => self::$fixture_ids['post'] ) ); + $tag = $this->update( array( 'default_category' => self::$fixture_ids['tag'] ) ); + + $this->assert_invalid_value_error( $post, 'page_on_front' ); + $this->assert_invalid_value_error( $tag, 'default_category' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * A page in the trash or an auto-draft is refused for each page setting, and the other + * settings of the call are not written either. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_unusable_page_statuses + * + * @param string $name The exposed setting name. + * @param string $status The status of the page. + */ + public function test_refuses_a_page_in_the_trash_or_an_auto_draft( string $name, string $status ): void { + $page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => $status, + ) + ); + $this->become_admin_for( $name ); + $before = $this->snapshot(); + + $result = $this->update( + array( + 'title' => 'Changed title', + $name => $page_id, + ) + ); + + $this->assert_invalid_value_error( $result, $name ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Page setting names and page statuses that cannot be used. + */ + public static function data_unusable_page_statuses(): array { + return array( + 'a front page in the trash' => array( 'page_on_front', 'trash' ), + 'an auto-draft front page' => array( 'page_on_front', 'auto-draft' ), + 'a page for posts in the trash' => array( 'page_for_posts', 'trash' ), + 'an auto-draft page for posts' => array( 'page_for_posts', 'auto-draft' ), + 'a privacy policy page in the trash' => array( 'page_for_privacy_policy', 'trash' ), + 'an auto-draft privacy policy page' => array( 'page_for_privacy_policy', 'auto-draft' ), + ); + } + + /** + * A draft page can be the privacy policy page, as Settings > Privacy offers drafts. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_accepts_a_draft_privacy_policy_page(): void { + $page_id = self::factory()->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'draft', + ) + ); + $this->become_admin_for( 'page_for_privacy_policy' ); + + $result = $this->update( array( 'page_for_privacy_policy' => $page_id ) ); + + $this->assertSame( array( 'page_for_privacy_policy' => $page_id ), $result, 'The output should show the saved page.' ); + $this->assertSame( (string) $page_id, $this->snapshot()['wp_page_for_privacy_policy'], 'The draft page should be stored.' ); + } + + /** + * The value rules hold when the option is exposed under another name, also when its name is + * registered in another case, which the database ignores. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_value_rule_options + * + * @param string $option The name the option is registered with. + * @param string $type The type the option is registered with. + * @param string|int $value A value the option cannot use. + */ + public function test_value_rule_follows_the_option_under_another_name( string $option, string $type, $value ): void { + $name = 'settings_update_test_value_rule_option'; + + register_setting( + 'general', + $option, + array( + 'type' => $type, + 'show_in_abilities' => array( 'name' => $name ), + ) + ); + $this->register_ability(); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( array( $name => $value ) ); + + $this->assert_invalid_value_error( $result, $name ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * Data provider. + * + * @return array Names and types that options with value rules are registered with, and values they cannot use. + */ + public static function data_value_rule_options(): array { + return array( + 'the timezone' => array( 'timezone_string', 'string', 'Mars/Olympus' ), + 'the timezone in another case' => array( 'TimeZone_String', 'string', 'Mars/Olympus' ), + 'the language in lower case' => array( 'wplang', 'string', 'xx_XX' ), + 'the post format in upper case' => array( 'DEFAULT_POST_FORMAT', 'string', 'banana' ), + 'the front page in another case' => array( 'Page_On_Front', 'integer', 999999 ), + 'the category in upper case' => array( 'DEFAULT_CATEGORY', 'integer', 999999 ), + ); + } + + /** + * `en_US` is saved as English when the language option is registered in another case. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_en_us_rule_follows_the_option_in_another_case(): void { + $name = 'settings_update_test_language'; + + register_setting( + 'general', + 'wplang', + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => $name ), + ) + ); + $this->register_ability(); + $this->store_raw( 'WPLANG', 'de_DE' ); + $this->become_admin(); + $expected = $this->snapshot(); + $expected['WPLANG'] = ''; + + $result = $this->update( array( $name => 'en_US' ) ); + + $this->assertSame( array( $name => '' ), $result, 'en_US should be saved as English.' ); + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'English should be stored as an empty string.' ); + } + + /** + * The values that stand for "none" and the other forms a setting can use are saved. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_usable_values + * + * @param string $name The exposed setting name. + * @param string $option The option name. + * @param string|int $stored The raw value stored before the call. + * @param string|int $value The value to write. + */ + public function test_accepts_a_value_the_setting_can_use( string $name, string $option, $stored, $value ): void { + $this->store_raw( $option, $stored ); + $this->become_admin_for( $name ); + $expected = $this->snapshot(); + + $result = $this->update( array( $name => $value ) ); + + $this->assertSame( array( $name => $value ), $result, 'The output should show the saved value.' ); + $expected[ $option ] = (string) $value; + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'Only the option of the named setting should hold the saved value.' ); + } + + /** + * Data provider. + * + * @return array Setting names, option names, stored values and values to write. + */ + public static function data_usable_values(): array { + return array( + 'no timezone' => array( 'timezone', 'timezone_string', 'Europe/Lisbon', '' ), + 'UTC as the timezone' => array( 'timezone', 'timezone_string', 'Europe/Lisbon', 'UTC' ), + 'a timezone under an old name' => array( 'timezone', 'timezone_string', 'Europe/Lisbon', 'US/Pacific' ), + 'no default post format' => array( 'default_post_format', 'default_post_format', 'aside', '0' ), + 'the standard post format' => array( 'default_post_format', 'default_post_format', 'aside', 'standard' ), + 'an empty default post format' => array( 'default_post_format', 'default_post_format', 'aside', '' ), + 'no front page' => array( 'page_on_front', 'page_on_front', '5', 0 ), + 'no page for posts' => array( 'page_for_posts', 'page_for_posts', '5', 0 ), + 'no privacy policy page' => array( 'page_for_privacy_policy', 'wp_page_for_privacy_policy', '5', 0 ), + ); + } + + /** + * The language that core/settings-get reads when none is stored, `en_US`, can be written back, + * and is saved as English. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_en_us_language_is_saved_as_english(): void { + $this->store_raw( 'WPLANG', null ); + $this->become_admin(); + $read = wp_get_ability( 'core/settings-get' )->execute( array( 'fields' => array( 'language' ) ) ); + $this->store_raw( 'WPLANG', 'de_DE' ); + $expected = $this->snapshot(); + + $result = $this->update( $read ); + + $this->assertSame( array( 'language' => 'en_US' ), $read, 'The language should read as en_US when none is stored.' ); + $this->assertSame( array( 'language' => '' ), $result, 'en_US should be saved as English.' ); + $expected['WPLANG'] = ''; + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'English should be stored as an empty string.' ); + } + + /** + * 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 resets 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 reset setting should read as its default.' ); + + $expected['blogname'] = 'Acme Robotics'; + $expected['posts_per_page'] = '12'; + $expected['use_smilies'] = '1'; + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'Only the named settings should change.' ); + } + + /** + * 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'; + $calls = 0; + + register_setting( + 'general', + $option, + array( + 'type' => 'string', + 'show_in_abilities' => true, + 'sanitize_callback' => static function ( $value ) use ( &$calls ): string { + ++$calls; + return strtoupper( (string) $value ); + }, + ) + ); + $this->register_ability(); + $this->store_raw( $option, 'seed' ); + $this->become_admin(); + + $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, $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, + * with or without a default, and nothing is replaced or deleted. The error names the setting. + * + * @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. + */ + 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_refused_setting_error( $result, 'settings_invalid_stored_value', 500, $name ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be replaced or deleted.' ); + } + + /** + * Every setting whose stored value a null value cannot replace or delete is reported. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_reports_every_invalid_stored_value(): void { + $this->store_raw( 'start_of_week', 'Monday' ); + $this->store_raw( 'default_ping_status', 'maybe' ); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( + array( + 'start_of_week' => null, + 'default_ping_status' => null, + ) + ); + + $this->assert_error_code( $result, 'settings_invalid_stored_value' ); + $this->assertSame( 'These parameters have an invalid stored value, and cannot be updated to null: data[start_of_week], data[default_ping_status]', $result->get_error_message(), 'The message should name every refused setting.' ); + $this->assertSame( 500, $result->get_error_data()['status'], 'The error should be a server error.' ); + $this->assertSameSets( array( 'data[start_of_week]', 'data[default_ping_status]' ), array_keys( $result->get_error_data()['params'] ), 'The error data should name every refused setting.' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be deleted.' ); + } + + /** + * Data provider. + * + * @return array Stored values that a null value cannot replace or delete. + */ + public static function data_invalid_stored_values(): array { + return array( + 'a word for an integer' => array( 'start_of_week', 'start_of_week', 'Monday' ), + 'an empty string for an integer' => array( 'start_of_week', 'start_of_week', '' ), + '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 word for an integer with a default' => array( 'posts_per_page', 'posts_per_page', 'ten' ), + 'a word for a boolean with a default' => array( 'use_smilies', 'use_smilies', 'maybe' ), + ); + } + + /** + * A null value resets a stored value that matches the schema of the setting, including the + * forms in which a boolean is stored, and a setting with no stored value. + * + * @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->expected_after_null( $option ); + + $result = $this->update( array( $name => null ) ); + + $this->assertNotWPError( $result, 'The setting should be reset.' ); + $this->assertSame( $output, wp_json_encode( $result ), 'The setting should read as its default, or be left out.' ); + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'Only the row of the named setting should hold its default or be deleted.' ); + } + + /** + * Data provider. + * + * @return array Stored values that a null value resets, 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}' ), + 'no value for an integer with a default' => array( 'posts_per_page', 'posts_per_page', null, '{"posts_per_page":10}' ), + 'no value for the language' => array( 'language', 'WPLANG', null, '{"language":""}' ), + 'no value for a string without a default' => array( 'title', 'blogname', null, '[]' ), + 'false for a boolean without a default' => array( 'settings_update_test_boolean', 'settings_update_test_boolean', '', '[]' ), + '"0" for a boolean without a default' => array( 'settings_update_test_boolean', 'settings_update_test_boolean', '0', '[]' ), + '"1" for a boolean without a default' => array( 'settings_update_test_boolean', 'settings_update_test_boolean', '1', '[]' ), + ); + } + + /** + * Repeating a null value stores the default of a setting with one again, and changes nothing + * for a setting without one, which has no stored value left. + * + * @ticket 64616 + * + * @since 7.3.0 + */ + public function test_repeated_null(): void { + $this->store_raw( 'posts_per_page', '12' ); + $this->store_raw( 'blogname', 'Acme Robotics' ); + $this->become_admin(); + + $this->assertSame( array( 'posts_per_page' => 10 ), $this->update( array( 'posts_per_page' => null ) ), 'The first call should store the default.' ); + $this->assertSame( array( 'posts_per_page' => 10 ), $this->update( array( 'posts_per_page' => null ) ), 'The second call should store the default again.' ); + + $this->assertSame( array(), $this->update( array( 'title' => null ) ), 'The first call should delete the stored value.' ); + $this->assertSame( array(), $this->update( array( 'title' => null ) ), 'The second call should change nothing.' ); + $this->assertArrayNotHasKey( 'blogname', $this->snapshot(), 'The stored value should stay deleted.' ); + } + + /** + * A value equal to the default that get_option() reads, or sanitized to it, is stored when the + * setting has no stored value, so requests that do not register the setting read it too. This + * also holds when the setting is exposed with another default or has none. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_values_equal_to_the_read_default + * + * @param string $option The option name, which is also the exposed setting name. + * @param array|null $args The setting registration arguments, or null for a core setting. + * @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_value_equal_to_the_read_default_is_stored( string $option, ?array $args, $value, string $output, string $raw ): void { + if ( null === $args ) { + $this->store_raw( $option, null ); + } else { + register_setting( 'general', $option, $args ); + $this->register_ability(); + } + $this->become_admin(); + $expected = $this->snapshot(); + $expected[ $option ] = $raw; + + $result = $this->update( array( $option => $value ) ); + + $this->assertSame( '{"' . $option . '":' . $output . '}', wp_json_encode( $result ), 'The output should show the written value.' ); + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'Only the option of the named setting should hold the value.' ); + } + + /** + * Data provider. + * + * @return array|null, 2: mixed, 3: string, 4: string}> Settings and a value equal to the default get_option() reads. + */ + public static function data_values_equal_to_the_read_default(): array { + return array( + 'the default of a core boolean' => array( 'use_smilies', null, true, 'true', '1' ), + 'the default of a core integer' => array( 'posts_per_page', null, 10, '10', '10' ), + 'a core value sanitized to the default' => array( 'posts_per_page', null, -10, '10', '10' ), + 'the registered default under another exposed default' => array( + 'settings_update_test_read_default', + array( + 'type' => 'string', + 'default' => 'Registered', + 'show_in_abilities' => array( + 'schema' => array( 'default' => 'Exposed' ), + ), + ), + 'Registered', + '"Registered"', + 'Registered', + ), + 'false for a boolean without a default' => array( + 'settings_update_test_read_default', + array( + 'type' => 'boolean', + 'show_in_abilities' => true, + ), + false, + 'false', + '', + ), + 'a value sanitized to the default' => array( + 'settings_update_test_read_default', + array( + 'type' => 'string', + 'default' => 'Registered', + 'sanitize_callback' => 'trim', + 'show_in_abilities' => true, + ), + ' Registered ', + '"Registered"', + 'Registered', + ), + ); + } + + /** + * A false value written over a stored value updates the option without adding it again, also + * when false is the default get_option() reads. + * + * @ticket 64616 + * + * @since 7.3.0 + * + * @dataProvider data_false_values_over_a_stored_value + * + * @param array $args The setting registration arguments. + * @param bool|null $value The value to write. + */ + public function test_false_over_a_stored_value_does_not_add_the_option( array $args, ?bool $value ): void { + global $wpdb; + + $option = 'settings_update_test_stored_boolean'; + register_setting( 'general', $option, $args ); + $this->register_ability(); + $this->store_raw( $option, '1' ); + $this->become_admin(); + + $added = array(); + add_action( + 'add_option', + static function ( $name ) use ( &$added ): void { + $added[] = $name; + } + ); + + $result = $this->update( array( $option => $value ) ); + + $this->assertSame( array( $option => false ), $result, 'The output should show the written value.' ); + $this->assertSame( '', $this->snapshot()[ $option ] ?? null, 'The value should be stored.' ); + $this->assertNotContains( $option, $added, 'The stored option should not be added again.' ); + $this->assertSame( + 'on', + $wpdb->get_var( $wpdb->prepare( "SELECT autoload FROM {$wpdb->options} WHERE option_name = %s", $option ) ), + 'The autoload value of the stored option should not change.' + ); + } + + /** + * Data provider. + * + * @return array, 1: bool|null}> Boolean settings and a value that is saved as false. + */ + public static function data_false_values_over_a_stored_value(): array { + return array( + 'false for a boolean without a default' => array( + array( + 'type' => 'boolean', + 'show_in_abilities' => true, + ), + false, + ), + 'false for a boolean that defaults to false' => array( + array( + 'type' => 'boolean', + 'default' => false, + 'show_in_abilities' => true, + ), + false, + ), + 'null for a boolean that defaults to false' => array( + array( + 'type' => 'boolean', + 'default' => false, + 'show_in_abilities' => true, + ), + null, + ), + ); + } + + /** + * 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', '0' ); + $this->store_raw( 'start_of_week', 'Monday' ); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( $data ); + + $this->assert_error_code( $result, 'settings_invalid_stored_value' ); + $this->assertSameSetsWithIndex( $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', + 'start_of_week' => null, + ), + ), + 'a reset first' => array( + array( + 'use_smilies' => null, + 'start_of_week' => null, + ), + ), + 'a deletion first' => array( + array( + 'description' => null, + 'start_of_week' => null, + ), + ), + ); + } + + /** + * 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->assertSameSetsWithIndex( $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' => self::$fixture_ids['page'], + ) + ); + + $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( self::$fixture_ids['page'], $result['page_for_privacy_policy'], 'The output should show the saved privacy policy page.' ); + $expected['blogname'] = 'Network title'; + $expected['wp_page_for_privacy_policy'] = (string) self::$fixture_ids['page']; + $this->assertSameSetsWithIndex( $expected, $this->snapshot(), 'Both settings should be saved.' ); + } + + /** + * 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->assertSameSetsWithIndex( $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.' ); + } }