Repository navigation
Abilities API: Add the core/settings-update ability - #10892
jorgefilipecosta wants to merge 15 commits into
Conversation
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
|
Test using WordPress PlaygroundThe changes in this pull request can previewed and tested using a WordPress Playground instance. WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser. Some things to be aware of
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
eb0ef04 to
e582d44
Compare
|
Thank you @westonruter for reviewing this PR, all your suggestions were applied. |
| * @return array<string, array<string, mixed>|object>|WP_Error Updated settings on success, WP_Error on failure. | ||
| */ | ||
| public static function execute_update_settings( $input = array() ) { | ||
| $input = is_array( $input ) ? $input : array(); |
There was a problem hiding this comment.
The @param for $input says it is an array. Is this case here in case an external request is submitting a non-array value? When would an non-array be passed? I realize this is the same as the execute_get_settings() method.
|
|
||
| if ( empty( $input['settings'] ) || ! is_array( $input['settings'] ) ) { | ||
| return array( | ||
| 'updated_settings' => (object) array(), |
There was a problem hiding this comment.
Why are we coercing an empty array into an object?
There was a problem hiding this comment.
To force the JSON encoding to be {} as opposed to [].
There was a problem hiding this comment.
Sorry I should have been clear I'm asking from an API perspective not the technical impl. I should have asked: why feed it an empty anything (I only saw that resolved thread afterwards 😅)
If there's isn't a strong reason, I'd suggest we just make $payload['updated_settings'] : array<string,mixed>|null . It's
- more self documenting (the possibility of no updated settings),
- more performant to check (a falsy check you don't need to unpack),
- more resilient to user/llm error (since they only need to do the falsely check to access the internals without erroring),
- lets us bypass all these ugly coercions from WP using multidimensional arrays by just setting these to
null.
(I understand none of these are big concerns individually, but papercuts add up in api design, why I'm asking if there's any downsides to consider)
|
Related to https://core.trac.wordpress.org/ticket/64605, but since that got merged I'll ask here. How exactly does Is |
6ef6754 to
d129749
Compare
d129749 to
c20d3ff
Compare
core/settings-update ability
Adds `core/settings-update`, which updates the settings exposed with the `show_in_abilities` argument and returns the saved values of the settings named in the call. A `null` value deletes the stored value of a setting, which then reads as its default when it has one. A setting whose schema sets `readonly` to true can be read with `core/settings-get`, but is left out of the update input. The ability requires the `manage_options` capability, and changing the privacy policy page also requires `manage_privacy_options`. See #64616.
c20d3ff to
ad65fc0
Compare
…mpotent. A null value deletes the stored value of a setting, so the ability is annotated as destructive. Repeating a null value can fail, so it is not annotated as idempotent. The REST method stays `POST`. Also documents in the code that deleting on null is intended, and that every setting registered with `show_in_abilities` can be updated unless its schema is read-only.
…pdate`. A value that matches the schema but that the setting cannot use is now refused with `settings_invalid_value`, and the error data names the setting under `params`. This covers an unknown timezone, a language that is not installed, an unknown default post format, a page setting that is not 0 or the ID of a page, and a default category that is not the ID of a category. Every check runs before the first write. Also addresses review feedback: * The input schema of a setting leaves out its `default`. * The output schema lists only the settings the ability can write. * The check for a setting unregistered after the ability is removed. * The docs say that only `readonly` at the top level of a schema counts. * The tests are trimmed, and restore the allowed options after the class. See #64616.
…tings-update`. The site address and the administration email address are left out of the update input, under whatever name they are exposed, and can still be read with `core/settings-get`. Settings > General only changes the administration email address after the new address confirms it. When several values cannot be used, the `settings_invalid_value` error now maps each refused setting to its message under `params`, instead of naming only the first one. Also saves `en_US` as the language as English, so a value read with `core/settings-get` can be written back. See #64616.
…pdate`. A null value now stores the default of a setting that has one, instead of leaving the option deleted. 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 read a deleted value as false. A setting without a default still has its stored value deleted. A value equal to the default of a setting with no stored value is now stored too, since update_option() skips it. See #64616.
Also addresses review feedback: * The tests for users without `manage_options` share one provider of three roles, and check the permission filter case too. * `test_updates_each_setting` reads the saved value back once, from the database. * `@param` blocks are aligned to their own types. * The last try/finally is removed, since the base test case restores the settings and the abilities after each test. See #64616.
…gs-update`. A null value for a setting with a default now always stores the default, instead of failing when the setting has no stored value or an invalid one, such as the language of a site installed in English. A null value for a setting without a default and without a stored value changes nothing. A null value is still refused when a setting without a default has a stored value that does not match its schema. A value equal to the default that get_option() reads is now stored when no value is stored, also when the setting is exposed with another default, or when the value is false for a boolean setting without a default. See #64616.
The value each setting is written with, including the default for a null value and `en_US` saved as English, is now worked out once, before the checks. A null value for a setting without a default is checked against the raw stored value, so a boolean stored as false, an empty string, is refused like any other stored value that does not match its schema. Also addresses review feedback: * The page settings no longer check for a negative ID, since get_post_type() finds no post for one. * The settings lists are declared without property types again. * The read-only options docblock says why the site address and the administration email address are left to Settings > General. * The test base case removes the faked action after registering the abilities again. * The tests share the read-only names, count the sanitize calls in a closure, use the ID of a real page for the privacy policy page, and fix the idempotent assertion message. See #64616.
…value in `core/settings-update`. A null value for a setting without a default is now refused only while the setting has a stored value that `core/settings-get` leaves out, so a boolean stored as false can be reset. A page in the trash or an auto-draft is now refused for the front page, the page for posts and the privacy policy page. The `settings_invalid_stored_value` error now names every refused setting, and maps each one to its message under `params`, as `settings_invalid_value` does. Also addresses review feedback: * The writable settings filter is split over two lines. * Two assertions get a message. See #64616.
| 'execute_callback' => function ( $input ) { | ||
| return $this->execute_settings_update( $input ); | ||
| }, |
There was a problem hiding this comment.
Why not just this?
| 'execute_callback' => function ( $input ) { | |
| return $this->execute_settings_update( $input ); | |
| }, | |
| 'execute_callback' => array( $this, 'execute_settings_update' ), |
Otherwise, PHPStan is flagging this as a argument.type error:
Parameter #1 $input of method WP_Abilities_Settings::execute_settings_update() expects array{data: array<int|string, mixed>}, mixed given.
| * @return array<string, mixed> The value JSON Schema that also accepts null. | ||
| */ | ||
| private function nullable_schema( array $schema ): array { | ||
| $schema['type'] = array( $schema['type'], 'null' ); |
There was a problem hiding this comment.
What if type is a string[] already?
This seems it should be something like:
| $schema['type'] = array( $schema['type'], 'null' ); | |
| $schema['type'] = array_merge( (array) $schema['type'], array( 'null' ) ); |
| * @since 7.3.0 | ||
| * | ||
| * @param array<string, mixed> $schema The value JSON Schema. | ||
| * @return array<string, mixed> The value JSON Schema that also accepts null. |
There was a problem hiding this comment.
| * @return array<string, mixed> The value JSON Schema that also accepts null. | |
| * @return array<string, mixed> The value JSON Schema that also accepts null. | |
| * | |
| * @phpstan-param array{ | |
| * type: non-empty-string|non-empty-string[], | |
| * enum?: mixed[], | |
| * default?: mixed, | |
| * ... | |
| * } $schema | |
| * @phpstan-return array{ | |
| * type: non-empty-string[], | |
| * enum?: mixed[], | |
| * ... | |
| * } |
…epeated capability check in `core/settings-update`. A false value written over a stored value no longer adds the option again, which could change its autoload value. A value equal to the default that get_option() reads is now added only when no value is stored. The execute callback no longer checks `manage_options` again. The required capability decides who can run the ability, so a `wp_ability_permission_result` filter that grants the call, or changed required capabilities, now also allow the update. Setting the privacy policy page still requires `manage_privacy_options`. See #64616.
| foreach ( $named as $exposed_name => $setting ) { | ||
| $value = $data[ $exposed_name ]; | ||
| if ( null === $value ) { | ||
| delete_option( $setting['option'] ); | ||
| continue; | ||
| } |
There was a problem hiding this comment.
I tested a null reset on three core settings, and the site broke in two ways.
- After a reset of
date_formatandtime_format,get_the_date()andget_the_time()returned empty strings. - After a reset of
default_category, a newly published post had no category.
The installer adds these values, but the settings are registered without a default. So the reset deletes the option, and nothing replaces it.
Could we reject null for these settings until each has a reliable reset value? I tested only three settings. Other core settings lacking a registered default might share this issue. It is difficult to judge how far we should extend this approach.
| 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. | ||
| if ( | ||
| 0 !== $value | ||
| && ( | ||
| ! is_int( $value ) | ||
| || 'page' !== get_post_type( $value ) | ||
| || in_array( get_post_status( $value ), array( 'trash', 'auto-draft' ), true ) | ||
| ) | ||
| ) { | ||
| return __( 'Invalid page ID.' ); | ||
| } | ||
| break; |
There was a problem hiding this comment.
This check accepts a page in any status except trash and auto-draft. I set page_on_front to a draft, pending, private, and scheduled page. Each call succeeded, and / then returned 404 for a logged-out visitor.
The Settings screens prevent this only in the form, so I know it is hard to enforce here today. A shared rule in the Settings API would be the right fix, and that is follow-up work.
For this PR, could the comment above this check mention the gap?
| /* | ||
| * Intentionally strict: the whole call is refused, instead of leaving this one setting out | ||
| * of the update. The rule belongs to the option, whatever name exposes it. | ||
| */ | ||
| if ( in_array( 'wp_page_for_privacy_policy', array_column( $named, 'option' ), true ) && ! current_user_can( 'manage_privacy_options' ) ) { | ||
| return new WP_Error( | ||
| 'settings_cannot_manage_privacy_options', | ||
| __( 'Sorry, you are not allowed to manage privacy options on this site.' ), | ||
| array( 'status' => rest_authorization_required_code() ) | ||
| ); | ||
| } |
There was a problem hiding this comment.
Could this check move into a permission_callback? That is the place for permission rules. The callback receives the prepared input, so it can look for the privacy policy page option in the same way as here.
A caller can then learn about the restriction from check_permissions(), before the ability runs. The wp_ability_permission_result filter also applies to it.
When a permission check fails, execute() returns the generic ability_invalid_permissions error. So the two tests that expect settings_cannot_manage_privacy_options will need an update.
| * | ||
| * @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 { |
There was a problem hiding this comment.
The last commit removed the part of this test where a wp_ability_permission_result filter grants the call. The commit message says that such a filter now also allows the update. Could we add a test for that, so the new behavior is covered?
| * Every check runs before the first write, so a call that ends in an error changes nothing. | ||
| * The output holds only the settings named in the call, read the same way as for | ||
| * `core/settings-get`. |
There was a problem hiding this comment.
This is true for the ability's own checks. A plugin sanitizer can still throw during a later write, and then the earlier writes are already saved. Could the comment say that?
| * @since 7.3.0 | ||
| * @var string[] | ||
| */ | ||
| private const READ_ONLY_OPTIONS = array( 'siteurl', 'admin_email' ); |
There was a problem hiding this comment.
Two small points about this list. I found both by reading the code, and I did not test them.
update_option()trims the option name, but this list is compared with the name as registered. So a setting registered as'siteurl 'would pass the check and still write tositeurl. Could we trim the name once, when the exposed settings are collected?- Should
homebe on this list next tositeurl? Core does not exposehometo abilities, but a plugin could.
| /* | ||
| * Intentional: every exposed setting can be updated, including the settings exposed | ||
| * before `core/settings-update` existed, except the options in READ_ONLY_OPTIONS. A | ||
| * setting that must stay read-only sets `readonly` to true in its schema. | ||
| * | ||
| * Intentionally strict: a setting whose schema is read-only cannot be updated, so naming | ||
| * it 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( $setting['option'], self::READ_ONLY_OPTIONS, true ) | ||
| ); |
There was a problem hiding this comment.
This is the open question I have been asking since the beginning. Every setting with show_in_abilities becomes writable here.
A plugin that added show_in_abilities in 7.2 only wanted the setting to be readable. After this change the same setting can also be updated, and the plugin author did not choose that. The only way out is readonly in the schema, and existing plugins do not have it. This matters most on multisite, where a site administrator has manage_options but is not a network administrator.
Should writing need its own opt in? For example, an extra key in the show_in_abilities array. Existing registrations would then stay read only, and a plugin could allow updates on purpose.
There was a problem hiding this comment.
After thinking about this a bit more, I’d be happy to use readonly: true in the setting schema to prevent writes. Could we document that settings already exposed through show_in_abilities will become writable unless their schema marks them as read-only?
| continue; | ||
| } | ||
|
|
||
| update_option( $setting['option'], $value ); |
There was a problem hiding this comment.
This is an observation that came up when I compared the ability with REST. No change is needed.
This writes the normal option with update_option(), the same way core/settings-get reads it with get_option(). The two abilities are consistent with each other, and I think that is right.
A plugin can use the rest_pre_get_setting and rest_pre_update_setting filters to store a setting somewhere else. REST and the abilities then show different values. In my test, REST still returned its old value after an update through the ability.
| } elseif ( | ||
| null === $value | ||
| // The stored value reads as null when there is none, and then there is nothing to delete. | ||
| && 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 | ||
| ); | ||
| } |
There was a problem hiding this comment.
This check only covers a setting without a default. I think a setting with a default needs it too.
Example: a setting has the type integer and a default, but the stored value is not an integer. core/settings-get leaves this setting out, so the caller cannot see the stored value. Then the caller sends null.
- Without a default, the ability refuses the call. That is good.
- With a default, the ability replaces the stored value with the default.
- REST refuses in both cases with
rest_invalid_stored_value.
Could the same protection apply when the setting has a default?
| case 'default_post_format': | ||
| if ( '0' !== $value && ! in_array( $value, get_post_format_slugs(), true ) ) { | ||
| return __( 'Invalid post format.' ); | ||
| } | ||
| break; |
There was a problem hiding this comment.
A small note that came up during testing. It is unlikely to happen, but I think it is worth mentioning.
If default_post_format is stored as an empty string, for example after a REST update, core/settings-get returns "". This check then refuses the same value when the caller sends it back. Core treats '' and '0' in the same way, so this check could accept '' too.
| 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; |
There was a problem hiding this comment.
A note that came up during testing. No change is needed in this PR.
The abilities expose timezone_string only. A site can also use a fixed offset, such as UTC+2. Core stores that in gmt_offset and keeps timezone_string empty. On such a site the abilities show an empty timezone and cannot change the offset.
Exposing gmt_offset directly would not be safe, because the two options depend on each other. When timezone_string is set, core calculates gmt_offset from it. The Settings > General form keeps them in sync, and the Settings API has no rule for that. This looks like follow-up work.
| private function nullable_schema( array $schema ): array { | ||
| $schema['type'] = array( $schema['type'], 'null' ); | ||
| if ( isset( $schema['enum'] ) ) { | ||
| $schema['enum'][] = null; | ||
| } | ||
| unset( $schema['default'] ); | ||
|
|
||
| return $schema; | ||
| } |
There was a problem hiding this comment.
A hypothetical case. No core setting uses anyOf or oneOf, but a plugin setting could.
register_setting(
'general',
'my_setting',
array(
'type' => 'string',
'show_in_abilities' => array(
'schema' => array(
'anyOf' => array(
array( 'type' => 'string', 'enum' => array( 'a', 'b' ) ),
array( 'type' => 'string', 'pattern' => '^x' ),
),
),
),
)
);Writing 'a' to this setting works. A null reset is refused with ability_invalid_input. This method adds null only to the top-level type, and no branch in the list accepts it. REST accepts the same null.
One fix worked in my test. For such a schema, keep it unchanged and wrap it in anyOf together with array( 'type' => 'null' ).
gziolo
left a comment
There was a problem hiding this comment.
This PR looks close to ready. I’ve finished my detailed review, including local testing and a comparison with core/settings-get and the REST API. I’ve left my findings inline. Thanks for all the work on this!
…allback in `core/settings-update`. The privacy policy page check now runs as the permission callback of the ability, so `check_permissions()` reports it before the ability runs and the `wp_ability_permission_result` filter applies to it. A refused call now returns `ability_invalid_permissions`. A null value is now refused while the setting has a stored value that `core/settings-get` leaves out, also for a setting with a default. A schema with a top-level `anyOf` or `oneOf` now accepts null through an `anyOf` with a null schema, and a schema whose type is already a list gets null added to that list. The site address (`home`) is now read-only too, and the read-only and capability rules compare the option name trimmed, as the options API stores it. An empty `default_post_format` is now accepted as the standard format, as `0` is. Also addresses review feedback: * The execute callback sanitizes its input, as the permission callback does. * The value schema helper has PHPStan shapes. * The docblocks say that a callback that runs while a value is saved can still stop the call after earlier settings were saved, and that settings exposed before become writable unless their schema sets `readonly` to true. * A comment notes that a page in a status other than the trash or an auto-draft is still accepted. * New tests cover the permission filter, unprepared input, the read-only options and the combining keywords. See #64616.
…t and the default category in `core/settings-update`. These settings have no registered default, so a null value deleted them, and without a value dates and times show as empty strings and new posts get no category. Their input schema no longer accepts null, whatever name exposes them. They can still be updated with a value. See #64616.
…gs-update`. When no value is stored and the sanitized value matches the default that get_option() reads, update_option() stores nothing, so requests that do not register the setting read false. The default that reads is now stored whenever a write leaves no stored value, for example `-10` for the number of posts per page. Also addresses review feedback: * The input schema of a setting drops the default in one place. * The execute callback keeps the values to write apart from the input. * The `register_setting()` docblock no longer says "including settings exposed before", and names the settings that cannot be updated or reset. * The comment in wp_register_core_abilities() names both settings abilities. See #64616.
…ore/settings-update`. The read-only, reset and privacy policy page rules now compare the option name in lower case, the way the database matches it, to fix possible inconsistencies. Also addresses review feedback: * The ability description, the `register_setting()` docblock and a test docblock name the WordPress address as read-only. * An invalid stored value is reported with its own message instead of "Invalid parameter(s)". * The language and page value errors reuse existing translated strings. * The repeated paragraphs in register() are merged. * The value schema helpers drop the unused list type handling, and their PHPStan shapes say the type is a single type. * The settings tests share one administrator instead of creating one per call. See #64616.
… of `core/settings-update`. The value rules and the `en_US` language mapping now compare the option name in lower case, the way the read-only, reset and privacy policy page rules do, to fix possible inconsistencies. Also simplifies the tests: * The value rule test covers each option registered in another case. * The tests that store a core default are rows of the read-default data provider, which now also checks that no other option changes. See #64616.
Part of: WordPress/ai#40
Inspired by the work on https://github.com/galatanovidiu/mcp-adapter-implementation-example/tree/experiment/layerd-mcp-tools/includes/Abilities by @galatanovidiu.
Follow-up to #12141, with the shape from WordPress/abilities#22.
This PR adds the
core/settings-updateability to thesitecategory, for the settings registered withshow_in_abilities:{ data }, with one property per setting to change, named as incore/settings-get, and returns the saved values of those settings.nullvalue resets a setting to its default, and stores the default so requests that do not register the setting read it too. A setting without a default has its stored value deleted, exceptdate_format,time_formatanddefault_category, which refusenullbecause Core needs their values.settings_invalid_value, and the error data maps each refused setting to its message underparams. This covers an unknowntimezone, alanguagethat is not installed, an unknowndefault_post_format, a page setting that is not 0 or the ID of a page, or is a page in the trash or an auto-draft, and adefault_categorythat is not the ID of a category.show_in_abilitiescan be updated, except the read-only ones below, including the settings a plugin exposed forcore/settings-getbefore this ability existed. This is intended, and no separate opt-in for writing is added.readonlytotruein its schema: it can be read withcore/settings-get, but not updated.url), the site address and the administration email address (email) are read-only for this ability, under whatever name a plugin exposes them. Settings > General only changes the administration email address after the new address confirms it.manage_optionscapability, and changing the privacy policy page also requiresmanage_privacy_options.Updating some settings:
{ "title": "Launch notes", "description": "News about the launch", "posts_per_page": 5 }Going back to the default with
null:{ "posts_per_page": 10 }Trac ticket: https://core.trac.wordpress.org/ticket/64616
Known issue
Two settings still get a successful response for a value they do not accept:
show_on_front: "banana"is saved asposts, andstart_of_week: 99is saved as sent. The output always has the stored value. The settings REST route (POST /wp/v2/settings) has the same issue, so it is fixed outside this PR: #16207 limits both settings in the schema both use.Follow-up work
date_format,time_formatanddefault_categoryhave no registered default, so they refusenullhere, while the settings REST route deletes them. Registering a reset value for each would let both reset them.show_on_front,default_comment_statusanddefault_ping_statushave no registered default either, so anullvalue deletes them. After that,is_front_page()is false on the posts home page, and new posts have comments and pings closed, while the installer storesposts,openandopen. Registering these values as defaults would let anullvalue store them.timezone_stringis exposed (timezone). A site on a fixed offset, such as UTC+2, stores it ingmt_offsetand keepstimezone_stringempty, so the abilities show an empty timezone and cannot change the offset. Exposinggmt_offsetalone is not safe, because core calculates it fromtimezone_string, and only the Settings > General form keeps the two in sync.Testing
Verify unit tests are passing:
Or run the examples above in the editor console as an administrator.
AI disclosure: the change and tests were drafted with AI assistance (Claude Code).