From 00d65cfbc4e4d335138bcdd51d3d17dcbd55f027 Mon Sep 17 00:00:00 2001 From: Nik McLaughlin <72171383+nikmclaughlin@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:29:05 -0700 Subject: [PATCH 1/3] Add the mcp meta flag (public => true) to the 8 media/terms abilities MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PLAN-mcp-adapter-poc.md step 1.5 (sec. 1 resolution, sec. 4.0): the 8 media/terms abilities — wp/media-query, wp/media-upload, wp/media-update, wp/media-delete, wp/terms-query, wp/term-create, wp/term-update, wp/term-delete — did not carry the public meta, so the MCP adapter's McpAbilityExposure falls back to meta.public and excludes them from the MCP surface. This adds the MCP-specific flag mcp => array( public => true ) to their ability_meta(), which McpAbilityExposure checks first, without changing their high-level publicness (no public key added) — the team decides between the mcp flag and full meta.public before this lands on the package's main. annotations/show_in_rest and every other meta key are untouched; no other ability changes. The Registrar's Gate-6 public_only probe reads the ability's own public meta only — the flag is additive there. Tests: the registered-once tests of the 8 abilities (media-query/upload/ update/delete, terms-query, and the term-writes contract test) each now also assert the exact mcp meta shape ( array( public => true ) ) and that the high-level public meta is unchanged (get_meta_item( 'public', false ) === false). No assertions were deleted. --- src/Media/Media_Delete.php | 3 +++ src/Media/Media_Query.php | 3 +++ src/Media/Media_Update.php | 3 +++ src/Media/Media_Upload.php | 3 +++ src/Terms/Term_Create.php | 3 +++ src/Terms/Term_Delete.php | 3 +++ src/Terms/Term_Update.php | 3 +++ src/Terms/Terms_Query.php | 3 +++ tests/Abilities/MediaDeleteTest.php | 6 ++++++ tests/Abilities/MediaQueryTest.php | 6 ++++++ tests/Abilities/MediaUpdateTest.php | 6 ++++++ tests/Abilities/MediaUploadTest.php | 6 ++++++ tests/Abilities/TermWritesTest.php | 2 ++ tests/Abilities/TermsQueryTest.php | 6 ++++++ 14 files changed, 56 insertions(+) diff --git a/src/Media/Media_Delete.php b/src/Media/Media_Delete.php index 11504b6..c146ed9 100644 --- a/src/Media/Media_Delete.php +++ b/src/Media/Media_Delete.php @@ -114,6 +114,9 @@ protected function ability_meta(): array { 'open_world' => false, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } } diff --git a/src/Media/Media_Query.php b/src/Media/Media_Query.php index 04dd1c4..7fd37bb 100644 --- a/src/Media/Media_Query.php +++ b/src/Media/Media_Query.php @@ -182,6 +182,9 @@ protected function ability_meta(): array { 'open_world' => false, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } diff --git a/src/Media/Media_Update.php b/src/Media/Media_Update.php index 36bdffc..bf384a7 100644 --- a/src/Media/Media_Update.php +++ b/src/Media/Media_Update.php @@ -119,6 +119,9 @@ protected function ability_meta(): array { 'open_world' => false, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } } diff --git a/src/Media/Media_Upload.php b/src/Media/Media_Upload.php index 9a02517..63eb185 100644 --- a/src/Media/Media_Upload.php +++ b/src/Media/Media_Upload.php @@ -119,6 +119,9 @@ protected function ability_meta(): array { 'open_world' => true, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } } diff --git a/src/Terms/Term_Create.php b/src/Terms/Term_Create.php index 875248e..e784f5f 100644 --- a/src/Terms/Term_Create.php +++ b/src/Terms/Term_Create.php @@ -116,6 +116,9 @@ protected function ability_meta(): array { 'open_world' => false, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } } diff --git a/src/Terms/Term_Delete.php b/src/Terms/Term_Delete.php index 10c6ef8..e19bc66 100644 --- a/src/Terms/Term_Delete.php +++ b/src/Terms/Term_Delete.php @@ -115,6 +115,9 @@ protected function ability_meta(): array { 'open_world' => false, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } } diff --git a/src/Terms/Term_Update.php b/src/Terms/Term_Update.php index 0ecce5b..361dd53 100644 --- a/src/Terms/Term_Update.php +++ b/src/Terms/Term_Update.php @@ -117,6 +117,9 @@ protected function ability_meta(): array { 'open_world' => false, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } } diff --git a/src/Terms/Terms_Query.php b/src/Terms/Terms_Query.php index 0460a49..283a20d 100644 --- a/src/Terms/Terms_Query.php +++ b/src/Terms/Terms_Query.php @@ -199,6 +199,9 @@ protected function ability_meta(): array { 'open_world' => false, ), 'show_in_rest' => true, + 'mcp' => array( + 'public' => true, + ), ); } diff --git a/tests/Abilities/MediaDeleteTest.php b/tests/Abilities/MediaDeleteTest.php index f499358..827705b 100644 --- a/tests/Abilities/MediaDeleteTest.php +++ b/tests/Abilities/MediaDeleteTest.php @@ -244,6 +244,12 @@ public function test_registers_the_delete_ability(): void { self::assertSame( 'Media Delete', $ability->get_label(), 'The ability should use the PR\'s label.' ); self::assertSame( 'media', $ability->get_category(), 'The ability should use the package-authored media category.' ); self::assertTrue( (bool) ( $meta['show_in_rest'] ?? false ), 'The ability should be exposed in REST.' ); + self::assertSame( + array( 'public' => true ), + $meta['mcp'] ?? null, + 'The mcp meta opts the ability in for MCP-tool exposure; the high-level public meta is unchanged.' + ); + self::assertFalse( $ability->get_meta_item( 'public', false ), 'The high-level public meta is unchanged.' ); $annotations = $meta['annotations'] ?? array(); self::assertFalse( (bool) ( $annotations['readonly'] ?? true ), 'Deleting writes the library.' ); diff --git a/tests/Abilities/MediaQueryTest.php b/tests/Abilities/MediaQueryTest.php index 9d1dbc6..655b47f 100644 --- a/tests/Abilities/MediaQueryTest.php +++ b/tests/Abilities/MediaQueryTest.php @@ -318,6 +318,12 @@ public function test_registered_once_with_annotations_and_provenance(): void { self::assertSame( 'Media Query', $ability->get_label(), 'The ability should use the PR\'s label.' ); self::assertSame( 'media', $ability->get_category(), 'The ability should use the package-authored media category.' ); self::assertTrue( (bool) ( $meta['show_in_rest'] ?? false ), 'The ability should be exposed in REST.' ); + self::assertSame( + array( 'public' => true ), + $meta['mcp'] ?? null, + 'The mcp meta opts the ability in for MCP-tool exposure; the high-level public meta is unchanged.' + ); + self::assertFalse( $ability->get_meta_item( 'public', false ), 'The high-level public meta is unchanged.' ); self::assertSame( array( 'readonly' => true, diff --git a/tests/Abilities/MediaUpdateTest.php b/tests/Abilities/MediaUpdateTest.php index 87a3667..4b70249 100644 --- a/tests/Abilities/MediaUpdateTest.php +++ b/tests/Abilities/MediaUpdateTest.php @@ -250,6 +250,12 @@ public function test_registers_the_update_ability(): void { self::assertSame( 'Media Update', $ability->get_label(), 'The ability should use the PR\'s label.' ); self::assertSame( 'media', $ability->get_category(), 'The ability should use the package-authored media category.' ); self::assertTrue( (bool) ( $meta['show_in_rest'] ?? false ), 'The ability should be exposed in REST.' ); + self::assertSame( + array( 'public' => true ), + $meta['mcp'] ?? null, + 'The mcp meta opts the ability in for MCP-tool exposure; the high-level public meta is unchanged.' + ); + self::assertFalse( $ability->get_meta_item( 'public', false ), 'The high-level public meta is unchanged.' ); $annotations = $meta['annotations'] ?? array(); self::assertFalse( (bool) ( $annotations['readonly'] ?? true ), 'Updating writes the item.' ); diff --git a/tests/Abilities/MediaUploadTest.php b/tests/Abilities/MediaUploadTest.php index 253c5f4..ffbc2d9 100644 --- a/tests/Abilities/MediaUploadTest.php +++ b/tests/Abilities/MediaUploadTest.php @@ -292,6 +292,12 @@ public function test_registers_the_upload_ability(): void { self::assertSame( 'Media Upload', $ability->get_label(), 'The ability should use the PR\'s label.' ); self::assertSame( 'media', $ability->get_category(), 'The ability should use the package-authored media category.' ); self::assertTrue( (bool) ( $meta['show_in_rest'] ?? false ), 'The ability should be exposed in REST.' ); + self::assertSame( + array( 'public' => true ), + $meta['mcp'] ?? null, + 'The mcp meta opts the ability in for MCP-tool exposure; the high-level public meta is unchanged.' + ); + self::assertFalse( $ability->get_meta_item( 'public', false ), 'The high-level public meta is unchanged.' ); $annotations = $meta['annotations'] ?? array(); self::assertFalse( (bool) ( $annotations['readonly'] ?? true ), 'Uploading writes the library.' ); diff --git a/tests/Abilities/TermWritesTest.php b/tests/Abilities/TermWritesTest.php index b8a3922..024e4e9 100644 --- a/tests/Abilities/TermWritesTest.php +++ b/tests/Abilities/TermWritesTest.php @@ -403,6 +403,8 @@ public function test_registered_once_with_the_pr_contract(): void { foreach ( array( $create, $update, $delete ) as $ability ) { self::assertSame( 'content', $ability->get_category(), 'The write abilities share the query\'s content category.' ); self::assertTrue( $ability->get_meta_item( 'show_in_rest', false ), 'The write abilities should be exposed in REST.' ); + self::assertSame( array( 'public' => true ), $ability->get_meta_item( 'mcp', array() ), 'The mcp meta opts the write abilities in for MCP-tool exposure.' ); + self::assertFalse( $ability->get_meta_item( 'public', false ), 'The write abilities\' high-level public meta is unchanged.' ); } $create_annotations = $create->get_meta_item( 'annotations', array() ); diff --git a/tests/Abilities/TermsQueryTest.php b/tests/Abilities/TermsQueryTest.php index b913298..b4ce16e 100644 --- a/tests/Abilities/TermsQueryTest.php +++ b/tests/Abilities/TermsQueryTest.php @@ -372,6 +372,12 @@ public function test_registered_once_with_annotations_and_provenance(): void { self::assertSame( 'Terms Query', $ability->get_label(), 'The ability should use the PR\'s label.' ); self::assertSame( 'content', $ability->get_category(), 'The ability should use the content category.' ); self::assertTrue( (bool) ( $meta['show_in_rest'] ?? false ), 'The ability should be exposed in REST.' ); + self::assertSame( + array( 'public' => true ), + $meta['mcp'] ?? null, + 'The mcp meta opts the ability in for MCP-tool exposure; the high-level public meta is unchanged.' + ); + self::assertFalse( $ability->get_meta_item( 'public', false ), 'The high-level public meta is unchanged.' ); self::assertSame( array( 'readonly' => true, From 9ab085d29f37bf8e8699c3ffff71f69c8158c9a9 Mon Sep 17 00:00:00 2001 From: Nik McLaughlin <72171383+nikmclaughlin@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:22:37 -0700 Subject: [PATCH 2/3] Add the show_in_rest meta flag to the trio core backports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PLAN-ai-plugin-poc.md sec. 7.0 (sec. 10.2 resolution, Option A): core/content-query, core/settings-get and core/users-query gain 'show_in_rest' => true in ability_meta() under a // Package: marker, so the abilities stay exposed over core's REST abilities routes on every supported WordPress (6.9+) — core's own registration omits the flag and relies on meta.public seeding it, which WordPress 7.1+ only does. On 7.1+ the seeding makes the flag redundant but harmless. The same accommodation the AI plugin's synced copies carry with their // Plugin: marker, made once in the package. tools/coreify.php tolerates exactly this marked line and nothing more, symmetrically: a narrow PKG_META_ACCOMMODATIONS map (meta key => marker-comment lines) makes --reverse re-inject the flag (plus markers) into regenerated backports when the fixture's meta lacks it, and forward drop it behind marker-verbatim checks when unwrapping ability_meta() into core-shaped registration args — both semantic-diff invariants of the check gate stay green, and a mapped key without the const's exact markers fails the forward path loudly. The trio tests now pin meta.show_in_rest === true with the high-level public meta unchanged (PR #12's pattern). Stacked on #12 (add/mcp-public-meta) so the ai PoC pins one integration ref. --- CHANGELOG.md | 12 ++ src/Content/Content_Query.php | 15 +- src/Settings/Settings_Get.php | 15 +- src/Users/Users_Query.php | 15 +- tests/Abilities/ContentQueryTest.php | 6 + tests/Abilities/SettingsGetTest.php | 6 + tests/Abilities/UsersQueryTest.php | 6 + tools/coreify.php | 265 +++++++++++++++++++++++++++ 8 files changed, 331 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 501a6a4..3ace465 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,6 +165,18 @@ The entries below describe the current prototype state._ category cannot be deleted (core's capability mapping denies the cap, and `wp_delete_term()` refuses the term). Rides the same `taxonomy_show_in_abilities` opt-in and content category as the query. +- `show_in_rest` exposure flag on the three tier-core backports + (`core/content-query`, `core/settings-get`, `core/users-query`): their + `ability_meta()` now sets the flag explicitly under a `// Package:` marker, + so the abilities stay exposed over core's REST abilities routes on every + supported WordPress (6.9+) — core's own registration omits the flag and + relies on `meta.public` seeding it, which WordPress 7.1+ only does. The same + accommodation the AI plugin's synced copies carry with their `// Plugin:` + marker, made once in the package; the coreify round-trip gate tolerates + exactly this marked line and nothing more (a `PKG_META_ACCOMMODATIONS` map: + `--reverse` re-injects the flag into regenerated backports, forward drops it + behind `// Package:`-verified markers), and the trio tests pin + `meta.show_in_rest === true` with the high-level `public` meta unchanged. ### Removed - `wp/post-create` — the self-authored experimental write-ability prototype diff --git a/src/Content/Content_Query.php b/src/Content/Content_Query.php index 9cacafd..d641156 100644 --- a/src/Content/Content_Query.php +++ b/src/Content/Content_Query.php @@ -213,23 +213,32 @@ protected function make_permission_callback(): callable { } /** - * The authored ability meta, exactly as core registers it. + * The authored ability meta: core-verbatim, plus one marked package accommodation. * * Core also carries no `required_capabilities` on this ability: the permission callback * gates the request as a whole (an authenticated user, an exposed post type, and the * capabilities for the requested statuses), and execute_content_query() adds the * row-level read checks, so the static floor stays empty here too. * + * The `show_in_rest` key below is the one addition (see its `// Package:` marker): + * core's registration omits the flag and relies on `public` seeding it, which + * WordPress 7.1+ only does, so the flag is set explicitly to stay exposed over the + * REST abilities routes on every supported WordPress (6.9+). + * * @return array The ability meta. */ protected function ability_meta(): array { return array( - 'annotations' => array( + 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), - 'public' => true, + 'public' => true, + // Package: set explicitly so the ability is exposed over REST on all + // supported WordPress versions; core's registration relies on the + // `public` flag seeding `show_in_rest`, which WordPress 7.1+ only does. + 'show_in_rest' => true, ); } diff --git a/src/Settings/Settings_Get.php b/src/Settings/Settings_Get.php index 3dd79b6..e1c6396 100644 --- a/src/Settings/Settings_Get.php +++ b/src/Settings/Settings_Get.php @@ -118,18 +118,27 @@ protected function make_permission_callback(): ?callable { } /** - * The authored ability meta, exactly as core registers it. + * The authored ability meta: core-verbatim, plus one marked package accommodation. + * + * The `show_in_rest` key below is the one addition (see its `// Package:` marker): + * core's registration omits the flag and relies on `public` seeding it, which + * WordPress 7.1+ only does, so the flag is set explicitly to stay exposed over the + * REST abilities routes on every supported WordPress (6.9+). * * @return array The ability meta. */ protected function ability_meta(): array { return array( - 'annotations' => array( + 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), - 'public' => true, + 'public' => true, + // Package: set explicitly so the ability is exposed over REST on all + // supported WordPress versions; core's registration relies on the + // `public` flag seeding `show_in_rest`, which WordPress 7.1+ only does. + 'show_in_rest' => true, ); } diff --git a/src/Users/Users_Query.php b/src/Users/Users_Query.php index 592f818..7b63f1d 100644 --- a/src/Users/Users_Query.php +++ b/src/Users/Users_Query.php @@ -168,18 +168,27 @@ protected function make_permission_callback(): callable { } /** - * The authored ability meta, exactly as core registers it. + * The authored ability meta: core-verbatim, plus one marked package accommodation. + * + * The `show_in_rest` key below is the one addition (see its `// Package:` marker): + * core's registration omits the flag and relies on `public` seeding it, which + * WordPress 7.1+ only does, so the flag is set explicitly to stay exposed over the + * REST abilities routes on every supported WordPress (6.9+). * * @return array The ability meta. */ protected function ability_meta(): array { return array( - 'annotations' => array( + 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), - 'public' => true, + 'public' => true, + // Package: set explicitly so the ability is exposed over REST on all + // supported WordPress versions; core's registration relies on the + // `public` flag seeding `show_in_rest`, which WordPress 7.1+ only does. + 'show_in_rest' => true, ); } diff --git a/tests/Abilities/ContentQueryTest.php b/tests/Abilities/ContentQueryTest.php index 1c3348d..4aff438 100644 --- a/tests/Abilities/ContentQueryTest.php +++ b/tests/Abilities/ContentQueryTest.php @@ -188,6 +188,12 @@ public function test_registered_once_with_core_annotations(): void { $meta['annotations'] ?? null ); self::assertTrue( (bool) ( $meta['public'] ?? false ) ); + self::assertSame( + true, + $meta['show_in_rest'] ?? null, + 'The ability stays exposed over the REST abilities routes on every supported WordPress: core seeds show_in_rest from `public` on 7.1+ only, so the package copy ships the flag explicitly (the `// Package:` meta accommodation).' + ); + self::assertSame( true, $ability->get_meta_item( 'public', null ), 'The high-level public meta stays true.' ); if ( empty( $meta['source'] ) ) { // Trunk env: core provides the name; the package copy must have skipped. diff --git a/tests/Abilities/SettingsGetTest.php b/tests/Abilities/SettingsGetTest.php index b0cdde7..0156e04 100644 --- a/tests/Abilities/SettingsGetTest.php +++ b/tests/Abilities/SettingsGetTest.php @@ -213,6 +213,12 @@ public function test_registered_once_with_core_annotations(): void { $meta['annotations'] ?? null ); self::assertTrue( (bool) ( $meta['public'] ?? false ) ); + self::assertSame( + true, + $meta['show_in_rest'] ?? null, + 'The ability stays exposed over the REST abilities routes on every supported WordPress: core seeds show_in_rest from `public` on 7.1+ only, so the package copy ships the flag explicitly (the `// Package:` meta accommodation).' + ); + self::assertSame( true, $ability->get_meta_item( 'public', null ), 'The high-level public meta stays true.' ); if ( empty( $meta['source'] ) ) { // Trunk env: core provides the name; the package copy must have skipped. diff --git a/tests/Abilities/UsersQueryTest.php b/tests/Abilities/UsersQueryTest.php index d25f88d..2c49e4d 100644 --- a/tests/Abilities/UsersQueryTest.php +++ b/tests/Abilities/UsersQueryTest.php @@ -261,6 +261,12 @@ public function test_registered_once_with_core_annotations(): void { $meta['annotations'] ?? null ); self::assertTrue( (bool) ( $meta['public'] ?? false ) ); + self::assertSame( + true, + $meta['show_in_rest'] ?? null, + 'The ability stays exposed over the REST abilities routes on every supported WordPress: core seeds show_in_rest from `public` on 7.1+ only, so the package copy ships the flag explicitly (the `// Package:` meta accommodation).' + ); + self::assertSame( true, $ability->get_meta_item( 'public', null ), 'The high-level public meta stays true.' ); if ( empty( $meta['source'] ) ) { // Trunk env: core provides the name; the package copy must have skipped. diff --git a/tools/coreify.php b/tools/coreify.php index e7dfbc2..a7bf8c2 100644 --- a/tools/coreify.php +++ b/tools/coreify.php @@ -74,6 +74,42 @@ function fail( string $msg ): void { 'execute_callback', 'permission_callback', 'required_capabilities', 'meta', ); +/** + * The one intentional, hand-marked meta divergence the package's tier-core + * backports carry vs core trunk: an explicit `'show_in_rest' => true` in + * ability_meta(). + * + * Core's registration relies on `meta.public` seeding `show_in_rest`, a + * WordPress 7.1+ behavior; the backports serve WordPress 6.9+, and core's REST + * abilities routes (list + run) hard-require the flag. Core's own trio classes + * omit it (fine on 7.2+); the AI plugin's synced copies set it explicitly with + * a `// Plugin:` marker, and the package does the same once with `// Package:`. + * + * This map teaches the round-trip to tolerate exactly this marked meta line and + * nothing more, symmetrically: + * + * - forward() drops the mapped keys (plus their marker comments) when + * unwrapping ability_meta() into core-shaped registration args, so the + * regenerated core text stays semantically identical to the fixture. + * - reverse() re-injects them (key + marker comment lines, boolean true) when + * emitting the package shape's ability_meta(), so a regenerated backport + * keeps the flag and the shipped files keep passing the check gate. + * + * Global across PROFILES is deliberate: every tier-core backport has the same + * 6.9+ floor and the same need. reverse() injects only when the fixture's meta + * lacks the key, so a fixture that already carries it is carried through + * verbatim, never duplicated; forward() requires the exact marker lines below + * immediately before the dropped key, so the shipped files and this const + * change together — the marker is the audit trail, not documentation. + */ +const PKG_META_ACCOMMODATIONS = array( + 'show_in_rest' => array( + '// Package: set explicitly so the ability is exposed over REST on all', + "// supported WordPress versions; core's registration relies on the", + '// `public` flag seeding `show_in_rest`, which WordPress 7.1+ only does.', + ), +); + /** * Optional authoring methods: Abstract_Core_Ability defaults them, and an * ability overrides them only when core's register() entry point computes @@ -994,6 +1030,13 @@ function transform_forward( string $pkgText, string $absText ): string { } $vals[ $entry ] = return_expr( $tokens, $rec ); } + + // The package's marked meta accommodations (PKG_META_ACCOMMODATIONS) leave the + // registration core-shaped: drop exactly the mapped keys (with their marker + // comments) from the meta entry. + if ( isset( $vals['meta'] ) ) { + $vals['meta'] = pkg_meta_drop_accommodations( $vals['meta'] ); + } $nameLit = "'" . $abname . "'"; if ( isset( $vals['required_capabilities'] ) && expr_is_empty_array( $vals['required_capabilities'] ) ) { @@ -1140,6 +1183,223 @@ function transform_forward( string $pkgText, string $absText ): string { return $header . $body . "}\n"; } +/* --------------------------------------------------------------------- + * Package meta accommodations (the one marked divergence, PKG_META_ACCOMMODATIONS) + * ------------------------------------------------------------------- */ + +/** + * Scan a registration-shaped array( ... ) expression: the outer group bounds + * and each top-level element as [first meaningful token, last meaningful + * token] with its separator comma index (null when there is none, i.e. the + * final element before the array close). + * + * The scan is comment-tolerant on purpose: the drop side must reach elements + * preceded by marker comment lines. Callers enforce their own strictness. + * + * @param array $tokens Token list of a '}|null + * Null when the expression is not an array( ... ) with `=>` elements. + */ +function pkg_meta_scan_top_level( array $tokens ): ?array { + $n = count( $tokens ); + $open = null; + for ( $i = 0; $i < $n; $i++ ) { + if ( T_ARRAY !== $tokens[ $i ][0] ) { + continue; + } + $paren = next_meaningful_token( $tokens, $i + 1 ); + if ( null !== $paren && 40 === $tokens[ $paren ][0] ) { + $open = $paren; + break; + } + } + if ( null === $open ) { + return null; + } + $close = match_group( $tokens, $open ); + $elements = array(); + $i = $open + 1; + while ( $i < $close ) { + $first = next_meaningful_token( $tokens, $i, $close - 1 ); + if ( null === $first ) { + break; + } + $arrow = next_meaningful_token( $tokens, $first + 1, $close - 1 ); + if ( null === $arrow || T_DOUBLE_ARROW !== $tokens[ $arrow ][0] ) { + return null; + } + $depth = 0; + $comma = null; + for ( $j = $arrow + 1; $j < $close; $j++ ) { + if ( is_skipped( $tokens[ $j ] ) ) { + continue; + } + if ( 0 === $depth && 44 === $tokens[ $j ][0] ) { + $comma = $j; + break; + } + $depth += struct_delta( $tokens[ $j ] ); + } + $end = prev_meaningful_token( $tokens, $arrow + 1, ( null === $comma ? $close : $comma ) - 1 ); + if ( null === $end ) { + return null; + } + $elements[] = array( 'first' => $first, 'end' => $end, 'comma' => $comma ); + $i = ( null === $comma ? $close : $comma ) + 1; + } + return array( 'open' => $open, 'close' => $close, 'elements' => $elements ); +} + +/** + * The reverse side of the accommodation: inject the {@see PKG_META_ACCOMMODATIONS} + * keys (boolean true, with their marker comment lines) into an emitted + * ability_meta() return statement — `return array( ... );` — so regenerated + * package files keep the accommodation the shipped files hand-author (the mB + * side of the gate). + * + * Keys already present in the meta are carried through untouched (never + * duplicated), so injection is a no-op for any future fixture that already + * ships the flag itself. Existing elements are re-emitted with `=>` arrows + * padded to the widest key among existing and injected elements (WPCS + * alignment); values keep their original text. + * + * @param string $metaReturn The ability_meta() return statement text. + */ +function pkg_meta_inject_accommodations( string $metaReturn ): string { + $tokens = tokenize_source( ' $markers ) { + if ( ! in_array( $key, $present, true ) ) { + $pending[] = $key; + } + } + if ( array() === $pending ) { + return $metaReturn; // already carries every accommodation + } + + /* element line indentation, from the line break ahead of the first element */ + $first0 = $scan['elements'][0]['first']; + $wstok = $first0 > 0 ? $tokens[ $first0 - 1 ] : null; + if ( null === $wstok || T_WHITESPACE !== $wstok[0] || false === strpos( $wstok[1], "\n" ) ) { + fail( 'pkg-meta inject: cannot derive the meta element indentation' ); + } + $indent = substr( $wstok[1], strrpos( $wstok[1], "\n" ) + 1 ); + + $maxlen = 0; + foreach ( $scan['elements'] as $e ) { + $maxlen = max( $maxlen, strlen( $tokens[ $e['first'] ][1] ) ); + } + foreach ( $pending as $key ) { + $maxlen = max( $maxlen, strlen( $key ) + 2 ); + } + + $lines = array(); + foreach ( $scan['elements'] as $e ) { + $arrow = next_meaningful_token( $tokens, $e['first'] + 1, $e['end'] ); + $value = ltrim( span_text( $tokens, $arrow + 1, $e['end'] ) ); + $pad = str_repeat( ' ', $maxlen - strlen( $tokens[ $e['first'] ][1] ) + 1 ); + $lines[] = $indent . $tokens[ $e['first'] ][1] . $pad . '=> ' . $value . ','; + } + foreach ( $pending as $key ) { + foreach ( PKG_META_ACCOMMODATIONS[ $key ] as $marker ) { + $lines[] = $indent . $marker; + } + $pad = str_repeat( ' ', $maxlen - ( strlen( $key ) + 2 ) + 1 ); + $lines[] = $indent . "'" . $key . "'" . $pad . '=> true,'; + } + + $last = $scan['elements'][ count( $scan['elements'] ) - 1 ]; + $tail = span_text( $tokens, ( $last['comma'] ?? $last['end'] ) + 1, count( $tokens ) - 1 ); + return span_text( $tokens, 1, $scan['open'] ) . "\n" . implode( "\n", $lines ) . $tail; +} + +/** + * The forward side of the accommodation: drop the {@see PKG_META_ACCOMMODATIONS} + * keys (plus their exact marker comment lines) from a lifted ability_meta() + * return expression, so the reconstructed core-shaped registration stays + * semantically identical to the fixture (the mA side of the gate). No wildcard + * dropping: only exactly the mapped keys are removed, and nothing else. + * + * Strict by design: a mapped key found in the meta MUST carry the const's + * marker comment lines immediately before it. An unmarked or reworded + * accommodation fails loudly instead of degrading silently, so the shipped + * files and the const change together. + * + * @param string $metaExpr The ability_meta() return expression text. + */ +function pkg_meta_drop_accommodations( string $metaExpr ): string { + $tokens = tokenize_source( ' $scan['open']; $j-- ) { + $id = $tokens[ $j ][0]; + if ( T_WHITESPACE === $id ) { + continue; + } + if ( T_COMMENT !== $id && T_DOC_COMMENT !== $id ) { + break; + } + $collected[] = array( $j, trim( $tokens[ $j ][1] ) ); + } + $got = array_reverse( array_column( $collected, 1 ) ); + if ( $got !== PKG_META_ACCOMMODATIONS[ $key ] ) { + fail( "pkg-meta drop: ability_meta() carries the accommodated key '$key' without PKG_META_ACCOMMODATIONS's exact marker comment lines (expected: " . implode( ' ', PKG_META_ACCOMMODATIONS[ $key ] ) . ' ; got: ' . ( array() === $got ? '(none)' : implode( ' ', $got ) ) . '); update the const and the source marker together.' ); + } + $dropStart = $collected[ count( $collected ) - 1 ][0]; + if ( T_WHITESPACE === $tokens[ $dropStart - 1 ][0] && false !== strpos( $tokens[ $dropStart - 1 ][1], "\n" ) ) { + $dropStart--; // swallow the line break separating the dropped block from the element above + } + $drops[] = array( 'start' => $dropStart, 'end' => $e['comma'] ?? $e['end'] ); + } + if ( array() === $drops ) { + return $metaExpr; + } + $out = ''; + for ( $j = 1, $n = count( $tokens ); $j < $n; $j++ ) { // token 0 is the '= $d['start'] && $j <= $d['end'] ) { + $drop = true; + break; + } + } + if ( ! $drop ) { + $out .= $tokens[ $j ][1]; + } + } + return $out; +} + /* --------------------------------------------------------------------- * REVERSE transform * ------------------------------------------------------------------- */ @@ -1379,6 +1639,11 @@ function transform_reverse( string $coreText ): string { } $authors['ability_meta'] = $mkret( 'meta' ); + // The package's marked meta accommodations (PKG_META_ACCOMMODATIONS) keep regenerated + // backports identical to the shipped files: re-inject the mapped keys (with their + // marker comment lines) when the fixture's meta lacks them. + $authors['ability_meta'] = pkg_meta_inject_accommodations( $authors['ability_meta'] ); + $rc = 'return array();'; if ( isset( $entries['required_capabilities'] ) ) { $rc = 'return ' . reindent( $entries['required_capabilities'], -2 ) . ';'; From 3afb1e7f9483e7f0fbea3e545a2e93596c900bd8 Mon Sep 17 00:00:00 2001 From: Nik McLaughlin <72171383+nikmclaughlin@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:53:24 -0700 Subject: [PATCH 3/3] Sync the content/users trio fixtures and ports to trunk (r65075/r65002) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PLAN-ai-plugin-poc.md sec. 7.0b (from the sec. 10.7 preflight stop-and-report): our trunk fixture snapshots predated two core changes the AI plugin's copies already carry — content r65075 (author-visibility rework) and users r65002 (registered/dotted-fields rework). Refresh both fixtures from today's wordpress-develop trunk (settings was already current), regenerate src/Content/Content_Query.php and src/Users/Users_Query.php verbatim through coreify --reverse (the sec. 7.0 show_in_rest '// Package:' meta accommodation survives regeneration by design; PKG_META_ACCOMMODATIONS markers unchanged), and update the tests for core's new shapes. Sync deltas, verified hunk-by-hunk against the expected set: - content: get_visible_author() memoized per query via $visible_authors, an edit_user capability branch, the posts count restricted to show_in_abilities- exposed viewable post types, the author field nulling name/slug for authors the current user may not see; where.author_slug became a where.author object (id/slug) with where[author]/where[author][id]/where[author][slug] error paths and empty-page (not error) answers for authors that name no visible user; date.local became date.site; trunk's array_all()/array_any() (core's compat polyfills cover PHP < 8.4; the users profile gains the DateTimeZone import). - users: registered_date became the registered.site/registered.gmt object, with the get_field_paths()/is_field_requested() dotted projection and the dotted fields enum. Tests adapt to the new shapes (registered.site/gmt, dotted fields enum, author object filter and its error paths) and add coverage for the visible-author rule (memoization, the edit_user branch, filter matching) and the users dotted projection — adapted, never deleted. Settings is untouched: its fixture is byte-identical to today's trunk. Stacked on #15 (add/trio-show-in-rest) and #12 (add/mcp-public-meta), for the ai PoC to pin its integration ref on this head. --- CHANGELOG.md | 30 ++ src/Content/Content_Query.php | 263 ++++++++++------ src/Users/Users_Query.php | 198 ++++++++---- tests/Abilities/ContentQueryTest.php | 294 +++++++++++++++++- tests/Abilities/UsersQueryTest.php | 72 ++++- .../abilities/class-wp-abilities-content.php | 262 ++++++++++------ .../abilities/class-wp-abilities-users.php | 199 ++++++++---- tools/coreify.php | 2 +- 8 files changed, 1001 insertions(+), 319 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ace465..761a96b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -177,6 +177,36 @@ The entries below describe the current prototype state._ `--reverse` re-injects the flag into regenerated backports, forward drops it behind `// Package:`-verified markers), and the trio tests pin `meta.show_in_rest === true` with the high-level `public` meta unchanged. +### Changed + +- `core/users-query` (**breaking**, core trunk r65002): the flat `registered_date` + output field became a `registered` object with dotted sub-fields — + `registered.site` (the site's timezone) and `registered.gmt` (UTC), both + null-on-unusable-stored-date ISO 8601 strings — and the `fields` input now + accepts dotted paths via `get_field_paths()`/`is_field_requested()` + (`rest_is_field_included()`): requesting `registered` returns both sub-fields, + a sub-field path returns only that one, and the `fields` input `enum` lists + the dotted paths. Synced with the AI plugin's 1.5.0 copies; the fixture and + the backport are regenerated through `tools/coreify.php --reverse`. +- `core/content-query` (core trunk r65075-era): the author-visibility rework — + `get_visible_author()` resolves an author through one memoized rule per query + (`$visible_authors`), with an `edit_user` capability branch and the posts + count restricted to publicly viewable post types exposed through + `show_in_abilities`; the `author` field nulls `name`/`slug` when the current + user may not see the author. The `where.author_slug` string filter became a + `where.author` object with `id`/`slug` (error paths `where[author]`, + `where[author][id]`, `where[author][slug]`); a slug that names no user, a user + the current user may not see, or an `id`/`slug` pair naming different users + match no post (an empty page, not an error). The `date.local` output path + became `date.site`, and the class ships trunk's `array_all()`/`array_any()` + calls (runtime-safe: core's own compat polyfills cover PHP < 8.4 — the plugin + copies swap in loops only against its static-analysis stubs). +- Trunk fixture snapshots: content and users refreshed from today's + wordpress-develop trunk (the r65075-/r65002-era classes; settings was already + current) with refreshed provenance headers, regenerating both backports + through `coreify --reverse` — the §7.0 `show_in_rest` `// Package:` meta + accommodation survives regeneration by design. + ### Removed - `wp/post-create` — the self-authored experimental write-ability prototype diff --git a/src/Content/Content_Query.php b/src/Content/Content_Query.php index d641156..b514d06 100644 --- a/src/Content/Content_Query.php +++ b/src/Content/Content_Query.php @@ -24,6 +24,9 @@ */ declare( strict_types = 1 ); + + + namespace WordPress\Abilities\Content; use DateTimeZone; @@ -58,6 +61,7 @@ * @access private */ final class Content_Query extends Abstract_Core_Ability { + /** * The ability category used for content abilities. * @@ -114,7 +118,13 @@ final class Content_Query extends Abstract_Core_Ability { * @var list */ private const LOOP_GLOBALS = array( 'post', 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' ); - + /** + * Whether each author seen in the current query has posts the current user may read. + * + * @since 7.2.0 + * @var array + */ + private $visible_authors = array(); /** * The canonical ability name, as registered in core with wp_register_ability(). * @@ -253,6 +263,7 @@ protected function ability_meta(): array { protected function required_capabilities(): array { return array(); } + /** * Permission callback for the `core/content-query` ability. * @@ -304,13 +315,10 @@ private function check_permission( $input = array() ): bool { * @return bool True if the requested statuses may be queried. */ private function can_query_statuses( array $where, WP_Post_Type $post_type_object ): bool { - foreach ( $this->get_requested_statuses( $where ) as $status ) { - if ( ! $this->can_query_status( $status, $post_type_object ) ) { - return false; - } - } - - return true; + return array_all( + $this->get_requested_statuses( $where ), + fn( $status ) => $this->can_query_status( $status, $post_type_object ) + ); } /** @@ -427,6 +435,9 @@ private function execute_content_query( $input = array() ) { $input = rest_sanitize_object( $input ); $fields = $this->normalize_fields( $input ); + // The author visibility memo is per query; see get_visible_author(). + $this->visible_authors = array(); + /* * A `where` that is not an object cannot be honored. Reject it rather than reading it * as no filter at all. @@ -480,24 +491,75 @@ private function execute_content_query( $input = array() ) { } } - $author = null; - if ( isset( $where['author_slug'] ) ) { + /* + * The author filter is an object with an `id` or a `slug`, the keys the `author` + * field returns. Null, int, or false: no filter, the user ID to query, or a filter + * that names no user, which matches no post (see below). + */ + $author_id = null; + if ( array_key_exists( 'author', $where ) ) { if ( ! post_type_supports( $post_type, 'author' ) ) { return $this->invalid_filter_error( - 'where[author_slug]', + 'where[author]', /* translators: %s: Parameter. */ - sprintf( __( 'The %s filter is only supported for post types that support authors.' ), 'author_slug' ) + sprintf( __( 'The %s filter is only supported for post types that support authors.' ), 'author' ) ); } - $author = $this->get_author_by_slug( $where['author_slug'], $post_type_object ); - if ( ! $author ) { + /* + * An object without `id` or `slug`, such as `{}` or an empty string, and one with + * an unknown key, such as a list or a misspelled property, name no user and must not + * fall through to an unrestricted query, like an empty `ids` filter. + */ + $author_filter = $this->get_input_object( $where, 'author' ); + if ( empty( $author_filter ) || ! empty( array_diff_key( $author_filter, array_flip( array( 'id', 'slug' ) ) ) ) ) { return $this->invalid_filter_error( - 'where[author_slug]', + 'where[author]', /* translators: %s: Parameter. */ - sprintf( __( 'The %s filter must be the slug of an existing user.' ), 'author_slug' ) + sprintf( __( 'The %s filter must be an object with an id or a slug.' ), 'author' ) ); } + + /* + * An `id` of 0 must not reach the query: WP_Query reads `author => 0` as no author + * filter, which would return every post of the type. + */ + if ( array_key_exists( 'id', $author_filter ) ) { + $author_id = $this->parse_filter_int( $author_filter['id'], 1 ); + if ( null === $author_id ) { + return $this->invalid_filter_error( + 'where[author][id]', + /* translators: %s: Parameter. */ + sprintf( __( 'The %s ID must be a positive integer.' ), 'author' ) + ); + } + } + + if ( array_key_exists( 'slug', $author_filter ) ) { + if ( ! is_string( $author_filter['slug'] ) || '' === $author_filter['slug'] ) { + return $this->invalid_filter_error( + 'where[author][slug]', + /* translators: %s: Parameter. */ + sprintf( __( 'The %s slug must be a non-empty string.' ), 'author' ) + ); + } + + /* + * The slug is looked up as given, like the `slug` of the users endpoint: the + * collation of the users table decides whether the case matters. A slug that + * names no user, or a user the current user may not see, or names another user + * than `id`, matches no post, as a post must match every given filter. The + * visibility rule is the one the `author` field follows, so a slug the field + * withholds cannot be confirmed through the filter. + */ + $user = get_user_by( 'slug', $author_filter['slug'] ); + $user = $user ? $this->get_visible_author( $user->ID ) : null; + if ( ! $user || ( null !== $author_id && $user->ID !== $author_id ) ) { + $author_id = false; + } else { + $author_id = $user->ID; + } + } } /* @@ -591,14 +653,24 @@ private function execute_content_query( $input = array() ) { $query_args['post_name__in'] = $slugs; } - if ( null !== $author ) { - $query_args['author'] = $author->ID; + if ( is_int( $author_id ) ) { + $query_args['author'] = $author_id; } if ( null !== $parent ) { $query_args['post_parent'] = $parent; } + /* + * A slug that names no user or a user the current user may not see, or an ID and a slug + * that name different users, match no post, like IDs and slugs that name no post, rather + * than failing the query. An `id` is not looked up: the query matches the stored author + * ID, so the posts of a deleted user still match it. + */ + if ( false === $author_id ) { + return $this->prepare_output( array(), 0, 0 ); + } + $query = new WP_Query( $query_args ); $total = $this->get_query_total( $query, $query_args, $page ); @@ -726,13 +798,10 @@ private function get_query_total( WP_Query $query, array $query_args, int $page * @return bool True when post meta and term caches should be primed. */ private function should_prime_post_caches( array $fields ): bool { - foreach ( self::CACHE_PRIMING_FIELDS as $field ) { - if ( $this->is_field_requested( $field, $fields ) ) { - return true; - } - } - - return false; + return array_any( + self::CACHE_PRIMING_FIELDS, + fn( $field ) => $this->is_field_requested( $field, $fields ) + ); } /** @@ -753,50 +822,6 @@ private function is_field_requested( string $path, array $fields ): bool { return rest_is_field_included( $path, $fields ); } - /** - * Looks up the user an author slug names. - * - * The slug is the user's nicename, which the REST API users endpoint returns as `slug`. It is - * looked up as given, like that endpoint's `slug` filter, so the database collation decides - * whether a variant in another case matches. A user the current user may not see is reported - * like a missing one. The current user can see themselves, any user of the site when they can - * list users, and authors with posts in a publicly viewable post type. A user who can edit - * others' posts of the post type can also see any user of the site, since they may make any of - * them the author, so for them the lookup does tell whether such an account exists. - * - * On multisite the lookup searches the whole network, so posts by authors who are not - * members of the site, such as super admins, can still be filtered. Those users are only - * visible as the current user or as authors with posts in a publicly viewable post type, so - * the lookup does not tell whether an account exists elsewhere on the network. - * - * @since 7.2.0 - * - * @param mixed $slug The author slug. - * @param WP_Post_Type $post_type_object The post type the author is looked up for. - * @return WP_User|null The user, or null when the slug does not name a visible user. - */ - private function get_author_by_slug( $slug, WP_Post_Type $post_type_object ): ?WP_User { - $user = is_string( $slug ) ? get_user_by( 'slug', $slug ) : false; - if ( ! $user ) { - return null; - } - - if ( get_current_user_id() === $user->ID ) { - return $user; - } - - // The capabilities only reveal users of the site, not of the whole network. - if ( is_user_member_of_blog( $user->ID ) - && ( current_user_can( 'list_users' ) || current_user_can( $post_type_object->cap->edit_others_posts ) ) - ) { - return $user; - } - - $public_post_types = array_values( array_filter( get_post_types(), 'is_post_type_viewable' ) ); - - return ! empty( $public_post_types ) && count_user_posts( $user->ID, $public_post_types ) > 0 ? $user : null; - } - /** * Returns a post type exposed through the Abilities API. * @@ -974,12 +999,12 @@ private function get_post_properties(): array { 'type' => 'object', 'additionalProperties' => false, 'properties' => array( - 'local' => array( + 'site' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( "The publication date, in ISO 8601 format using the site's timezone. Null when the date cannot be resolved." ), ), - 'gmt' => array( + 'gmt' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( 'The publication date, in ISO 8601 format as GMT. Null when the date cannot be resolved.' ), @@ -991,12 +1016,12 @@ private function get_post_properties(): array { 'type' => 'object', 'additionalProperties' => false, 'properties' => array( - 'local' => array( + 'site' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( "The last modified date, in ISO 8601 format using the site's timezone. Null when the date cannot be resolved." ), ), - 'gmt' => array( + 'gmt' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( 'The last modified date, in ISO 8601 format as GMT. Null when the date cannot be resolved.' ), @@ -1071,15 +1096,15 @@ private function get_post_properties(): array { 'properties' => array( 'id' => array( 'type' => 'integer', - 'description' => __( 'The user ID of the author.' ), + 'description' => __( 'The user ID of the author, as the `author.id` filter takes it.' ), ), 'name' => array( 'type' => array( 'string', 'null' ), - 'description' => __( "The author's display name, as the REST API users endpoint returns it in `name`. Null when the author no longer exists." ), + 'description' => __( "The author's display name, as the REST API users endpoint returns it in `name`. Null when the author no longer exists or the current user may not see them." ), ), 'slug' => array( 'type' => array( 'string', 'null' ), - 'description' => __( "The author's user slug (nicename), as the REST API users endpoint returns it in `slug`, and as the `author_slug` filter takes it. Null when the author no longer exists." ), + 'description' => __( "The author's user slug (nicename), as the REST API users endpoint returns it in `slug`, and as the `author.slug` filter takes it. Null when the author no longer exists or the current user may not see them." ), ), ), 'description' => __( 'The post author. Present when the post type supports authors.' ), @@ -1145,7 +1170,7 @@ private function get_fields_input_schema(): array { * The input has three members: `where` selects the posts, `fields` selects the fields * returned for each post, and `pagination` selects the page of results. `where` holds * the post type to query in `type`, and any of the filters `ids`, `slugs`, `status`, - * `author_slug`, and `parent`, which all combine. Every object sets + * `author`, and `parent`, which all combine. Every object sets * `additionalProperties: false`, so an unknown key, such as a misspelled filter, fails * validation instead of being silently ignored. * @@ -1166,12 +1191,12 @@ private function get_content_query_input_schema( array $post_types, array $statu 'additionalProperties' => false, 'required' => array( 'type' ), 'properties' => array( - 'type' => array( + 'type' => array( 'type' => 'string', 'enum' => $post_types, 'description' => __( 'Post type to query for readable posts.' ), ), - 'ids' => array( + 'ids' => array( 'type' => 'array', 'uniqueItems' => true, 'minItems' => 1, @@ -1182,7 +1207,7 @@ private function get_content_query_input_schema( array $post_types, array $statu ), 'description' => __( 'Limit the query to these post IDs. The order of the IDs does not affect the order of the results. If `pagination.per_page` is omitted, every matching post is returned on the first page.' ), ), - 'slugs' => array( + 'slugs' => array( 'type' => 'array', 'uniqueItems' => true, 'minItems' => 1, @@ -1193,7 +1218,7 @@ private function get_content_query_input_schema( array $post_types, array $statu ), 'description' => __( 'Limit the query to posts with these slugs. Each slug is sanitized as a post slug is, so `Hello-World` matches `hello-world`. A slug can match several posts, such as pages under different parents, and every match is returned. The order of the slugs does not affect the order of the results. If `pagination.per_page` is omitted, every matching post is returned on the first page, up to the `per_page` maximum.' ), ), - 'status' => array( + 'status' => array( 'type' => 'array', 'uniqueItems' => true, 'minItems' => 1, @@ -1203,18 +1228,31 @@ private function get_content_query_input_schema( array $post_types, array $statu ), 'description' => __( 'Filter readable posts by one or more post statuses. Defaults to publish, or, when `ids` or `slugs` is given, to every status the current user may query. Statuses that are not publicly viewable, other than private, require edit access.' ), ), - 'author_slug' => array( - 'type' => 'string', - 'minLength' => 1, - 'description' => __( "Filter by the author's user slug (nicename), as the REST API users endpoint returns it in `slug`. Only supported for post types that support authors." ), + 'author' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + 'description' => __( 'The user ID of the author, as `author.id` is returned.' ), + ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( "The author's user slug (nicename), as `author.slug` is returned and as the REST API users endpoint returns it in `slug`." ), + ), + ), + 'description' => __( 'Filter by the post author, given as the `id` or the `slug` the `author` field of a post returns. An `id` matches the author ID stored on the post, even when that user no longer exists. A `slug` that names no user or a user the current user may not see, as the `author` field reports them, or an `id` and a `slug` that name different users, match no post. Only supported for post types that support authors.' ), ), - 'parent' => array( + 'parent' => array( 'type' => 'integer', 'minimum' => 0, 'description' => __( 'Filter by parent post ID. Only supported for hierarchical post types. Use 0 for top-level posts.' ), ), ), - 'description' => __( 'Selects the posts to return: the readable posts of a `type`, filtered by any of `ids`, `slugs`, `status`, `author_slug`, and `parent`. A post must match every given filter.' ), + 'description' => __( 'Selects the posts to return: the readable posts of a `type`, filtered by any of `ids`, `slugs`, `status`, `author`, and `parent`. A post must match every given filter.' ), ), 'fields' => $this->get_fields_input_schema(), 'pagination' => array( @@ -1305,6 +1343,42 @@ private function get_content_query_output_schema(): array { ); } + /** + * Returns a user when the current user may see them as an author. + * + * The current user may see themselves, the users they can edit, every user when they can + * list users, and otherwise the authors of posts they can read in a publicly viewable post + * type exposed to abilities: this ability returns those posts with their author, so the + * author is already in view. Which post types the REST API exposes plays no part. A user + * the current user may not see is reported like a missing one. + * + * The `author` field and the `author` slug filter share this rule, so the filter never + * confirms a slug the field withholds. The post count is kept per author for the query, + * since count_user_posts() is not cached. + * + * @since 7.2.0 + * + * @param int $user_id The user ID. + * @return WP_User|null The user, or null when they no longer exist or may not be seen. + */ + private function get_visible_author( int $user_id ): ?WP_User { + $user = get_userdata( $user_id ); + if ( ! $user ) { + return null; + } + + if ( get_current_user_id() === $user_id || current_user_can( 'list_users' ) || current_user_can( 'edit_user', $user_id ) ) { + return $user; + } + + if ( ! isset( $this->visible_authors[ $user_id ] ) ) { + $post_types = array_values( array_filter( get_post_types( array( 'show_in_abilities' => true ), 'names' ), 'is_post_type_viewable' ) ); + $this->visible_authors[ $user_id ] = (int) count_user_posts( $user_id, $post_types ) > 0; + } + + return $this->visible_authors[ $user_id ] ? $user : null; + } + /** * Formats a post into the ability output shape. * @@ -1397,8 +1471,8 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit foreach ( array( 'date', 'modified' ) as $field ) { $dates = array(); - if ( $this->is_field_requested( "{$field}.local", $fields ) ) { - $dates['local'] = $this->format_date( $post, $field, false ); + if ( $this->is_field_requested( "{$field}.site", $fields ) ) { + $dates['site'] = $this->format_date( $post, $field, false ); } if ( $this->is_field_requested( "{$field}.gmt", $fields ) ) { $dates['gmt'] = $this->format_date( $post, $field, true ); @@ -1450,7 +1524,10 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit } if ( $this->is_field_requested( 'author', $fields ) && post_type_supports( $post_type, 'author' ) ) { - $user = get_userdata( (int) $post->post_author ); + $user = null; + if ( $this->is_field_requested( 'author.name', $fields ) || $this->is_field_requested( 'author.slug', $fields ) ) { + $user = $this->get_visible_author( (int) $post->post_author ); + } $author = array(); if ( $this->is_field_requested( 'author.id', $fields ) ) { $author['id'] = (int) $post->post_author; @@ -1483,8 +1560,8 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit * * @since 7.2.0 * - * @param mixed $required Whether the post currently requires a password. - * @param mixed $post The post being checked; a WP_Post when invoked by the core filter. + * @param bool $required Whether the post currently requires a password. + * @param WP_Post|null $post The post being checked, or null if no post is found. * @return bool Whether the post still requires a password. */ private function allow_password_content( $required, $post ): bool { @@ -1521,7 +1598,7 @@ private function get_title( WP_Post $post ): string { * A title filter that returns a non-string would fail the return type, so guard * it as the excerpt and content are. */ - return is_string( $title ) ? $title : ''; // @phpstan-ignore function.alreadyNarrowedType (WP stubs type get_the_title() as string; trunk keeps the runtime guard against a misbehaving title filter.) + return is_string( $title ) ? $title : ''; // @phpstan-ignore function.alreadyNarrowedType (WP stubs type get_the_title() as string; trunk keeps the is_string guard) } finally { remove_filter( 'protected_title_format', $strip ); remove_filter( 'private_title_format', $strip ); diff --git a/src/Users/Users_Query.php b/src/Users/Users_Query.php index 7b63f1d..b541df3 100644 --- a/src/Users/Users_Query.php +++ b/src/Users/Users_Query.php @@ -14,8 +14,10 @@ */ declare( strict_types = 1 ); + namespace WordPress\Abilities\Users; +use DateTimeZone; use WP_Error; use WP_User; use WP_User_Query; @@ -90,7 +92,6 @@ final class Users_Query extends Abstract_Core_Ability { 'slug', 'avatar_urls', ); - /** * The canonical ability name. * @@ -398,11 +399,12 @@ private function get_public_post_types(): array { } /** - * Returns the requested fields, or a lean default set when none are given. + * Returns the requested field paths, or a lean default set when none are given. * * An empty or absent `fields` value selects a lean set of common read fields. - * Otherwise the requested fields are returned. The input schema has already - * validated the names against the supported set before the ability executes. + * Otherwise the requested paths are returned. The input schema has already + * validated them against the paths from {@see self::get_field_paths()} before the + * ability executes, and {@see self::format_user()} ignores any other path. * * The `id` field is always included, matching the REST users controller * where `id` is present in every context. This also guarantees the result @@ -411,7 +413,7 @@ private function get_public_post_types(): array { * @since 7.2.0 * * @param array $input The ability input. - * @return string[] List of requested field names. + * @return string[] List of requested field paths. */ private function normalize_fields( array $input ): array { $fields = isset( $input['fields'] ) ? $this->normalize_string_list( $input['fields'] ) : array(); @@ -430,8 +432,9 @@ private function normalize_fields( array $input ): array { * Returns the user field definitions, keyed by field name in output order. * * This is the single source of truth for the ability's user fields: the output - * schema uses the definitions directly, while the input schema and field - * normalization use the keys. The field set is deliberately unconditional: + * schema uses the definitions directly, while the input schema `fields` enum lists + * each field, followed by the path of each of its sub-fields, such as + * `registered.gmt`. The field set is deliberately unconditional: * the registered schemas are a registration-time snapshot, so conditional * availability (such as `avatar_urls` honoring the `show_avatars` option) is * enforced per call in {@see self::format_user()} instead of here, where the @@ -443,19 +446,19 @@ private function normalize_fields( array $input ): array { */ private function get_user_properties(): array { return array( - 'id' => array( + 'id' => array( 'type' => 'integer', 'description' => __( 'The user ID.' ), ), - 'name' => array( + 'name' => array( 'type' => 'string', 'description' => __( 'The display name for the user.' ), ), - 'description' => array( + 'description' => array( 'type' => 'string', 'description' => __( 'Description of the user. Present when the current user can view it.' ), ), - 'url' => array( + 'url' => array( /* * Unlike the REST users controller, `url` declares no `uri` format. It is * empty for users without a website, and clients that check formats, @@ -465,16 +468,16 @@ private function get_user_properties(): array { 'type' => 'string', 'description' => __( 'URL of the user. Present when the current user can view it.' ), ), - 'link' => array( + 'link' => array( 'type' => 'string', 'format' => 'uri', 'description' => __( 'Author archive URL for the user.' ), ), - 'slug' => array( + 'slug' => array( 'type' => 'string', 'description' => __( 'An alphanumeric identifier for the user.' ), ), - 'avatar_urls' => array( + 'avatar_urls' => array( 'type' => 'object', 'description' => __( 'Avatar URLs for the user, keyed by image size in pixels. A size is null when no avatar URL can be resolved for it. Present when the show_avatars option is enabled.' ), 'additionalProperties' => array( @@ -482,37 +485,49 @@ private function get_user_properties(): array { 'format' => 'uri', ), ), - 'username' => array( + 'username' => array( 'type' => 'string', 'description' => __( 'Login name for the user. Present when the current user can view it.' ), ), - 'email' => array( + 'email' => array( 'type' => array( 'string', 'null' ), 'format' => 'email', 'description' => __( 'The email address for the user. Null when the user has no stored address, or when the stored address is not a valid email. Present when the current user can view it.' ), ), - 'first_name' => array( + 'first_name' => array( 'type' => 'string', 'description' => __( 'First name for the user. Present when the current user can view it.' ), ), - 'last_name' => array( + 'last_name' => array( 'type' => 'string', 'description' => __( 'Last name for the user. Present when the current user can view it.' ), ), - 'nickname' => array( + 'nickname' => array( 'type' => 'string', 'description' => __( 'The nickname for the user. Present when the current user can view it.' ), ), - 'locale' => array( + 'locale' => array( 'type' => 'string', 'description' => __( 'Locale for the user. Present when the current user can view it.' ), ), - 'registered_date' => array( - 'type' => array( 'string', 'null' ), - 'format' => 'date-time', - 'description' => __( 'Registration date for the user. Null when the stored date is not a valid date. Present when the current user can view it.' ), + 'registered' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'site' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + 'description' => __( "The registration date, in ISO 8601 format using the site's timezone. Null when the stored date is not a valid date." ), + ), + 'gmt' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + 'description' => __( 'The registration date, in ISO 8601 format as GMT. Null when the stored date is not a valid date.' ), + ), + ), + 'description' => __( 'The registration date for the user. Present when the current user can view it.' ), ), - 'roles' => array( + 'roles' => array( 'type' => 'array', 'description' => __( 'Roles assigned to the user. Present when the current user can view them.' ), /* @@ -530,6 +545,47 @@ private function get_user_properties(): array { ); } + /** + * Returns the field paths the `fields` input accepts, in output order. + * + * Each user field is followed by the path of each sub-field its definition declares, + * such as `registered`, `registered.site` and `registered.gmt`. Requesting a field + * returns all of its sub-fields, while a sub-field path returns only that sub-field. + * + * @since 7.2.0 + * + * @return string[] The field paths. + */ + private function get_field_paths(): array { + $paths = array(); + foreach ( $this->get_user_properties() as $name => $schema ) { + $paths[] = $name; + + foreach ( array_keys( $schema['properties'] ?? array() ) as $sub_field ) { + $paths[] = "{$name}.{$sub_field}"; + } + } + + return $paths; + } + + /** + * Checks whether a field path is requested. + * + * A field such as `registered` is requested when it or one of its paths, such as + * `registered.gmt`, is requested, and a path such as `registered.gmt` is requested + * when it or its whole field is. + * + * @since 7.2.0 + * + * @param string $path The field path, such as `registered` or `registered.gmt`. + * @param string[] $fields The requested field paths. + * @return bool Whether the field path is requested. + */ + private function is_field_requested( string $path, array $fields ): bool { + return rest_is_field_included( $path, $fields ); + } + /** * Normalizes a mixed value into a list of user IDs. * @@ -703,9 +759,9 @@ private function get_users_query_input_schema(): array { 'uniqueItems' => true, 'items' => array( 'type' => 'string', - 'enum' => array_keys( $this->get_user_properties() ), + 'enum' => $this->get_field_paths(), ), - 'description' => __( 'Limit each returned user to these fields. If omitted or empty, a lean set of common read fields is returned. The `id` field is always included, and fields the current user cannot view are omitted rather than causing an error.' ), + 'description' => __( 'Limit each returned user to these fields. A field such as `registered` returns all of its sub-fields, while a path such as `registered.gmt` returns only that sub-field. If omitted or empty, a lean set of common read fields is returned. The `id` field is always included, and fields the current user cannot view are omitted rather than causing an error.' ), ), 'pagination' => array( 'type' => 'object', @@ -782,47 +838,45 @@ private function get_users_query_output_schema(): array { /** * Formats a user into the ability output shape. * - * Only the requested fields the current user can see are included, except - * `id`, which {@see self::normalize_fields()} always requests. + * Fields are selected with {@see self::is_field_requested()}, so `registered` returns + * both of its sub-fields, while `registered.site` or `registered.gmt` returns only that + * one. Only the requested fields the current user can see are included, except `id`, + * which {@see self::normalize_fields()} always requests. * * @since 7.2.0 * * @param WP_User $user The user object. - * @param string[] $fields The requested field names. + * @param string[] $fields The requested field paths. * @return array The formatted user data. */ private function format_user( WP_User $user, array $fields ): array { - $fields_requested = static function ( string $field ) use ( $fields ): bool { - return in_array( $field, $fields, true ); - }; - $can_view_sensitive = get_current_user_id() === $user->ID || current_user_can( 'edit_user', $user->ID ); $data = array(); - if ( $fields_requested( 'id' ) ) { + if ( $this->is_field_requested( 'id', $fields ) ) { $data['id'] = $user->ID; } - if ( $fields_requested( 'name' ) ) { + if ( $this->is_field_requested( 'name', $fields ) ) { $data['name'] = (string) $user->display_name; } - if ( $fields_requested( 'description' ) ) { + if ( $this->is_field_requested( 'description', $fields ) ) { $data['description'] = (string) $user->description; } - if ( $fields_requested( 'url' ) ) { + if ( $this->is_field_requested( 'url', $fields ) ) { $data['url'] = (string) $user->user_url; } - if ( $fields_requested( 'link' ) ) { + if ( $this->is_field_requested( 'link', $fields ) ) { $data['link'] = (string) get_author_posts_url( $user->ID, $user->user_nicename ); } - if ( $fields_requested( 'slug' ) ) { + if ( $this->is_field_requested( 'slug', $fields ) ) { $data['slug'] = (string) $user->user_nicename; } /* * The schemas always declare avatar_urls; availability is enforced here, * since the option can change after the schemas are registered. */ - if ( $fields_requested( 'avatar_urls' ) && get_option( 'show_avatars' ) ) { + if ( $this->is_field_requested( 'avatar_urls', $fields ) && get_option( 'show_avatars' ) ) { $data['avatar_urls'] = array_map( static function ( $url ) { return is_string( $url ) ? $url : null; @@ -832,32 +886,34 @@ static function ( $url ) { } if ( $can_view_sensitive ) { - if ( $fields_requested( 'username' ) ) { + if ( $this->is_field_requested( 'username', $fields ) ) { $data['username'] = (string) $user->user_login; } - if ( $fields_requested( 'email' ) ) { + if ( $this->is_field_requested( 'email', $fields ) ) { $data['email'] = is_email( $user->user_email ) ? (string) $user->user_email : null; } - if ( $fields_requested( 'first_name' ) ) { + if ( $this->is_field_requested( 'first_name', $fields ) ) { $data['first_name'] = (string) $user->first_name; } - if ( $fields_requested( 'last_name' ) ) { + if ( $this->is_field_requested( 'last_name', $fields ) ) { $data['last_name'] = (string) $user->last_name; } - if ( $fields_requested( 'nickname' ) ) { + if ( $this->is_field_requested( 'nickname', $fields ) ) { $data['nickname'] = (string) $user->nickname; } - if ( $fields_requested( 'locale' ) ) { + if ( $this->is_field_requested( 'locale', $fields ) ) { $data['locale'] = (string) get_user_locale( $user ); } - if ( $fields_requested( 'registered_date' ) ) { - /* - * The zero date, the column default, formats with a negative year that the - * `date-time` format rejects, so it is reported as null, like an unusable email. - */ - $registered_timestamp = strtotime( $user->user_registered ); - $registered_date = false !== $registered_timestamp ? gmdate( 'c', $registered_timestamp ) : ''; - $data['registered_date'] = rest_parse_date( $registered_date ) ? $registered_date : null; + + $registered = array(); + if ( $this->is_field_requested( 'registered.site', $fields ) ) { + $registered['site'] = $this->format_registered_date( $user, wp_timezone() ); + } + if ( $this->is_field_requested( 'registered.gmt', $fields ) ) { + $registered['gmt'] = $this->format_registered_date( $user, new DateTimeZone( 'UTC' ) ); + } + if ( ! empty( $registered ) ) { + $data['registered'] = $registered; } } @@ -868,13 +924,43 @@ static function ( $url ) { * matching the REST users controller, where `roles` is an edit-context * field and rows the caller cannot edit are dropped from collections. */ - if ( $fields_requested( 'roles' ) && $can_view_sensitive ) { + if ( $this->is_field_requested( 'roles', $fields ) && $can_view_sensitive ) { $data['roles'] = array_values( $user->roles ); } return $data; } + /** + * Formats the user's registration date as an ISO 8601 string in a timezone. + * + * The `user_registered` column holds the date in GMT, so it is parsed as UTC + * whatever the PHP default timezone is, then converted to the given timezone. + * + * @since 7.2.0 + * + * @param WP_User $user The user object. + * @param DateTimeZone $timezone The timezone to format the date in. + * @return string|null The ISO 8601 date, or null when the stored date is not a valid date. + */ + private function format_registered_date( WP_User $user, DateTimeZone $timezone ): ?string { + $datetime = date_create_immutable_from_format( 'Y-m-d H:i:s', (string) $user->user_registered, new DateTimeZone( 'UTC' ) ); + if ( ! $datetime ) { + return null; + } + + /* + * A malformed stored date can still parse, since out-of-range parts roll over: the + * zero date, the column default, formats with a negative year, and converting a + * date at either end of the range can push its year outside four digits. The + * `date-time` format rejects these, which would fail output validation for the + * whole call, so they are reported as null too, like an unusable email. + */ + $date = $datetime->setTimezone( $timezone )->format( 'c' ); + + return false !== rest_parse_date( $date ) ? $date : null; + } + /** * Builds the ability output for a page of formatted users. * diff --git a/tests/Abilities/ContentQueryTest.php b/tests/Abilities/ContentQueryTest.php index 4aff438..37d2444 100644 --- a/tests/Abilities/ContentQueryTest.php +++ b/tests/Abilities/ContentQueryTest.php @@ -21,6 +21,7 @@ use WordPress\Abilities\Support\Features; use WP_Abilities_Registry; use WP_Error; +use WP_User; use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** @@ -77,6 +78,11 @@ public function tear_down(): void { wp_delete_user( (int) $id ); } } + // Remove any previously persisted cq_usereditor test role (an earlier version of + // these tests created it via add_role(), which writes to the site's role option). + if ( wp_roles()->get_role( 'cq_usereditor' ) ) { + remove_role( 'cq_usereditor' ); + } $this->user_ids = array(); $this->post_ids = array(); @@ -246,12 +252,18 @@ public function test_input_schema_matches_trunk(): void { self::assertSame( array( 'where' ), $schema['required'] ); $where = $schema['properties']['where']; - self::assertSame( array( 'type', 'ids', 'slugs', 'status', 'author_slug', 'parent' ), array_keys( $where['properties'] ) ); + self::assertSame( array( 'type', 'ids', 'slugs', 'status', 'author', 'parent' ), array_keys( $where['properties'] ) ); self::assertSame( array( 'type' ), $where['required'] ); self::assertSame( array_values( get_post_types( array( 'show_in_abilities' => true ) ) ), $where['properties']['type']['enum'] ); self::assertSame( 100, $where['properties']['ids']['maxItems'] ); self::assertSame( 100, $where['properties']['slugs']['maxItems'] ); self::assertSame( array_values( get_post_stati( array( 'internal' => false ) ) ), $where['properties']['status']['items']['enum'] ); + self::assertSame( 'object', $where['properties']['author']['type'], 'r65075: the author filter is an id/slug object now.' ); + self::assertFalse( $where['properties']['author']['additionalProperties'] ); + self::assertSame( 1, $where['properties']['author']['minProperties'] ); + self::assertSame( 'integer', $where['properties']['author']['properties']['id']['type'] ); + self::assertSame( 1, $where['properties']['author']['properties']['id']['minimum'] ); + self::assertSame( 1, $where['properties']['author']['properties']['slug']['minLength'] ); self::assertSame( array( @@ -259,10 +271,10 @@ public function test_input_schema_matches_trunk(): void { 'type', 'status', 'date', - 'date.local', + 'date.site', 'date.gmt', 'modified', - 'modified.local', + 'modified.site', 'modified.gmt', 'slug', 'link', @@ -312,7 +324,7 @@ public function test_output_schema_matches_trunk(): void { ); self::assertSame( array( 'id' ), $post['required'] ); self::assertSame( array( 'total', 'total_pages' ), array_keys( $schema['properties']['pagination']['properties'] ) ); - self::assertSame( array( 'local', 'gmt' ), array_keys( $post['properties']['date']['properties'] ) ); + self::assertSame( array( 'site', 'gmt' ), array_keys( $post['properties']['date']['properties'] ), 'r65002-era: `date.site` replaces `date.local`, as in users-query `registered.site`.' ); self::assertSame( array( 'raw', 'rendered', 'protected' ), array_keys( $post['properties']['content']['properties'] ) ); self::assertSame( array( 'id', 'name', 'slug' ), array_keys( $post['properties']['author']['properties'] ) ); } @@ -405,8 +417,8 @@ public function test_permission_post_type_gate_negative_and_positive(): void { /** * Fail-closed malformed-filter rejections in the execute callback (ungated - * transports bypass validation, so these run through it directly), plus the - * schema-reachable parent/author_slug rejections through the real ability. + * transports bypass validation, so these run through it directly), plus + * schema-reachable parent/author rejections through the real ability. */ public function test_execute_fail_closed_malformed_filters(): void { $ability = $this->get_registered(); @@ -504,18 +516,115 @@ public function test_execute_fail_closed_malformed_filters(): void { 'The status filter must list valid post statuses.' ); - // Unknown author slug (schema-reachable; goes through validate via the input, so - // schema validation passes and the filter rejection fires). - $author = $this->execute_raw( + // The author filter is an object with an `id` and/or a `slug` (r65075). Filter-level + // rejections (unvalidated transport path). + $this->assert_wp_error( + 'content_invalid_filter', + $this->execute_raw( + $ability, + array( + 'where' => array( + 'type' => 'post', + 'author' => array(), + ), + ) + ), + null, + array( + 'status' => 400, + 'params' => array( 'where[author]' => 'The author filter must be an object with an id or a slug.' ), + ) + ); + $this->assert_wp_error( + 'content_invalid_filter', + $this->execute_raw( + $ability, + array( + 'where' => array( + 'type' => 'post', + 'author' => array( 'bogus' => 1 ), + ), + ) + ), + null, + array( + 'status' => 400, + 'params' => array( 'where[author]' => 'The author filter must be an object with an id or a slug.' ), + ) + ); + $this->assert_wp_error( + 'content_invalid_filter', + $this->execute_raw( + $ability, + array( + 'where' => array( + 'type' => 'post', + 'author' => array( 'id' => 0 ), + ), + ) + ), + null, + array( + 'status' => 400, + 'params' => array( 'where[author][id]' => 'The author ID must be a positive integer.' ), + ) + ); + $this->assert_wp_error( + 'content_invalid_filter', + $this->execute_raw( + $ability, + array( + 'where' => array( + 'type' => 'post', + 'author' => array( 'slug' => '' ), + ), + ) + ), + null, + array( + 'status' => 400, + 'params' => array( 'where[author][slug]' => 'The author slug must be a non-empty string.' ), + ) + ); + + // Schema-reachable author shapes through the validated transport: a non-object author + // fails validation (a schema rejection, not a filter rejection), while a well-formed + // `id` + unknown `slug` passes validation and reaches the execute callback, which + // answers an empty page (an author that names no visible user matches no post; no error). + $scalar_author = $ability->execute( + array( + 'where' => array( + 'type' => 'post', + 'author' => 'no-such-user', + ), + ) + ); + self::assertInstanceOf( + WP_Error::class, + $scalar_author, + 'A non-object author filter is rejected by schema validation.' + ); + self::assertNotSame( 'content_invalid_filter', $scalar_author->get_error_code() ); + + $no_such_user = $this->execute_raw( $ability, array( 'where' => array( - 'type' => 'post', - 'author_slug' => 'no-such-user', + 'type' => 'post', + 'author' => array( + 'id' => 999999999, + 'slug' => 'no-such-user', + ), ), ) ); - $this->assert_wp_error( 'content_invalid_filter', $author, 'The author_slug filter must be the slug of an existing user.' ); + self::assertNotInstanceOf( + WP_Error::class, + $no_such_user, + 'An author slug that names no user matches no post, rather than erroring.' + ); + self::assertSame( 0, $no_such_user['pagination']['total'] ); + self::assertSame( array(), $no_such_user['items'] ); } /** @@ -594,4 +703,165 @@ public function test_execute_mocked_data_set_and_pagination(): void { self::assertSame( array(), $withheld['items'], "Another user's draft is withheld from a subscriber." ); self::assertLessThanOrEqual( 1, $withheld['pagination']['total'] ); } + + /** + * The r65075 author filter: an `id` matches the stored author ID, a `slug` resolves + * through the visible-author rule, and an `id` + a `slug` that name different users + * match no post. The author field of matched posts reports the same author. + */ + public function test_execute_author_object_filter(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + $this->create_mocked_data_set(); + $admin_id = $this->user_ids['admin']; + $draft_id = $this->post_ids['draft-admin']; + wp_set_current_user( $admin_id ); + + $by_id = $ability->execute( + array( + 'where' => array( + 'type' => 'post', + 'status' => array( 'publish', 'draft' ), + 'author' => array( 'id' => $admin_id ), + ), + 'fields' => array( 'id', 'author' ), + ) + ); + self::assertIsArray( $by_id ); + self::assertSame( array( $draft_id ), wp_list_pluck( $by_id['items'], 'id' ), 'The `author.id` filter matches the stored author ID.' ); + self::assertSame( + array( + 'id' => $admin_id, + 'name' => 'cqadmin', + 'slug' => 'cqadmin', + ), + $by_id['items'][0]['author'], + 'The author field resolves the same user for the current user.' + ); + + $by_slug = $ability->execute( + array( + 'where' => array( + 'type' => 'post', + 'status' => array( 'publish', 'draft' ), + 'author' => array( 'slug' => 'cqadmin' ), + ), + ) + ); + self::assertIsArray( $by_slug ); + self::assertSame( $by_id['pagination']['total'], $by_slug['pagination']['total'], 'The `author.slug` filter and the `author.id` filter name the same user.' ); + + $mismatch = $ability->execute( + array( + 'where' => array( + 'type' => 'post', + 'status' => array( 'publish', 'draft' ), + 'author' => array( + 'id' => $admin_id, + 'slug' => 'cqsubscriber', + ), + ), + ) + ); + self::assertIsArray( $mismatch ); + self::assertSame( 0, $mismatch['pagination']['total'], 'An `id` and a `slug` that name different users match no post.' ); + self::assertSame( array(), $mismatch['items'] ); + } + + /** + * The author field follows the same visibility rule the filter does: an author the + * current user may not see reports `null` name and slug (the ID stays), while a user + * with `edit_users` (the `edit_user` branch) or one whose posts count resolves sees them. + */ + public function test_author_field_resolves_visible_author(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + $this->create_mocked_data_set(); + + $this->user_ids['quiet'] = (int) wp_insert_user( + array( + 'user_login' => 'cqquiet', + 'role' => 'subscriber', + ) + ); + $this->post_ids['quiet-draft'] = (int) wp_insert_post( + array( + 'post_title' => 'Quiet draft', + 'post_content' => 'Draft content.', + 'post_status' => 'draft', + 'post_type' => 'post', + 'post_author' => $this->user_ids['quiet'], + ) + ); + + // A subscriber sees the ID but not the identity of a draft's author (the row itself + // is withheld for a subscriber, so use the id-level fields of a readable query). + wp_set_current_user( $this->user_ids['subscriber'] ); + $peep = $this->invoke_private( $ability, 'format_post', get_post( $this->post_ids['quiet-draft'] ), array( 'author.id', 'author.name', 'author.slug' ) ); + self::assertIsArray( $peep['author'], 'The `author` field resolves through the visible-author rule.' ); + self::assertSame( + array( + 'id' => $this->user_ids['quiet'], + 'name' => null, + 'slug' => null, + ), + $peep['author'], + 'An author the current user may not see is reported like an unpublishable identity: null name and slug.' + ); + + // A user who can edit the author's profile sees the identity: the `edit_user` + // branch (r65075) does not need `list_users`, `edit_others_posts`, or a posts + // count (the draft itself is unpublished, so the count is zero). The caps ride + // on the user directly, never as a role, so no site role state is touched. + $this->user_ids['usereditor'] = (int) wp_insert_user( + array( + 'user_login' => 'cqusereditor', + 'role' => 'subscriber', + ) + ); + $usereditor = get_userdata( $this->user_ids['usereditor'] ); + self::assertInstanceOf( WP_User::class, $usereditor ); + $usereditor->add_cap( 'edit_posts' ); + $usereditor->add_cap( 'edit_users' ); + wp_set_current_user( $this->user_ids['usereditor'] ); + $sees = $this->invoke_private( $ability, 'format_post', get_post( $this->post_ids['quiet-draft'] ), array( 'author.id', 'author.name', 'author.slug' ) ); + self::assertIsArray( $sees['author'] ); + self::assertSame( + array( + 'id' => $this->user_ids['quiet'], + 'name' => 'cqquiet', + 'slug' => 'cqquiet', + ), + $sees['author'], + 'The `edit_user` branch opens the identity of an author the current user may edit, where the pre-r65075 rule (a posts count over viewable post types) would not.' + ); + } + + /** + * The r65075 visible-author memo: one rule evaluation per author per query, and a + * memoized judgment is respected without re-evaluating caps or posts counts. + */ + public function test_get_visible_author_is_memoized_per_query(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + $this->create_mocked_data_set(); + wp_set_current_user( $this->user_ids['subscriber'] ); + + // Seed the memo, then confirm it is honored for another user (the self branch + // never reaches the memo, so the memo target must be a different user). + $prop = ( new ReflectionClass( $ability ) )->getProperty( 'visible_authors' ); + $prop->setAccessible( true ); + $prop->setValue( $ability, array( $this->user_ids['admin'] => false ) ); + self::assertNull( $this->invoke_private( $ability, 'get_visible_author', $this->user_ids['admin'] ), 'The memoized false short-circuits the posts count.' ); + + $prop->setValue( $ability, array( $this->user_ids['admin'] => true ) ); + $memoized = $this->invoke_private( $ability, 'get_visible_author', $this->user_ids['admin'] ); + self::assertInstanceOf( WP_User::class, $memoized, 'A memoized positive resolves the user without re-evaluating anything.' ); + self::assertSame( $this->user_ids['admin'], $memoized->ID ); + + // A fresh query resets the memo. + $this->execute_raw( $ability, array( 'where' => array( 'type' => 'post' ) ) ); + $fresh = $prop->getValue( $ability ); + self::assertSame( array(), $fresh, 'The author visibility memo is per query and starts empty.' ); + } } diff --git a/tests/Abilities/UsersQueryTest.php b/tests/Abilities/UsersQueryTest.php index 2c49e4d..f3b391b 100644 --- a/tests/Abilities/UsersQueryTest.php +++ b/tests/Abilities/UsersQueryTest.php @@ -47,7 +47,31 @@ final class UsersQueryTest extends TestCase { 'last_name', 'nickname', 'locale', - 'registered_date', + 'registered', + 'roles', + ); + + /** + * The field paths the trunk `fields` input accepts, in get_field_paths() order + * (r65002): each field followed by the path of each of its sub-fields. + */ + private const TRUNK_FIELD_PATHS = array( + 'id', + 'name', + 'description', + 'url', + 'link', + 'slug', + 'avatar_urls', + 'username', + 'email', + 'first_name', + 'last_name', + 'nickname', + 'locale', + 'registered', + 'registered.site', + 'registered.gmt', 'roles', ); @@ -323,7 +347,7 @@ public function test_schemas_match_trunk(): void { array_values( array_filter( get_post_types(), 'is_post_type_viewable' ) ), $where['has_published_posts']['anyOf'][1]['items']['enum'] ); - self::assertSame( self::TRUNK_FIELDS, $input['properties']['fields']['items']['enum'] ); + self::assertSame( self::TRUNK_FIELD_PATHS, $input['properties']['fields']['items']['enum'], 'r65002: the fields enum lists dotted paths.' ); self::assertSame( 100, $input['properties']['pagination']['properties']['per_page']['maximum'] ); $output = $ability->get_output_schema(); @@ -443,7 +467,7 @@ public function test_execute_field_visibility(): void { $this->create_mocked_users(); $input = array( 'where' => array( 'ids' => array( $this->user_ids['post_author'] ) ), - 'fields' => array( 'username', 'email', 'first_name', 'registered_date', 'roles' ), + 'fields' => array( 'username', 'email', 'first_name', 'registered', 'roles' ), ); wp_set_current_user( $this->user_ids['subscriber'] ); @@ -456,7 +480,9 @@ public function test_execute_field_visibility(): void { self::assertSame( 'uqpostauthor', $self['username'] ); self::assertSame( 'uqpostauthor@example.com', $self['email'] ); self::assertSame( 'First', $self['first_name'] ); - self::assertMatchesRegularExpression( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00$/', $self['registered_date'] ); + self::assertSame( array( 'site', 'gmt' ), array_keys( $self['registered'] ), 'r65002: the registration date reports through `registered.site`/`registered.gmt`.' ); + self::assertMatchesRegularExpression( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00$/', $self['registered']['site'] ); + self::assertMatchesRegularExpression( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00$/', $self['registered']['gmt'] ); self::assertSame( array( 'author' ), $self['roles'] ); wp_set_current_user( $this->user_ids['administrator'] ); @@ -469,6 +495,44 @@ public function test_execute_field_visibility(): void { self::assertSame( $expected, array_keys( $default ) ); } + /** + * The r65002 dotted-field projection: requesting `registered` returns both of its + * sub-fields, while `registered.site` or `registered.gmt` returns only that one. + */ + public function test_execute_dotted_field_projection(): void { + $ability = $this->get_registered(); + self::assertNotNull( $ability ); + $this->create_mocked_users(); + wp_set_current_user( $this->user_ids['administrator'] ); + $where = array( 'ids' => array( $this->user_ids['post_author'] ) ); + + $only_gmt = $ability->execute( + array( + 'where' => $where, + 'fields' => array( 'registered.gmt' ), + ) + )['items'][0]; + self::assertArrayHasKey( 'registered', $only_gmt ); + self::assertSame( array( 'gmt' ), array_keys( $only_gmt['registered'] ), 'A sub-field path returns only that sub-field.' ); + self::assertMatchesRegularExpression( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00$/', $only_gmt['registered']['gmt'] ); + + $only_site = $ability->execute( + array( + 'where' => $where, + 'fields' => array( 'registered.site' ), + ) + )['items'][0]; + self::assertSame( array( 'site' => $only_site['registered']['site'] ), $only_site['registered'] ); + + $whole = $ability->execute( + array( + 'where' => $where, + 'fields' => array( 'registered' ), + ) + )['items'][0]; + self::assertSame( array( 'site', 'gmt' ), array_keys( $whole['registered'] ), 'Requesting the whole field returns all of its sub-fields.' ); + } + /** * Pagination: totals, the default page sizes (10, or every listed user for * an identifier list), and a page past the end. diff --git a/tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php b/tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php index a2e1a3f..4502f0c 100644 --- a/tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php +++ b/tests/Fixtures/abilities-api/abilities/class-wp-abilities-content.php @@ -2,8 +2,7 @@ /** * TRUNK SNAPSHOT — manually refreshed copy from WordPress/wordpress-develop trunk. * Original core path (for refresh): src/wp-includes/abilities/class-wp-abilities-content.php - * Refreshed: 2026-10-20 by WP2 (test infrastructure). - * + * Refreshed: 2026-11-06 by Worker A (§7.0b trio trunk-sync refresh, stacked PR; content synced to the r65075-era class — the author-visibility rework), verified against the WordPress/ai 1.5.0 synced copy. * * Tracked trunk reference for the coreify round-trip gate: * tools/coreify.php --check reads this file by default. Only this file-level * header is package-local; the code body below stays byte-faithful to trunk. @@ -11,7 +10,6 @@ * since 6.9 and the tests assume it (former fixture shim removed). NOT * package code: never shipped, never autoloaded. Excluded from WPCS/PHPStan; * see phpcs.xml.dist and phpstan.neon.dist. - */ /** * Abilities API: WP_Abilities_Content class. * @@ -28,7 +26,7 @@ * Registers the read-only `core/content-query` ability, which queries the readable posts of a * post type exposed to abilities via `show_in_abilities`, filtered by any of post IDs, slugs, * status, author, and parent. Raw fields are only returned for posts the current user can - * edit. + * edit, and the author's name and slug only for authors the current user may see. * * Unlike the core abilities registered directly in wp_register_core_abilities() as * self-contained closures, the content ability lives in a dedicated class because @@ -105,6 +103,14 @@ final class WP_Abilities_Content { */ private const LOOP_GLOBALS = array( 'post', 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' ); + /** + * Whether each author seen in the current query has posts the current user may read. + * + * @since 7.2.0 + * @var array + */ + private $visible_authors = array(); + /** * Registers all content abilities. * @@ -287,13 +293,10 @@ private function parse_list_input( array $input, string $key ): array { * @return bool True if the requested statuses may be queried. */ private function can_query_statuses( array $where, WP_Post_Type $post_type_object ): bool { - foreach ( $this->get_requested_statuses( $where ) as $status ) { - if ( ! $this->can_query_status( $status, $post_type_object ) ) { - return false; - } - } - - return true; + return array_all( + $this->get_requested_statuses( $where ), + fn( $status ) => $this->can_query_status( $status, $post_type_object ) + ); } /** @@ -410,6 +413,9 @@ private function execute_content_query( $input = array() ) { $input = rest_sanitize_object( $input ); $fields = $this->normalize_fields( $input ); + // The author visibility memo is per query; see get_visible_author(). + $this->visible_authors = array(); + /* * A `where` that is not an object cannot be honored. Reject it rather than reading it * as no filter at all. @@ -463,24 +469,75 @@ private function execute_content_query( $input = array() ) { } } - $author = null; - if ( isset( $where['author_slug'] ) ) { + /* + * The author filter is an object with an `id` or a `slug`, the keys the `author` + * field returns. Null, int, or false: no filter, the user ID to query, or a filter + * that names no user, which matches no post (see below). + */ + $author_id = null; + if ( array_key_exists( 'author', $where ) ) { if ( ! post_type_supports( $post_type, 'author' ) ) { return $this->invalid_filter_error( - 'where[author_slug]', + 'where[author]', /* translators: %s: Parameter. */ - sprintf( __( 'The %s filter is only supported for post types that support authors.' ), 'author_slug' ) + sprintf( __( 'The %s filter is only supported for post types that support authors.' ), 'author' ) ); } - $author = $this->get_author_by_slug( $where['author_slug'], $post_type_object ); - if ( ! $author ) { + /* + * An object without `id` or `slug`, such as `{}` or an empty string, and one with + * an unknown key, such as a list or a misspelled property, name no user and must not + * fall through to an unrestricted query, like an empty `ids` filter. + */ + $author_filter = $this->get_input_object( $where, 'author' ); + if ( empty( $author_filter ) || ! empty( array_diff_key( $author_filter, array_flip( array( 'id', 'slug' ) ) ) ) ) { return $this->invalid_filter_error( - 'where[author_slug]', + 'where[author]', /* translators: %s: Parameter. */ - sprintf( __( 'The %s filter must be the slug of an existing user.' ), 'author_slug' ) + sprintf( __( 'The %s filter must be an object with an id or a slug.' ), 'author' ) ); } + + /* + * An `id` of 0 must not reach the query: WP_Query reads `author => 0` as no author + * filter, which would return every post of the type. + */ + if ( array_key_exists( 'id', $author_filter ) ) { + $author_id = $this->parse_filter_int( $author_filter['id'], 1 ); + if ( null === $author_id ) { + return $this->invalid_filter_error( + 'where[author][id]', + /* translators: %s: Parameter. */ + sprintf( __( 'The %s ID must be a positive integer.' ), 'author' ) + ); + } + } + + if ( array_key_exists( 'slug', $author_filter ) ) { + if ( ! is_string( $author_filter['slug'] ) || '' === $author_filter['slug'] ) { + return $this->invalid_filter_error( + 'where[author][slug]', + /* translators: %s: Parameter. */ + sprintf( __( 'The %s slug must be a non-empty string.' ), 'author' ) + ); + } + + /* + * The slug is looked up as given, like the `slug` of the users endpoint: the + * collation of the users table decides whether the case matters. A slug that + * names no user, or a user the current user may not see, or names another user + * than `id`, matches no post, as a post must match every given filter. The + * visibility rule is the one the `author` field follows, so a slug the field + * withholds cannot be confirmed through the filter. + */ + $user = get_user_by( 'slug', $author_filter['slug'] ); + $user = $user ? $this->get_visible_author( $user->ID ) : null; + if ( ! $user || ( null !== $author_id && $user->ID !== $author_id ) ) { + $author_id = false; + } else { + $author_id = $user->ID; + } + } } /* @@ -574,14 +631,24 @@ private function execute_content_query( $input = array() ) { $query_args['post_name__in'] = $slugs; } - if ( null !== $author ) { - $query_args['author'] = $author->ID; + if ( is_int( $author_id ) ) { + $query_args['author'] = $author_id; } if ( null !== $parent ) { $query_args['post_parent'] = $parent; } + /* + * A slug that names no user or a user the current user may not see, or an ID and a slug + * that name different users, match no post, like IDs and slugs that name no post, rather + * than failing the query. An `id` is not looked up: the query matches the stored author + * ID, so the posts of a deleted user still match it. + */ + if ( false === $author_id ) { + return $this->prepare_output( array(), 0, 0 ); + } + $query = new WP_Query( $query_args ); $total = $this->get_query_total( $query, $query_args, $page ); @@ -731,13 +798,10 @@ private function get_query_total( WP_Query $query, array $query_args, int $page * @return bool True when post meta and term caches should be primed. */ private function should_prime_post_caches( array $fields ): bool { - foreach ( self::CACHE_PRIMING_FIELDS as $field ) { - if ( $this->is_field_requested( $field, $fields ) ) { - return true; - } - } - - return false; + return array_any( + self::CACHE_PRIMING_FIELDS, + fn( $field ) => $this->is_field_requested( $field, $fields ) + ); } /** @@ -758,50 +822,6 @@ private function is_field_requested( string $path, array $fields ): bool { return rest_is_field_included( $path, $fields ); } - /** - * Looks up the user an author slug names. - * - * The slug is the user's nicename, which the REST API users endpoint returns as `slug`. It is - * looked up as given, like that endpoint's `slug` filter, so the database collation decides - * whether a variant in another case matches. A user the current user may not see is reported - * like a missing one. The current user can see themselves, any user of the site when they can - * list users, and authors with posts in a publicly viewable post type. A user who can edit - * others' posts of the post type can also see any user of the site, since they may make any of - * them the author, so for them the lookup does tell whether such an account exists. - * - * On multisite the lookup searches the whole network, so posts by authors who are not - * members of the site, such as super admins, can still be filtered. Those users are only - * visible as the current user or as authors with posts in a publicly viewable post type, so - * the lookup does not tell whether an account exists elsewhere on the network. - * - * @since 7.2.0 - * - * @param mixed $slug The author slug. - * @param WP_Post_Type $post_type_object The post type the author is looked up for. - * @return WP_User|null The user, or null when the slug does not name a visible user. - */ - private function get_author_by_slug( $slug, WP_Post_Type $post_type_object ): ?WP_User { - $user = is_string( $slug ) ? get_user_by( 'slug', $slug ) : false; - if ( ! $user ) { - return null; - } - - if ( get_current_user_id() === $user->ID ) { - return $user; - } - - // The capabilities only reveal users of the site, not of the whole network. - if ( is_user_member_of_blog( $user->ID ) - && ( current_user_can( 'list_users' ) || current_user_can( $post_type_object->cap->edit_others_posts ) ) - ) { - return $user; - } - - $public_post_types = array_values( array_filter( get_post_types(), 'is_post_type_viewable' ) ); - - return ! empty( $public_post_types ) && count_user_posts( $user->ID, $public_post_types ) > 0 ? $user : null; - } - /** * Returns a post type exposed through the Abilities API. * @@ -979,12 +999,12 @@ private function get_post_properties(): array { 'type' => 'object', 'additionalProperties' => false, 'properties' => array( - 'local' => array( + 'site' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( "The publication date, in ISO 8601 format using the site's timezone. Null when the date cannot be resolved." ), ), - 'gmt' => array( + 'gmt' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( 'The publication date, in ISO 8601 format as GMT. Null when the date cannot be resolved.' ), @@ -996,12 +1016,12 @@ private function get_post_properties(): array { 'type' => 'object', 'additionalProperties' => false, 'properties' => array( - 'local' => array( + 'site' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( "The last modified date, in ISO 8601 format using the site's timezone. Null when the date cannot be resolved." ), ), - 'gmt' => array( + 'gmt' => array( 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'description' => __( 'The last modified date, in ISO 8601 format as GMT. Null when the date cannot be resolved.' ), @@ -1076,15 +1096,15 @@ private function get_post_properties(): array { 'properties' => array( 'id' => array( 'type' => 'integer', - 'description' => __( 'The user ID of the author.' ), + 'description' => __( 'The user ID of the author, as the `author.id` filter takes it.' ), ), 'name' => array( 'type' => array( 'string', 'null' ), - 'description' => __( "The author's display name, as the REST API users endpoint returns it in `name`. Null when the author no longer exists." ), + 'description' => __( "The author's display name, as the REST API users endpoint returns it in `name`. Null when the author no longer exists or the current user may not see them." ), ), 'slug' => array( 'type' => array( 'string', 'null' ), - 'description' => __( "The author's user slug (nicename), as the REST API users endpoint returns it in `slug`, and as the `author_slug` filter takes it. Null when the author no longer exists." ), + 'description' => __( "The author's user slug (nicename), as the REST API users endpoint returns it in `slug`, and as the `author.slug` filter takes it. Null when the author no longer exists or the current user may not see them." ), ), ), 'description' => __( 'The post author. Present when the post type supports authors.' ), @@ -1150,7 +1170,7 @@ private function get_fields_input_schema(): array { * The input has three members: `where` selects the posts, `fields` selects the fields * returned for each post, and `pagination` selects the page of results. `where` holds * the post type to query in `type`, and any of the filters `ids`, `slugs`, `status`, - * `author_slug`, and `parent`, which all combine. Every object sets + * `author`, and `parent`, which all combine. Every object sets * `additionalProperties: false`, so an unknown key, such as a misspelled filter, fails * validation instead of being silently ignored. * @@ -1171,12 +1191,12 @@ private function get_content_query_input_schema( array $post_types, array $statu 'additionalProperties' => false, 'required' => array( 'type' ), 'properties' => array( - 'type' => array( + 'type' => array( 'type' => 'string', 'enum' => $post_types, 'description' => __( 'Post type to query for readable posts.' ), ), - 'ids' => array( + 'ids' => array( 'type' => 'array', 'uniqueItems' => true, 'minItems' => 1, @@ -1187,7 +1207,7 @@ private function get_content_query_input_schema( array $post_types, array $statu ), 'description' => __( 'Limit the query to these post IDs. The order of the IDs does not affect the order of the results. If `pagination.per_page` is omitted, every matching post is returned on the first page.' ), ), - 'slugs' => array( + 'slugs' => array( 'type' => 'array', 'uniqueItems' => true, 'minItems' => 1, @@ -1198,7 +1218,7 @@ private function get_content_query_input_schema( array $post_types, array $statu ), 'description' => __( 'Limit the query to posts with these slugs. Each slug is sanitized as a post slug is, so `Hello-World` matches `hello-world`. A slug can match several posts, such as pages under different parents, and every match is returned. The order of the slugs does not affect the order of the results. If `pagination.per_page` is omitted, every matching post is returned on the first page, up to the `per_page` maximum.' ), ), - 'status' => array( + 'status' => array( 'type' => 'array', 'uniqueItems' => true, 'minItems' => 1, @@ -1208,18 +1228,31 @@ private function get_content_query_input_schema( array $post_types, array $statu ), 'description' => __( 'Filter readable posts by one or more post statuses. Defaults to publish, or, when `ids` or `slugs` is given, to every status the current user may query. Statuses that are not publicly viewable, other than private, require edit access.' ), ), - 'author_slug' => array( - 'type' => 'string', - 'minLength' => 1, - 'description' => __( "Filter by the author's user slug (nicename), as the REST API users endpoint returns it in `slug`. Only supported for post types that support authors." ), + 'author' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + 'description' => __( 'The user ID of the author, as `author.id` is returned.' ), + ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( "The author's user slug (nicename), as `author.slug` is returned and as the REST API users endpoint returns it in `slug`." ), + ), + ), + 'description' => __( 'Filter by the post author, given as the `id` or the `slug` the `author` field of a post returns. An `id` matches the author ID stored on the post, even when that user no longer exists. A `slug` that names no user or a user the current user may not see, as the `author` field reports them, or an `id` and a `slug` that name different users, match no post. Only supported for post types that support authors.' ), ), - 'parent' => array( + 'parent' => array( 'type' => 'integer', 'minimum' => 0, 'description' => __( 'Filter by parent post ID. Only supported for hierarchical post types. Use 0 for top-level posts.' ), ), ), - 'description' => __( 'Selects the posts to return: the readable posts of a `type`, filtered by any of `ids`, `slugs`, `status`, `author_slug`, and `parent`. A post must match every given filter.' ), + 'description' => __( 'Selects the posts to return: the readable posts of a `type`, filtered by any of `ids`, `slugs`, `status`, `author`, and `parent`. A post must match every given filter.' ), ), 'fields' => $this->get_fields_input_schema(), 'pagination' => array( @@ -1310,6 +1343,42 @@ private function get_content_query_output_schema(): array { ); } + /** + * Returns a user when the current user may see them as an author. + * + * The current user may see themselves, the users they can edit, every user when they can + * list users, and otherwise the authors of posts they can read in a publicly viewable post + * type exposed to abilities: this ability returns those posts with their author, so the + * author is already in view. Which post types the REST API exposes plays no part. A user + * the current user may not see is reported like a missing one. + * + * The `author` field and the `author` slug filter share this rule, so the filter never + * confirms a slug the field withholds. The post count is kept per author for the query, + * since count_user_posts() is not cached. + * + * @since 7.2.0 + * + * @param int $user_id The user ID. + * @return WP_User|null The user, or null when they no longer exist or may not be seen. + */ + private function get_visible_author( int $user_id ): ?WP_User { + $user = get_userdata( $user_id ); + if ( ! $user ) { + return null; + } + + if ( get_current_user_id() === $user_id || current_user_can( 'list_users' ) || current_user_can( 'edit_user', $user_id ) ) { + return $user; + } + + if ( ! isset( $this->visible_authors[ $user_id ] ) ) { + $post_types = array_values( array_filter( get_post_types( array( 'show_in_abilities' => true ), 'names' ), 'is_post_type_viewable' ) ); + $this->visible_authors[ $user_id ] = (int) count_user_posts( $user_id, $post_types ) > 0; + } + + return $this->visible_authors[ $user_id ] ? $user : null; + } + /** * Formats a post into the ability output shape. * @@ -1402,8 +1471,8 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit foreach ( array( 'date', 'modified' ) as $field ) { $dates = array(); - if ( $this->is_field_requested( "{$field}.local", $fields ) ) { - $dates['local'] = $this->format_date( $post, $field, false ); + if ( $this->is_field_requested( "{$field}.site", $fields ) ) { + $dates['site'] = $this->format_date( $post, $field, false ); } if ( $this->is_field_requested( "{$field}.gmt", $fields ) ) { $dates['gmt'] = $this->format_date( $post, $field, true ); @@ -1455,7 +1524,10 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit } if ( $this->is_field_requested( 'author', $fields ) && post_type_supports( $post_type, 'author' ) ) { - $user = get_userdata( (int) $post->post_author ); + $user = null; + if ( $this->is_field_requested( 'author.name', $fields ) || $this->is_field_requested( 'author.slug', $fields ) ) { + $user = $this->get_visible_author( (int) $post->post_author ); + } $author = array(); if ( $this->is_field_requested( 'author.id', $fields ) ) { $author['id'] = (int) $post->post_author; @@ -1488,8 +1560,8 @@ private function build_post_fields( WP_Post $post, array $fields, bool $can_edit * * @since 7.2.0 * - * @param mixed $required Whether the post currently requires a password. - * @param mixed $post The post being checked; a WP_Post when invoked by the core filter. + * @param bool $required Whether the post currently requires a password. + * @param WP_Post|null $post The post being checked, or null if no post is found. * @return bool Whether the post still requires a password. */ private function allow_password_content( $required, $post ): bool { diff --git a/tests/Fixtures/abilities-api/abilities/class-wp-abilities-users.php b/tests/Fixtures/abilities-api/abilities/class-wp-abilities-users.php index 83dee71..10d5486 100644 --- a/tests/Fixtures/abilities-api/abilities/class-wp-abilities-users.php +++ b/tests/Fixtures/abilities-api/abilities/class-wp-abilities-users.php @@ -2,8 +2,7 @@ /** * TRUNK SNAPSHOT — manually refreshed copy from WordPress/wordpress-develop trunk. * Original core path (for refresh): src/wp-includes/abilities/class-wp-abilities-users.php - * Refreshed: 2026-10-20 by WP2 (test infrastructure); re-verified identical - * to trunk 2026-10-23 (WP7). + * Refreshed: 2026-11-06 by Worker A (§7.0b trio trunk-sync refresh, stacked PR; users synced to the r65002-era class — the registered/dotted-field rework), verified against the WordPress/ai 1.5.0 synced copy. * * * Tracked trunk reference for the coreify round-trip gate of the * `core/users-query` backport: tools/coreify.php --check reads this file @@ -12,7 +11,6 @@ * anymore: the Abilities API ships in WordPress core since 6.9 and the * tests assume it. NOT package code: never shipped, never autoloaded. * Excluded from WPCS/PHPStan; see phpcs.xml.dist and phpstan.neon.dist. - */ /** * Abilities API: WP_Abilities_Users class. * @@ -409,11 +407,12 @@ private function get_public_post_types(): array { } /** - * Returns the requested fields, or a lean default set when none are given. + * Returns the requested field paths, or a lean default set when none are given. * * An empty or absent `fields` value selects a lean set of common read fields. - * Otherwise the requested fields are returned. The input schema has already - * validated the names against the supported set before the ability executes. + * Otherwise the requested paths are returned. The input schema has already + * validated them against the paths from {@see self::get_field_paths()} before the + * ability executes, and {@see self::format_user()} ignores any other path. * * The `id` field is always included, matching the REST users controller * where `id` is present in every context. This also guarantees the result @@ -422,7 +421,7 @@ private function get_public_post_types(): array { * @since 7.2.0 * * @param array $input The ability input. - * @return string[] List of requested field names. + * @return string[] List of requested field paths. */ private function normalize_fields( array $input ): array { $fields = isset( $input['fields'] ) ? $this->normalize_string_list( $input['fields'] ) : array(); @@ -441,8 +440,9 @@ private function normalize_fields( array $input ): array { * Returns the user field definitions, keyed by field name in output order. * * This is the single source of truth for the ability's user fields: the output - * schema uses the definitions directly, while the input schema and field - * normalization use the keys. The field set is deliberately unconditional: + * schema uses the definitions directly, while the input schema `fields` enum lists + * each field, followed by the path of each of its sub-fields, such as + * `registered.gmt`. The field set is deliberately unconditional: * the registered schemas are a registration-time snapshot, so conditional * availability (such as `avatar_urls` honoring the `show_avatars` option) is * enforced per call in {@see self::format_user()} instead of here, where the @@ -454,19 +454,19 @@ private function normalize_fields( array $input ): array { */ private function get_user_properties(): array { return array( - 'id' => array( + 'id' => array( 'type' => 'integer', 'description' => __( 'The user ID.' ), ), - 'name' => array( + 'name' => array( 'type' => 'string', 'description' => __( 'The display name for the user.' ), ), - 'description' => array( + 'description' => array( 'type' => 'string', 'description' => __( 'Description of the user. Present when the current user can view it.' ), ), - 'url' => array( + 'url' => array( /* * Unlike the REST users controller, `url` declares no `uri` format. It is * empty for users without a website, and clients that check formats, @@ -476,16 +476,16 @@ private function get_user_properties(): array { 'type' => 'string', 'description' => __( 'URL of the user. Present when the current user can view it.' ), ), - 'link' => array( + 'link' => array( 'type' => 'string', 'format' => 'uri', 'description' => __( 'Author archive URL for the user.' ), ), - 'slug' => array( + 'slug' => array( 'type' => 'string', 'description' => __( 'An alphanumeric identifier for the user.' ), ), - 'avatar_urls' => array( + 'avatar_urls' => array( 'type' => 'object', 'description' => __( 'Avatar URLs for the user, keyed by image size in pixels. A size is null when no avatar URL can be resolved for it. Present when the show_avatars option is enabled.' ), 'additionalProperties' => array( @@ -493,37 +493,49 @@ private function get_user_properties(): array { 'format' => 'uri', ), ), - 'username' => array( + 'username' => array( 'type' => 'string', 'description' => __( 'Login name for the user. Present when the current user can view it.' ), ), - 'email' => array( + 'email' => array( 'type' => array( 'string', 'null' ), 'format' => 'email', 'description' => __( 'The email address for the user. Null when the user has no stored address, or when the stored address is not a valid email. Present when the current user can view it.' ), ), - 'first_name' => array( + 'first_name' => array( 'type' => 'string', 'description' => __( 'First name for the user. Present when the current user can view it.' ), ), - 'last_name' => array( + 'last_name' => array( 'type' => 'string', 'description' => __( 'Last name for the user. Present when the current user can view it.' ), ), - 'nickname' => array( + 'nickname' => array( 'type' => 'string', 'description' => __( 'The nickname for the user. Present when the current user can view it.' ), ), - 'locale' => array( + 'locale' => array( 'type' => 'string', 'description' => __( 'Locale for the user. Present when the current user can view it.' ), ), - 'registered_date' => array( - 'type' => array( 'string', 'null' ), - 'format' => 'date-time', - 'description' => __( 'Registration date for the user. Null when the stored date is not a valid date. Present when the current user can view it.' ), + 'registered' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'site' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + 'description' => __( "The registration date, in ISO 8601 format using the site's timezone. Null when the stored date is not a valid date." ), + ), + 'gmt' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + 'description' => __( 'The registration date, in ISO 8601 format as GMT. Null when the stored date is not a valid date.' ), + ), + ), + 'description' => __( 'The registration date for the user. Present when the current user can view it.' ), ), - 'roles' => array( + 'roles' => array( 'type' => 'array', 'description' => __( 'Roles assigned to the user. Present when the current user can view them.' ), /* @@ -541,6 +553,47 @@ private function get_user_properties(): array { ); } + /** + * Returns the field paths the `fields` input accepts, in output order. + * + * Each user field is followed by the path of each sub-field its definition declares, + * such as `registered`, `registered.site` and `registered.gmt`. Requesting a field + * returns all of its sub-fields, while a sub-field path returns only that sub-field. + * + * @since 7.2.0 + * + * @return string[] The field paths. + */ + private function get_field_paths(): array { + $paths = array(); + foreach ( $this->get_user_properties() as $name => $schema ) { + $paths[] = $name; + + foreach ( array_keys( $schema['properties'] ?? array() ) as $sub_field ) { + $paths[] = "{$name}.{$sub_field}"; + } + } + + return $paths; + } + + /** + * Checks whether a field path is requested. + * + * A field such as `registered` is requested when it or one of its paths, such as + * `registered.gmt`, is requested, and a path such as `registered.gmt` is requested + * when it or its whole field is. + * + * @since 7.2.0 + * + * @param string $path The field path, such as `registered` or `registered.gmt`. + * @param string[] $fields The requested field paths. + * @return bool Whether the field path is requested. + */ + private function is_field_requested( string $path, array $fields ): bool { + return rest_is_field_included( $path, $fields ); + } + /** * Normalizes a mixed value into a list of user IDs. * @@ -714,9 +767,9 @@ private function get_users_query_input_schema(): array { 'uniqueItems' => true, 'items' => array( 'type' => 'string', - 'enum' => array_keys( $this->get_user_properties() ), + 'enum' => $this->get_field_paths(), ), - 'description' => __( 'Limit each returned user to these fields. If omitted or empty, a lean set of common read fields is returned. The `id` field is always included, and fields the current user cannot view are omitted rather than causing an error.' ), + 'description' => __( 'Limit each returned user to these fields. A field such as `registered` returns all of its sub-fields, while a path such as `registered.gmt` returns only that sub-field. If omitted or empty, a lean set of common read fields is returned. The `id` field is always included, and fields the current user cannot view are omitted rather than causing an error.' ), ), 'pagination' => array( 'type' => 'object', @@ -793,47 +846,45 @@ private function get_users_query_output_schema(): array { /** * Formats a user into the ability output shape. * - * Only the requested fields the current user can see are included, except - * `id`, which {@see self::normalize_fields()} always requests. + * Fields are selected with {@see self::is_field_requested()}, so `registered` returns + * both of its sub-fields, while `registered.site` or `registered.gmt` returns only that + * one. Only the requested fields the current user can see are included, except `id`, + * which {@see self::normalize_fields()} always requests. * * @since 7.2.0 * * @param WP_User $user The user object. - * @param string[] $fields The requested field names. + * @param string[] $fields The requested field paths. * @return array The formatted user data. */ private function format_user( WP_User $user, array $fields ): array { - $fields_requested = static function ( string $field ) use ( $fields ): bool { - return in_array( $field, $fields, true ); - }; - $can_view_sensitive = get_current_user_id() === $user->ID || current_user_can( 'edit_user', $user->ID ); $data = array(); - if ( $fields_requested( 'id' ) ) { + if ( $this->is_field_requested( 'id', $fields ) ) { $data['id'] = $user->ID; } - if ( $fields_requested( 'name' ) ) { + if ( $this->is_field_requested( 'name', $fields ) ) { $data['name'] = (string) $user->display_name; } - if ( $fields_requested( 'description' ) ) { + if ( $this->is_field_requested( 'description', $fields ) ) { $data['description'] = (string) $user->description; } - if ( $fields_requested( 'url' ) ) { + if ( $this->is_field_requested( 'url', $fields ) ) { $data['url'] = (string) $user->user_url; } - if ( $fields_requested( 'link' ) ) { + if ( $this->is_field_requested( 'link', $fields ) ) { $data['link'] = (string) get_author_posts_url( $user->ID, $user->user_nicename ); } - if ( $fields_requested( 'slug' ) ) { + if ( $this->is_field_requested( 'slug', $fields ) ) { $data['slug'] = (string) $user->user_nicename; } /* * The schemas always declare avatar_urls; availability is enforced here, * since the option can change after the schemas are registered. */ - if ( $fields_requested( 'avatar_urls' ) && get_option( 'show_avatars' ) ) { + if ( $this->is_field_requested( 'avatar_urls', $fields ) && get_option( 'show_avatars' ) ) { $data['avatar_urls'] = array_map( static function ( $url ) { return is_string( $url ) ? $url : null; @@ -843,32 +894,34 @@ static function ( $url ) { } if ( $can_view_sensitive ) { - if ( $fields_requested( 'username' ) ) { + if ( $this->is_field_requested( 'username', $fields ) ) { $data['username'] = (string) $user->user_login; } - if ( $fields_requested( 'email' ) ) { + if ( $this->is_field_requested( 'email', $fields ) ) { $data['email'] = is_email( $user->user_email ) ? (string) $user->user_email : null; } - if ( $fields_requested( 'first_name' ) ) { + if ( $this->is_field_requested( 'first_name', $fields ) ) { $data['first_name'] = (string) $user->first_name; } - if ( $fields_requested( 'last_name' ) ) { + if ( $this->is_field_requested( 'last_name', $fields ) ) { $data['last_name'] = (string) $user->last_name; } - if ( $fields_requested( 'nickname' ) ) { + if ( $this->is_field_requested( 'nickname', $fields ) ) { $data['nickname'] = (string) $user->nickname; } - if ( $fields_requested( 'locale' ) ) { + if ( $this->is_field_requested( 'locale', $fields ) ) { $data['locale'] = (string) get_user_locale( $user ); } - if ( $fields_requested( 'registered_date' ) ) { - /* - * The zero date, the column default, formats with a negative year that the - * `date-time` format rejects, so it is reported as null, like an unusable email. - */ - $registered_timestamp = strtotime( $user->user_registered ); - $registered_date = false !== $registered_timestamp ? gmdate( 'c', $registered_timestamp ) : ''; - $data['registered_date'] = rest_parse_date( $registered_date ) ? $registered_date : null; + + $registered = array(); + if ( $this->is_field_requested( 'registered.site', $fields ) ) { + $registered['site'] = $this->format_registered_date( $user, wp_timezone() ); + } + if ( $this->is_field_requested( 'registered.gmt', $fields ) ) { + $registered['gmt'] = $this->format_registered_date( $user, new DateTimeZone( 'UTC' ) ); + } + if ( ! empty( $registered ) ) { + $data['registered'] = $registered; } } @@ -879,13 +932,43 @@ static function ( $url ) { * matching the REST users controller, where `roles` is an edit-context * field and rows the caller cannot edit are dropped from collections. */ - if ( $fields_requested( 'roles' ) && $can_view_sensitive ) { + if ( $this->is_field_requested( 'roles', $fields ) && $can_view_sensitive ) { $data['roles'] = array_values( $user->roles ); } return $data; } + /** + * Formats the user's registration date as an ISO 8601 string in a timezone. + * + * The `user_registered` column holds the date in GMT, so it is parsed as UTC + * whatever the PHP default timezone is, then converted to the given timezone. + * + * @since 7.2.0 + * + * @param WP_User $user The user object. + * @param DateTimeZone $timezone The timezone to format the date in. + * @return string|null The ISO 8601 date, or null when the stored date is not a valid date. + */ + private function format_registered_date( WP_User $user, DateTimeZone $timezone ): ?string { + $datetime = date_create_immutable_from_format( 'Y-m-d H:i:s', (string) $user->user_registered, new DateTimeZone( 'UTC' ) ); + if ( ! $datetime ) { + return null; + } + + /* + * A malformed stored date can still parse, since out-of-range parts roll over: the + * zero date, the column default, formats with a negative year, and converting a + * date at either end of the range can push its year outside four digits. The + * `date-time` format rejects these, which would fail output validation for the + * whole call, so they are reported as null too, like an unusable email. + */ + $date = $datetime->setTimezone( $timezone )->format( 'c' ); + + return false !== rest_parse_date( $date ) ? $date : null; + } + /** * Builds the ability output for a page of formatted users. * diff --git a/tools/coreify.php b/tools/coreify.php index a7bf8c2..dff8629 100644 --- a/tools/coreify.php +++ b/tools/coreify.php @@ -176,7 +176,7 @@ function fail( string $msg ): void { 'get_input_object' => 'execute_users_query', 'parse_filter_int' => 'get_input_object', ), - 'imports' => array( 'WP_Error', 'WP_User', 'WP_User_Query' ), + 'imports' => array( 'DateTimeZone', 'WP_Error', 'WP_User', 'WP_User_Query' ), 'register_doc' => 'Registers all user abilities.', 'register_note' => array(), 'category' => 'user',