diff --git a/src/wp-includes/abilities/class-wp-abilities-settings.php b/src/wp-includes/abilities/class-wp-abilities-settings.php index c0f3df7ce5500..4186e81d8db44 100644 --- a/src/wp-includes/abilities/class-wp-abilities-settings.php +++ b/src/wp-includes/abilities/class-wp-abilities-settings.php @@ -35,7 +35,7 @@ * * @access private * - * @phpstan-type Exposed_Setting array{option: string, group: string, default: mixed, schema: array} + * @phpstan-type Exposed_Setting array{option: string, group: string, default: mixed, schema: array, validate_callback: mixed} */ final class WP_Abilities_Settings { @@ -278,8 +278,9 @@ private function execute_settings_update( $input ) { /* * 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 + * here changes nothing. A value is refused when the validate callback of its setting refuses + * it, instead of being saved as sent or silently replaced with the stored value. The callback + * does not check a null value, which resets the setting. 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. @@ -306,9 +307,14 @@ private function execute_settings_update( $input ) { } 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; + $validity = true; + if ( ! empty( $setting['validate_callback'] ) ) { + // A callback that cannot be called refuses every value, instead of letting any value through. + $validity = is_callable( $setting['validate_callback'] ) ? call_user_func( $setting['validate_callback'], $value, $setting['option'] ) : false; + } + + if ( true !== $validity ) { + $invalid_params[ "data[{$exposed_name}]" ] = is_wp_error( $validity ) ? $validity->get_error_message() : __( 'Invalid parameter.' ); } } elseif ( // The stored value reads as null when there is none, and then there is nothing to replace. @@ -400,75 +406,6 @@ private function get_refused_settings_error( string $code, array $params, int $s ); } - /** - * Checks a value that matches its schema against what the option can use. - * - * The rules belong to the option, whatever name exposes it. - * - * @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. * @@ -681,7 +618,8 @@ private function get_settings_output_schema( array $settings, string $descriptio * `show_in_abilities` argument, of a type the settings endpoint supports. Each entry is * keyed by its exposed name and carries the underlying option name, the settings group, * the default (the exposure schema's default when it declares one, otherwise the registered - * default, or null when there is none), and a JSON Schema describing the value. + * default, or null when there is none), a JSON Schema describing the value, and the + * registered validate callback, or null when there is none. * * Two settings exposed under the same name trigger a notice, and the later one is exposed. * @@ -732,10 +670,11 @@ private function get_exposed_settings(): array { * 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, + 'option' => trim( $option_name ), + 'group' => $args['group'] ?? '', + 'default' => array_key_exists( 'default', $schema ) ? $schema['default'] : ( $args['default'] ?? null ), + 'schema' => $schema, + 'validate_callback' => $args['validate_callback'] ?? null, ); } diff --git a/src/wp-includes/option.php b/src/wp-includes/option.php index 71c97b5342105..bfa3b84bfd7cf 100644 --- a/src/wp-includes/option.php +++ b/src/wp-includes/option.php @@ -2741,6 +2741,8 @@ function set_site_transient( $transient, $value, $expiration = 0 ) { * @since 6.0.1 The `show_on_front`, `page_on_front`, and `page_for_posts` options were added. * @since 7.2.0 The `wp_page_for_privacy_policy` option was registered, exposed as `page_for_privacy_policy`. * @since 7.2.0 Added `show_in_abilities` support for the exposed settings. + * @since 7.3.0 Added a `validate_callback` to the timezone, language, default category, default post format, + * and page settings. */ function register_initial_settings() { register_setting( @@ -2815,6 +2817,7 @@ function register_initial_settings() { 'name' => 'timezone', ), 'show_in_abilities' => true, + 'validate_callback' => '_wp_validate_timezone_string_setting', 'type' => 'string', 'description' => __( 'A city in the same timezone as you.' ), ) @@ -2866,6 +2869,7 @@ function register_initial_settings() { 'name' => 'language', ), 'show_in_abilities' => true, + 'validate_callback' => '_wp_validate_language_setting', 'type' => 'string', 'description' => __( 'WordPress locale code.' ), 'default' => 'en_US', @@ -2890,6 +2894,7 @@ function register_initial_settings() { array( 'show_in_rest' => true, 'show_in_abilities' => true, + 'validate_callback' => '_wp_validate_default_category_setting', 'type' => 'integer', 'description' => __( 'Default post category.' ), ) @@ -2901,6 +2906,7 @@ function register_initial_settings() { array( 'show_in_rest' => true, 'show_in_abilities' => true, + 'validate_callback' => '_wp_validate_default_post_format_setting', 'type' => 'string', 'description' => __( 'Default post format.' ), ) @@ -2941,6 +2947,7 @@ function register_initial_settings() { array( 'show_in_rest' => true, 'show_in_abilities' => true, + 'validate_callback' => '_wp_validate_page_setting', 'type' => 'integer', 'label' => __( 'Page on front' ), 'description' => __( 'The ID of the page that should be displayed on the front page' ), @@ -2953,6 +2960,7 @@ function register_initial_settings() { array( 'show_in_rest' => true, 'show_in_abilities' => true, + 'validate_callback' => '_wp_validate_page_setting', 'type' => 'integer', 'description' => __( 'The ID of the page that should display the latest posts' ), ) @@ -2966,6 +2974,7 @@ function register_initial_settings() { 'name' => 'page_for_privacy_policy', ), 'show_in_abilities' => true, + 'validate_callback' => '_wp_validate_page_setting', 'type' => 'integer', 'description' => __( 'The ID of the page that should be displayed as the privacy policy page' ), ) @@ -3037,6 +3046,121 @@ function _wp_register_initial_settings_for_abilities(): void { $new_allowed_options = $allowed_options; } +/** + * Checks whether the `timezone_string` setting can use a value. + * + * An empty value means no timezone is set. Any other value must be a timezone identifier + * known to PHP, including its older names. + * + * @since 7.3.0 + * @access private + * + * @param mixed $value The value to check. + * @return true|WP_Error True when the setting can use the value, an error otherwise. + */ +function _wp_validate_timezone_string_setting( $value ) { + if ( '' !== $value && ! in_array( $value, timezone_identifiers_list( DateTimeZone::ALL_WITH_BC ), true ) ) { + return new WP_Error( 'invalid_timezone', __( 'The timezone you have entered is not valid. Please select a valid timezone.' ) ); + } + + return true; +} + +/** + * Checks whether the `WPLANG` setting can use a value. + * + * English is stored as an empty value. Any other value must be a language installed on the site. + * + * @since 7.3.0 + * @access private + * + * @param mixed $value The value to check. + * @return true|WP_Error True when the setting can use the value, an error otherwise. + */ +function _wp_validate_language_setting( $value ) { + $languages = get_available_languages(); + if ( '' !== $value && ! in_array( $value, $languages, true ) ) { + return new WP_Error( + 'invalid_language', + /* translators: %l: List of valid values. */ + wp_sprintf( __( 'The language must be one of %l.' ), array_merge( array( 'en_US' ), $languages ) ) + ); + } + + return true; +} + +/** + * Checks whether the `default_post_format` setting can use a value. + * + * `0` and an empty value mean the standard format. Any other value must be a post format. + * + * @since 7.3.0 + * @access private + * + * @param mixed $value The value to check. + * @return true|WP_Error True when the setting can use the value, an error otherwise. + */ +function _wp_validate_default_post_format_setting( $value ) { + if ( '0' !== $value && '' !== $value && ! in_array( $value, get_post_format_slugs(), true ) ) { + return new WP_Error( 'invalid_post_format', __( 'Invalid post format.' ) ); + } + + return true; +} + +/** + * Checks whether the `default_category` setting can use a value. + * + * The value must be the ID of a category. + * + * @since 7.3.0 + * @access private + * + * @param mixed $value The value to check. + * @return true|WP_Error True when the setting can use the value, an error otherwise. + */ +function _wp_validate_default_category_setting( $value ) { + // A negative ID would be looked up as its absolute value. + if ( ! is_int( $value ) || $value <= 0 || ! term_exists( $value, 'category' ) ) { + return new WP_Error( 'invalid_term', __( 'Invalid term ID.' ) ); + } + + return true; +} + +/** + * Checks whether a page setting can use a value. + * + * Used by the `page_on_front`, `page_for_posts` and `wp_page_for_privacy_policy` settings. + * The value must be 0, for no page, or the ID of a page in a status that the Settings screens + * offer for the setting: a published page for the front page and the page for posts, and a + * published or draft page for the privacy policy page. + * + * @since 7.3.0 + * @access private + * + * @param mixed $value The value to check. + * @param string $option The option name. + * @return true|WP_Error True when the setting can use the value, an error otherwise. + */ +function _wp_validate_page_setting( $value, $option ) { + if ( 0 === $value ) { + return true; + } + + $statuses = 'wp_page_for_privacy_policy' === strtolower( trim( $option ) ) ? array( 'publish', 'draft' ) : array( 'publish' ); + if ( + ! is_int( $value ) + || 'page' !== get_post_type( $value ) + || ! in_array( get_post_status( $value ), $statuses, true ) + ) { + return new WP_Error( 'invalid_page', __( 'Invalid post ID.' ) ); + } + + return true; +} + /** * Registers a setting and its data. * @@ -3050,6 +3174,7 @@ function _wp_register_initial_settings_for_abilities(): void { * @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. + * @since 7.3.0 Added the `validate_callback` argument. * * @global array $new_allowed_options * @global array $wp_registered_settings @@ -3069,6 +3194,14 @@ function _wp_register_initial_settings_for_abilities(): void { * @type string $description A description of the data attached to this setting. * @type callable|null $sanitize_callback A callback function that sanitizes the option's value. * Default null. + * @type callable|null $validate_callback A callback function that checks whether the option can use a value, + * before it is saved. It receives the value and the option name, and + * returns true when the value can be used, or a WP_Error object whose + * message says why it cannot. Any other return value also refuses the + * value. It is not called when the option is saved with update_option(): + * the Abilities API calls it before updating a setting exposed with + * `$show_in_abilities`. Registering the setting again without one keeps + * the existing callback. Default null. * @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. @@ -3103,6 +3236,7 @@ function register_setting( $option_group, $option_name, $args = array() ) { 'label' => '', 'description' => '', 'sanitize_callback' => null, + 'validate_callback' => null, 'show_in_rest' => false, 'show_in_abilities' => false, ); @@ -3137,6 +3271,11 @@ function register_setting( $option_group, $option_name, $args = array() ) { $wp_registered_settings = array(); } + // Registering the setting again without a validate callback keeps the rule it was registered with. + if ( empty( $args['validate_callback'] ) && ! empty( $wp_registered_settings[ $option_name ]['validate_callback'] ) ) { + $args['validate_callback'] = $wp_registered_settings[ $option_name ]['validate_callback']; + } + if ( 'misc' === $option_group ) { _deprecated_argument( __FUNCTION__, @@ -3291,6 +3430,7 @@ function unregister_setting( $option_group, $option_name, $deprecated = '' ) { * * @since 4.7.0 * @since 7.2.0 Registered setting data includes the `show_in_abilities` argument. + * @since 7.3.0 Registered setting data includes the `validate_callback` argument. * * @global array $wp_registered_settings * @@ -3307,6 +3447,9 @@ function unregister_setting( $option_group, $option_name, $deprecated = '' ) { * @type string $label A label of the data attached to this setting. * @type string $description A description of the data attached to this setting. * @type callable|null $sanitize_callback A callback function that sanitizes the option's value. + * @type callable|null $validate_callback A callback function that checks whether the option can use a + * value, before it is saved. It receives the value and the option + * name, and returns true or a WP_Error object. * @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. diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php index d40b748864418..df8d66f5516ce 100644 --- a/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreSettingsUpdateAbility.php @@ -285,6 +285,25 @@ private function store_raw( string $option, $value ): void { wp_cache_delete( $option, 'options' ); } + /** + * Registers a plugin setting exposed as `settings_update_test_checked` with a validate callback, + * and registers the abilities again. + * + * @param mixed $callback The validate callback. + */ + private function register_validated_setting( $callback ): void { + register_setting( + 'general', + 'settings_update_test_checked_option', + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => 'settings_update_test_checked' ), + 'validate_callback' => $callback, + ) + ); + $this->register_ability(); + } + /** * Logs in as an administrator who can also set the privacy policy page when the setting needs it. * @@ -1455,10 +1474,11 @@ public function test_refuses_the_id_of_another_kind_of_content(): void { } /** - * 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. + * A page in a status that the Settings screens do not offer for the setting is refused, and + * the other settings of the call are not written either. * * @ticket 64616 + * @ticket 66900 * * @since 7.3.0 * @@ -1467,13 +1487,15 @@ public function test_refuses_the_id_of_another_kind_of_content(): void { * @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, - ) + public function test_refuses_a_page_in_a_status_the_settings_screens_do_not_offer( string $name, string $status ): void { + $args = array( + 'post_type' => 'page', + 'post_status' => $status, ); + if ( 'future' === $status ) { + $args['post_date'] = '2050-01-01 00:00:00'; + } + $page_id = self::factory()->post->create( $args ); $this->become_admin_for( $name ); $before = $this->snapshot(); @@ -1495,10 +1517,19 @@ public function test_refuses_a_page_in_the_trash_or_an_auto_draft( string $name, */ public static function data_unusable_page_statuses(): array { return array( + 'a draft front page' => array( 'page_on_front', 'draft' ), + 'a pending front page' => array( 'page_on_front', 'pending' ), + 'a private front page' => array( 'page_on_front', 'private' ), + 'a scheduled front page' => array( 'page_on_front', 'future' ), 'a front page in the trash' => array( 'page_on_front', 'trash' ), 'an auto-draft front page' => array( 'page_on_front', 'auto-draft' ), + 'a draft page for posts' => array( 'page_for_posts', 'draft' ), + 'a private page for posts' => array( 'page_for_posts', 'private' ), '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 pending privacy policy page' => array( 'page_for_privacy_policy', 'pending' ), + 'a private privacy policy page' => array( 'page_for_privacy_policy', 'private' ), + 'a scheduled privacy policy page' => array( 'page_for_privacy_policy', 'future' ), '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' ), ); @@ -1527,56 +1558,210 @@ public function test_accepts_a_draft_privacy_policy_page(): void { } /** - * 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. + * The value rule of a core setting holds when the setting is registered again, without a + * validate callback, and exposed under another name. + * + * @ticket 64616 + * @ticket 66900 + * + * @since 7.3.0 + */ + public function test_value_rule_follows_the_setting_under_another_name(): void { + $name = 'settings_update_test_value_rule_option'; + + register_setting( + 'general', + 'timezone_string', + array( + 'type' => 'string', + 'show_in_abilities' => array( 'name' => $name ), + ) + ); + $this->register_ability(); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( array( $name => 'Mars/Olympus' ) ); + + $this->assert_invalid_value_error( $result, $name ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * A core setting registered again without a validate callback keeps the value rule of Core, + * and nothing is written when it refuses a value. * * @ticket 64616 + * @ticket 66900 * * @since 7.3.0 + */ + public function test_setting_registered_again_without_a_validate_callback_keeps_the_value_rule(): void { + register_setting( + 'reading', + 'page_on_front', + array( + 'type' => 'integer', + 'show_in_abilities' => true, + ) + ); + $this->register_ability(); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( array( 'page_on_front' => self::$fixture_ids['post'] ) ); + + $this->assert_invalid_value_error( $result, 'page_on_front' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * The value rule belongs to the registered option name: an option registered in another case + * is another setting, which has no value rule unless it is given one. * - * @dataProvider data_value_rule_options + * @ticket 64616 + * @ticket 66900 * - * @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. + * @since 7.3.0 */ - public function test_value_rule_follows_the_option_under_another_name( string $option, string $type, $value ): void { + public function test_option_registered_in_another_case_has_no_value_rule(): void { $name = 'settings_update_test_value_rule_option'; register_setting( 'general', - $option, + 'DEFAULT_POST_FORMAT', array( - 'type' => $type, + 'type' => 'string', 'show_in_abilities' => array( 'name' => $name ), ) ); $this->register_ability(); $this->become_admin(); + + $result = $this->update( array( $name => 'banana' ) ); + + $this->assertSame( array( $name => 'banana' ), $result, 'The value should be saved.' ); + } + + /** + * The validate callback of a plugin setting can refuse a value: the error names the setting + * with the message of the callback, and nothing is written. + * + * @ticket 64616 + * @ticket 66900 + * + * @since 7.3.0 + */ + public function test_validate_callback_of_a_plugin_setting_refuses_a_value(): void { + $this->register_validated_setting( + static function ( $value ) { + return 'banana' === $value ? new WP_Error( 'test_invalid_fruit', 'Bananas are not allowed.' ) : true; + } + ); + $this->become_admin(); $before = $this->snapshot(); - $result = $this->update( array( $name => $value ) ); + $result = $this->update( + array( + 'title' => 'Changed title', + 'settings_update_test_checked' => 'banana', + ) + ); - $this->assert_invalid_value_error( $result, $name ); + $this->assert_invalid_value_error( $result, 'settings_update_test_checked' ); + $this->assertSame( 'Bananas are not allowed.', $result->get_error_message(), 'The message should be the message of the callback.' ); + $this->assertSameSetsWithIndex( $before, $this->snapshot(), 'Nothing should be written.' ); + } + + /** + * The validate callback of a plugin setting receives the value and the option name, and a + * value it accepts is saved. + * + * @ticket 64616 + * @ticket 66900 + * + * @since 7.3.0 + */ + public function test_validate_callback_receives_the_value_and_the_option_name(): void { + $calls = array(); + $this->register_validated_setting( + static function ( ...$args ) use ( &$calls ) { + $calls[] = $args; + return true; + } + ); + $this->become_admin(); + + $result = $this->update( array( 'settings_update_test_checked' => 'apple' ) ); + + $this->assertSame( array( array( 'apple', 'settings_update_test_checked_option' ) ), $calls, 'The callback should receive the value and the option name once.' ); + $this->assertSame( array( 'settings_update_test_checked' => 'apple' ), $result, 'The value should be saved.' ); + } + + /** + * A validate callback that returns neither true nor an error refuses the value, and so does a + * callback that cannot be called. + * + * @ticket 64616 + * @ticket 66900 + * + * @since 7.3.0 + * + * @dataProvider data_refusing_validate_callbacks + * + * @param mixed $callback The validate callback. + */ + public function test_validate_callback_refuses_a_value_unless_it_returns_true( $callback ): void { + $this->register_validated_setting( $callback ); + $this->become_admin(); + $before = $this->snapshot(); + + $result = $this->update( array( 'settings_update_test_checked' => 'apple' ) ); + + $this->assert_invalid_value_error( $result, 'settings_update_test_checked' ); + $this->assertSame( 'Invalid parameter.', $result->get_error_message(), 'The message should be the generic one.' ); $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. + * @return array Validate callbacks that refuse every value. */ - public static function data_value_rule_options(): array { + public static function data_refusing_validate_callbacks(): 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 ), + 'a callback that returns false' => array( '__return_false' ), + 'a callback that returns null' => array( '__return_null' ), + 'a callback that returns 1' => array( static fn(): int => 1 ), + 'a callback that does not exist' => array( 'settings_update_test_missing_function' ), ); } + /** + * A null value resets the setting without calling its validate callback. + * + * @ticket 64616 + * @ticket 66900 + * + * @since 7.3.0 + */ + public function test_validate_callback_is_not_called_for_null(): void { + $calls = 0; + $this->register_validated_setting( + static function () use ( &$calls ) { + ++$calls; + return new WP_Error( 'test_invalid', 'Invalid.' ); + } + ); + $this->store_raw( 'settings_update_test_checked_option', 'apple' ); + $this->become_admin(); + + $result = $this->update( array( 'settings_update_test_checked' => null ) ); + + $this->assertSame( array(), $result, 'The setting should have no value after the reset.' ); + $this->assertSame( 0, $calls, 'The callback should not be called.' ); + } + /** * `en_US` is saved as English when the language option is registered in another case. * diff --git a/tests/phpunit/tests/option/registerInitialSettingsValidateCallbacks.php b/tests/phpunit/tests/option/registerInitialSettingsValidateCallbacks.php new file mode 100644 index 0000000000000..03dfc515c1a78 --- /dev/null +++ b/tests/phpunit/tests/option/registerInitialSettingsValidateCallbacks.php @@ -0,0 +1,274 @@ + + */ + private static $ids = array(); + + /** + * Backup of the `$wp_registered_settings` global. + * + * @var array|null + */ + private $registered_settings_backup; + + /** + * Backup of the `$new_allowed_options` global. + * + * @var array|null + */ + private $allowed_options_backup; + + /** + * Creates a page in each status, a post, a category and a tag. + * + * @param WP_UnitTest_Factory $factory The unit test factory. + */ + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { + foreach ( array( 'publish', 'draft', 'pending', 'private', 'trash', 'auto-draft' ) as $status ) { + self::$ids[ "page_{$status}" ] = $factory->post->create( + array( + 'post_type' => 'page', + 'post_status' => $status, + ) + ); + } + + self::$ids['page_future'] = $factory->post->create( + array( + 'post_type' => 'page', + 'post_status' => 'future', + 'post_date' => '2050-01-01 00:00:00', + ) + ); + self::$ids['post'] = $factory->post->create(); + self::$ids['category'] = $factory->category->create(); + self::$ids['tag'] = $factory->tag->create(); + } + + /** + * Saves the registered settings. + */ + public function set_up() { + global $wp_registered_settings, $new_allowed_options; + + parent::set_up(); + + $this->registered_settings_backup = $wp_registered_settings; + $this->allowed_options_backup = $new_allowed_options; + } + + /** + * Restores the registered settings. + */ + public function tear_down() { + global $wp_registered_settings, $new_allowed_options; + + $wp_registered_settings = $this->registered_settings_backup; + $new_allowed_options = $this->allowed_options_backup; + + parent::tear_down(); + } + + /** + * Each setting with a value rule is registered with its validate callback. + * + * @ticket 64616 + * @ticket 66900 + * + * @dataProvider data_validate_callbacks + * + * @param string $option The option name. + * @param string $callback The expected validate callback. + */ + public function test_registers_the_validate_callback( string $option, string $callback ) { + register_initial_settings(); + + $this->assertSame( $callback, get_registered_settings()[ $option ]['validate_callback'] ); + } + + /** + * Data provider. + * + * @return array Option names and their validate callbacks. + */ + public static function data_validate_callbacks(): array { + return array( + 'timezone_string' => array( 'timezone_string', '_wp_validate_timezone_string_setting' ), + 'WPLANG' => array( 'WPLANG', '_wp_validate_language_setting' ), + 'default_post_format' => array( 'default_post_format', '_wp_validate_default_post_format_setting' ), + 'default_category' => array( 'default_category', '_wp_validate_default_category_setting' ), + 'page_on_front' => array( 'page_on_front', '_wp_validate_page_setting' ), + 'page_for_posts' => array( 'page_for_posts', '_wp_validate_page_setting' ), + 'wp_page_for_privacy_policy' => array( 'wp_page_for_privacy_policy', '_wp_validate_page_setting' ), + ); + } + + /** + * The other initial settings have no validate callback. + * + * @ticket 64616 + * @ticket 66900 + */ + public function test_other_settings_have_no_validate_callback() { + register_initial_settings(); + + $with_callback = array_filter( + get_registered_settings(), + static function ( $args ) { + return ! empty( $args['validate_callback'] ); + } + ); + + $this->assertSameSets( array_keys( self::data_validate_callbacks() ), array_keys( $with_callback ) ); + } + + /** + * Each validate callback accepts the values its setting can use. + * + * @ticket 64616 + * @ticket 66900 + * + * @dataProvider data_usable_values + * + * @param string $option The option name. + * @param mixed $value The value to check, or the key of a fixture whose ID is the value. + * @param bool $is_fixture Whether the value is the key of a fixture. + */ + public function test_accepts_a_usable_value( string $option, $value, bool $is_fixture = false ) { + $this->assertTrue( $this->validate( $option, $is_fixture ? self::$ids[ $value ] : $value ) ); + } + + /** + * Data provider. + * + * @return array Option names and values they can use. + */ + public static function data_usable_values(): array { + return array( + 'no timezone' => array( 'timezone_string', '' ), + 'a timezone' => array( 'timezone_string', 'Europe/Lisbon' ), + 'UTC as the timezone' => array( 'timezone_string', 'UTC' ), + 'a timezone under an old name' => array( 'timezone_string', 'US/Pacific' ), + 'English' => array( 'WPLANG', '' ), + 'an installed language' => array( 'WPLANG', 'de_DE' ), + 'no default post format' => array( 'default_post_format', '0' ), + 'an empty default post format' => array( 'default_post_format', '' ), + 'a post format' => array( 'default_post_format', 'aside' ), + 'a category' => array( 'default_category', 'category', true ), + 'no front page' => array( 'page_on_front', 0 ), + 'a published front page' => array( 'page_on_front', 'page_publish', true ), + 'no page for posts' => array( 'page_for_posts', 0 ), + 'a published page for posts' => array( 'page_for_posts', 'page_publish', true ), + 'no privacy policy page' => array( 'wp_page_for_privacy_policy', 0 ), + 'a published privacy policy page' => array( 'wp_page_for_privacy_policy', 'page_publish', true ), + 'a draft privacy policy page' => array( 'wp_page_for_privacy_policy', 'page_draft', true ), + 'a privacy policy page in another case' => array( 'WP_Page_For_Privacy_Policy', 'page_draft', true ), + ); + } + + /** + * Each validate callback refuses the values its setting cannot use, with the error of its rule. + * + * @ticket 64616 + * @ticket 66900 + * + * @dataProvider data_unusable_values + * + * @param string $option The option name. + * @param mixed $value The value to check, or the key of a fixture whose ID is the value. + * @param string $code The expected error code. + * @param bool $is_fixture Whether the value is the key of a fixture. + */ + public function test_refuses_an_unusable_value( string $option, $value, string $code, bool $is_fixture = false ) { + $result = $this->validate( $option, $is_fixture ? self::$ids[ $value ] : $value ); + + $this->assertWPError( $result, 'The value should be refused.' ); + $this->assertSame( $code, $result->get_error_code(), 'The error should have the code of the rule.' ); + } + + /** + * Data provider. + * + * @return array Option names, values they cannot use, and error codes. + */ + public static function data_unusable_values(): array { + return array( + 'an unknown timezone' => array( 'timezone_string', 'Mars/Olympus', 'invalid_timezone' ), + 'a UTC offset as the timezone' => array( 'timezone_string', 'UTC+2', 'invalid_timezone' ), + 'a language that is not installed' => array( 'WPLANG', 'xx_XX', 'invalid_language' ), + 'en_US as the language' => array( 'WPLANG', 'en_US', 'invalid_language' ), + 'an unknown post format' => array( 'default_post_format', 'banana', 'invalid_post_format' ), + 'no default category' => array( 'default_category', 0, 'invalid_term' ), + 'a negative default category' => array( 'default_category', -1, 'invalid_term' ), + 'a default category as a string' => array( 'default_category', 'category', 'invalid_term' ), + 'a tag as the default category' => array( 'default_category', 'tag', 'invalid_term', true ), + 'a front page that does not exist' => array( 'page_on_front', 999999, 'invalid_page' ), + 'a negative front page' => array( 'page_on_front', -1, 'invalid_page' ), + 'a front page as a string' => array( 'page_on_front', '0', 'invalid_page' ), + 'a post as the front page' => array( 'page_on_front', 'post', 'invalid_page', true ), + 'a post as the privacy policy page' => array( 'wp_page_for_privacy_policy', 'post', 'invalid_page', true ), + 'a draft front page' => array( 'page_on_front', 'page_draft', 'invalid_page', true ), + 'a draft page for posts' => array( 'page_for_posts', 'page_draft', 'invalid_page', true ), + 'a pending front page' => array( 'page_on_front', 'page_pending', 'invalid_page', true ), + 'a private front page' => array( 'page_on_front', 'page_private', 'invalid_page', true ), + 'a scheduled page for posts' => array( 'page_for_posts', 'page_future', 'invalid_page', true ), + 'a front page in the trash' => array( 'page_on_front', 'page_trash', 'invalid_page', true ), + 'an auto-draft page for posts' => array( 'page_for_posts', 'page_auto-draft', 'invalid_page', true ), + 'a pending privacy policy page' => array( 'wp_page_for_privacy_policy', 'page_pending', 'invalid_page', true ), + 'a private privacy policy page' => array( 'wp_page_for_privacy_policy', 'page_private', 'invalid_page', true ), + 'a scheduled privacy policy page' => array( 'wp_page_for_privacy_policy', 'page_future', 'invalid_page', true ), + 'a privacy policy page in the trash' => array( 'wp_page_for_privacy_policy', 'page_trash', 'invalid_page', true ), + 'an auto-draft privacy policy page' => array( 'wp_page_for_privacy_policy', 'page_auto-draft', 'invalid_page', true ), + 'a draft front page in another case' => array( 'Page_On_Front', 'page_draft', 'invalid_page', true ), + ); + } + + /** + * The language error lists English and the installed languages, without naming the option. + * + * @ticket 64616 + * @ticket 66900 + */ + public function test_language_error_lists_the_installed_languages() { + $result = _wp_validate_language_setting( 'xx_XX' ); + + $this->assertWPError( $result, 'The value should be refused.' ); + $this->assertSame( + wp_sprintf( 'The language must be one of %l.', array_merge( array( 'en_US' ), get_available_languages() ) ), + $result->get_error_message(), + 'The message should list English and the installed languages.' + ); + } + + /** + * Calls the validate callback the option is registered with. + * + * @param string $option The option name, which may differ in case from the registered one. + * @param mixed $value The value to check. + * @return mixed The result of the callback. + */ + private function validate( string $option, $value ) { + register_initial_settings(); + + $registered = array_change_key_case( get_registered_settings() ); + + return call_user_func( $registered[ strtolower( $option ) ]['validate_callback'], $value, $option ); + } +} diff --git a/tests/phpunit/tests/option/registration.php b/tests/phpunit/tests/option/registration.php index 48ee025d2536d..684a5f5fdd5f0 100644 --- a/tests/phpunit/tests/option/registration.php +++ b/tests/phpunit/tests/option/registration.php @@ -57,6 +57,100 @@ public function filter_registered_setting() { return 'S-M-R-T'; } + /** + * A setting has no validate callback unless it is registered with one. + * + * @ticket 64616 + * @ticket 66900 + * + * @covers ::register_setting + */ + public function test_register_without_validate_callback() { + register_setting( 'test_group', 'test_no_validate_callback' ); + + $this->assertNull( get_registered_settings()['test_no_validate_callback']['validate_callback'] ); + } + + /** + * The validate callback is kept with the registered setting, and saving the option does not call it. + * + * @ticket 64616 + * @ticket 66900 + * + * @covers ::register_setting + * @covers ::get_registered_settings + */ + public function test_register_with_validate_callback() { + $calls = 0; + $callback = static function () use ( &$calls ) { + ++$calls; + return new WP_Error( 'test_invalid', 'Invalid.' ); + }; + + register_setting( + 'test_group', + 'test_validate_callback', + array( + 'validate_callback' => $callback, + ) + ); + update_option( 'test_validate_callback', 'value' ); + + $this->assertSame( $callback, get_registered_settings()['test_validate_callback']['validate_callback'], 'The callback should be kept with the setting.' ); + $this->assertSame( 'value', get_option( 'test_validate_callback' ), 'update_option() should save the value.' ); + $this->assertSame( 0, $calls, 'update_option() should not call the callback.' ); + } + + /** + * Registering a setting again without a validate callback keeps the callback it was registered with. + * + * @ticket 64616 + * @ticket 66900 + * + * @covers ::register_setting + */ + public function test_register_again_without_validate_callback_keeps_it() { + register_setting( 'test_group', 'test_validate_callback_kept', array( 'validate_callback' => '__return_true' ) ); + register_setting( 'test_group', 'test_validate_callback_kept', array( 'type' => 'integer' ) ); + + $registered = get_registered_settings()['test_validate_callback_kept']; + + $this->assertSame( '__return_true', $registered['validate_callback'], 'The callback should be kept.' ); + $this->assertSame( 'integer', $registered['type'], 'The other arguments should be replaced.' ); + } + + /** + * Registering a setting again with a validate callback replaces the callback it was registered with. + * + * @ticket 64616 + * @ticket 66900 + * + * @covers ::register_setting + */ + public function test_register_again_with_validate_callback_replaces_it() { + register_setting( 'test_group', 'test_validate_callback_replaced', array( 'validate_callback' => '__return_true' ) ); + register_setting( 'test_group', 'test_validate_callback_replaced', array( 'validate_callback' => '__return_false' ) ); + + $this->assertSame( '__return_false', get_registered_settings()['test_validate_callback_replaced']['validate_callback'] ); + } + + /** + * A setting registered again after it was unregistered has no validate callback unless it is given one. + * + * @ticket 64616 + * @ticket 66900 + * + * @covers ::register_setting + * @covers ::unregister_setting + */ + public function test_register_after_unregister_has_no_validate_callback() { + register_setting( 'test_group', 'test_validate_callback_unregistered', array( 'validate_callback' => '__return_true' ) ); + unregister_setting( 'test_group', 'test_validate_callback_unregistered' ); + register_setting( 'test_group', 'test_validate_callback_unregistered' ); + + $this->assertNull( get_registered_settings()['test_validate_callback_unregistered']['validate_callback'] ); + } + /** * @ticket 38176 *