Repository navigation
Expand file tree
/
Copy pathclass-wp-abilities-content.php
More file actions
1848 lines (1702 loc) · 69.5 KB
/
Copy pathclass-wp-abilities-content.php
File metadata and controls
1848 lines (1702 loc) · 69.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Abilities API: WP_Abilities_Content class.
*
* @package WordPress
* @subpackage Abilities API
* @since 7.2.0
*/
declare( strict_types = 1 );
/**
* Core class used to register content-related abilities.
*
* 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, 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
* its callbacks and schemas share helpers: the permission and execute callbacks read the
* post type and the filters through the same code, and the input schema, output schema,
* and field projection are built from the same field definitions. Future write-oriented
* content abilities can reuse them as well.
*
* Only register() is public. The ability callbacks are closures that call private
* methods, so callers go through the Abilities API, such as
* `wp_get_ability( 'core/content-query' )->execute()`, which validates the input and
* checks permissions before running them.
*
* @since 7.2.0
*
* @access private
*/
final class WP_Abilities_Content {
/**
* The ability category used for content abilities.
*
* @since 7.2.0
* @var string
*/
private const CATEGORY = 'content';
/**
* Default number of posts returned per page, unless `where` lists posts by ID or slug.
*
* @since 7.2.0
* @var int
*/
private const DEFAULT_PER_PAGE = 10;
/**
* Maximum number of posts returned per page.
*
* The `ids` and `slugs` lists in `where` each hold at most this many values, so the posts
* that `ids` lists fit on one page.
*
* @since 7.2.0
* @var int
*/
private const MAX_PER_PAGE = 100;
/**
* Field paths whose output may read post meta or terms.
*
* Requests that include any of these, directly or through their whole object, prime
* the post meta and term caches for the page. Rendered excerpts and content may read
* either, and permalinks read terms when the permalink structure contains `%category%`.
* Other fields, such as the rendered title, do not need that cache priming.
*
* @since 7.2.0
* @var list<string>
*/
private const CACHE_PRIMING_FIELDS = array( 'link', 'excerpt.rendered', 'content.rendered' );
/**
* Default field paths returned when the caller does not request a field subset.
*
* @since 7.2.0
* @var list<string>
*/
private const DEFAULT_FIELDS = array( 'id', 'type', 'status', 'date', 'slug', 'title.rendered' );
/**
* Globals that rendering a post changes: the global post and the globals that
* setup_postdata() populates.
*
* @since 7.2.0
* @var list<string>
*/
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<int, bool>
*/
private $visible_authors = array();
/**
* Registers all content abilities.
*
* Must run on the `wp_abilities_api_init` hook.
*
* @since 7.2.0
*/
public function register(): void {
$this->register_content_query();
/*
* Future write-oriented content abilities can be registered here, reusing the
* shared helpers below (get_exposed_post_type(), format_post(), check_permission()).
*/
}
/**
* Registers the read-only `core/content-query` ability.
*
* @since 7.2.0
*/
private function register_content_query(): void {
/*
* Post types must be registered with `show_in_abilities` before the ability is
* registered so they are included in its input schema. Attachments are exposed
* through the media abilities instead.
*/
$post_types = $this->get_exposed_post_types();
if ( empty( $post_types ) ) {
return;
}
/*
* Internal statuses (e.g. `inherit`) are excluded here and from the statuses a query
* covers by default, so the posts of post types that rely on them cannot be queried,
* not even by ID.
*/
$statuses = array_values( get_post_stati( array( 'internal' => false ) ) );
wp_register_ability(
'core/content-query',
array(
'label' => __( 'Query Content' ),
'description' => __( 'Retrieves a paginated list of the readable posts of a post type exposed to abilities, filtered by any of post IDs, slugs, status, author, and parent. Requires an authenticated user. Filters are exact-match only; the ability does not perform full-text search.' ),
'category' => self::CATEGORY,
'input_schema' => $this->get_content_query_input_schema( $post_types, $statuses ),
'output_schema' => $this->get_content_query_output_schema(),
'execute_callback' => function ( $input = array() ) {
return $this->execute_content_query( $input );
},
'permission_callback' => function ( $input = array() ): bool {
return $this->check_permission( $input );
},
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'public' => true,
),
)
);
}
/**
* Permission callback for the `core/content-query` ability.
*
* The request is only gated as a whole here: it needs a logged-in user, a post type
* exposed to abilities, and the capabilities to query the explicitly requested statuses.
* It reads no post. {@see self::execute_content_query()} enforces row-level read
* permissions, since individual rows are unknown until the query runs.
*
* @since 7.2.0
*
* @param mixed $input Optional. The ability input. Default empty array.
* @return bool True if the request may proceed, false otherwise.
*/
private function check_permission( $input = array() ): bool {
$input = rest_sanitize_object( $input );
if ( ! is_user_logged_in() ) {
return false;
}
/*
* A `where` that is not an object is let through, so that the execute callback can
* report it as an invalid filter.
*/
$where = $this->get_input_object( $input, 'where' );
if ( null === $where ) {
return true;
}
// A query requires an exposed post type.
$post_type_object = $this->get_exposed_post_type( $where['type'] ?? null );
if ( ! $post_type_object ) {
return false;
}
return $this->can_query_statuses( $where, $post_type_object );
}
/**
* Parses a raw input value into an integer of at least a minimum, or null when invalid.
*
* Accepts the whole numbers that the integer schema accepts: native integers, floats such
* as the 2.0 that JSON encoders produce, and integer strings such as "2", "2.0", or "+2".
* Only the REST run controller converts input to the schema types, so other callers, such
* as the MCP adapter or a direct WP_Ability::execute() call, pass them on unconverted.
* Anything else, such as a fraction, is rejected rather than coerced: a malformed ID would
* otherwise resolve to another post, and a malformed `parent` filter would be read as 0,
* which asks for top-level posts.
*
* @since 7.2.0
*
* @param mixed $value The raw input value.
* @param int $min The smallest acceptable value.
* @return int|null The parsed integer, or null when the value is not an integer >= $min.
*/
private function parse_filter_int( $value, int $min ): ?int {
if ( is_int( $value ) ) {
return $value >= $min ? $value : null;
}
if ( is_string( $value ) && '' !== $value && ctype_digit( $value ) ) {
$int = (int) $value;
return $int >= $min ? $int : null;
}
if ( ! rest_is_integer( $value ) ) {
return null;
}
/*
* Other whole numbers are read as floats, which hold every integer only up to 2 ** 53.
* Past that, the value may not be the one that was sent, and casting a float beyond the
* integer range wraps it to an arbitrary integer, such as the ID of another post.
*/
$number = (float) $value;
return $number >= $min && $number <= 2 ** 53 ? (int) $number : null;
}
/**
* Parses a raw list input into a list of strings.
*
* Like schema validation, it also accepts a scalar or a comma-separated string, and
* parses it the same way, with wp_parse_list(). A number, such as a slug sent as 2024,
* is read as its string form.
*
* @since 7.2.0
*
* @param array<mixed> $input The ability input, or one of its objects, such as `where`.
* @param string $key The input key holding the list.
* @return list<string> The parsed string values; empty when absent or unparseable.
*/
private function parse_list_input( array $input, string $key ): array {
$value = $input[ $key ] ?? null;
if ( is_scalar( $value ) ) {
$value = (string) $value;
} elseif ( ! is_array( $value ) ) {
return array();
}
return array_values( array_filter( wp_parse_list( $value ), 'is_string' ) );
}
/**
* Checks whether the current user may query the explicitly requested statuses.
*
* The statuses a query covers by default, see {@see self::normalize_statuses()}, only
* hold statuses the current user may query, so they need no check.
*
* @since 7.2.0
*
* @param array<mixed> $where The `where` filters.
* @param WP_Post_Type $post_type_object The post type object.
* @return bool True if the requested statuses may be queried.
*/
private function can_query_statuses( array $where, WP_Post_Type $post_type_object ): bool {
return array_all(
$this->get_requested_statuses( $where ),
fn( $status ) => $this->can_query_status( $status, $post_type_object )
);
}
/**
* Checks whether the current user may query posts in a status.
*
* Like the REST posts controller, any user may query `publish`, while other statuses, such
* as `draft`, require edit access. Any user may also query the other publicly viewable
* statuses, and `private`, since the query only covers the private posts the user can
* read, see {@see self::execute_content_query()}.
*
* @since 7.2.0
*
* @param string $status The post status slug.
* @param WP_Post_Type $post_type_object The post type object.
* @return bool True if the status may be queried.
*/
private function can_query_status( string $status, WP_Post_Type $post_type_object ): bool {
return in_array( $status, array( 'publish', 'private' ), true ) || is_post_status_viewable( $status ) || current_user_can( $post_type_object->cap->edit_posts );
}
/**
* Checks if a post can be read by the current user.
*
* Mirrors the REST posts controller's read permission, while keeping this ability
* authenticated-only via {@see self::check_permission()}.
*
* @since 7.2.0
*
* @param WP_Post $post Post object.
* @param array<int, true> $checked_post_ids Post IDs already checked while walking inherited parents.
* @return bool Whether the post can be read.
*/
private function check_read_permission( WP_Post $post, array $checked_post_ids = array() ): bool {
if ( isset( $checked_post_ids[ $post->ID ] ) ) {
return false;
}
$checked_post_ids[ $post->ID ] = true;
if ( ! $this->get_exposed_post_type( $post->post_type ) ) {
return false;
}
/*
* Treat publicly viewable posts as readable. This checks both the post type
* and post status using Core's viewability helpers, which is stricter than
* checking the status object's `public` flag alone.
*/
if ( is_post_publicly_viewable( $post ) ) {
return true;
}
/*
* Use the normalized status for the status object lookup. For attachments,
* get_post_status() resolves `inherit` through the parent before returning.
*/
$post_status = get_post_status( $post );
if ( ! is_string( $post_status ) ) {
return false;
}
$post_status_object = get_post_status_object( $post_status );
if ( ! $post_status_object instanceof stdClass ) {
return false;
}
/*
* Core maps `read_post` for public statuses to the post type's plain `read`
* capability. Publicly viewable posts already returned above, so a remaining
* public status is public but not viewable and should require edit access.
*/
if ( $post_status_object->public ) {
return current_user_can( 'edit_post', $post->ID );
}
/*
* For non-public statuses, defer to Core's meta-capability mapping. This
* handles own drafts, private posts, and statuses that require edit access.
*/
if ( current_user_can( 'read_post', $post->ID ) ) {
return true;
}
/*
* Mirror the REST posts controller's inherited-parent behavior, but keep the
* ability fail-closed for missing parents or parent loops. No input can request
* `inherit`, since internal statuses are left out of the input schema and of the
* statuses a query covers by default, but a query filter such as a `pre_get_posts`
* callback can still add it, so such posts keep their parent's read check.
*/
if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
$parent = get_post( $post->post_parent );
if ( $parent instanceof WP_Post ) {
return $this->check_read_permission( $parent, $checked_post_ids );
}
}
return false;
}
/**
* Executes the `core/content-query` ability.
*
* {@see WP_Ability::execute()} always runs {@see self::check_permission()} first, which
* gates the request as a whole. The query still filters every row by read permission,
* because the gate cannot know the rows before the query runs.
*
* @since 7.2.0
*
* @param mixed $input Optional. The ability input. Default empty array.
* @return array<string, mixed>|WP_Error A page of posts, or a WP_Error on failure.
*/
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.
*/
$where = $this->get_input_object( $input, 'where' );
if ( null === $where ) {
return $this->invalid_filter_error( 'where', __( 'The where filter must be an object.' ) );
}
// Pagination that is not an object falls back to the defaults, like page values that cannot be parsed.
$pagination = $this->get_input_object( $input, 'pagination' ) ?? array();
$page = $this->parse_filter_int( $pagination['page'] ?? 1, 1 ) ?? 1;
/*
* Unreachable through gated transports, which run check_permission() first and deny a
* request without a post type exposed to abilities. A direct call to the execute
* callback still fails closed here, but it bypasses the checks of the request as a
* whole that the permission callback performed, such as the status capabilities, so
* only invoke the callback through WP_Ability::execute().
*/
$post_type_object = $this->get_exposed_post_type( $where['type'] ?? null );
if ( ! $post_type_object ) {
return new WP_Error(
'content_not_found',
__( 'The requested content was not found.' ),
array( 'status' => 404 )
);
}
$post_type = $post_type_object->name;
/*
* REST only registers the equivalent collection filters for post types that
* support them; a shared input schema cannot express that per post type. On
* transports that skip schema validation a malformed value would otherwise
* coerce to a benign default and silently *widen* the query (`author => 0`
* drops the author filter, an empty `post__in` or `post_name__in` is ignored,
* `post_parent => 0` becomes a top-level query). Reject unsupported filters and
* invalid filter values loudly so a filter that cannot be honored fails closed
* instead.
*/
$parent = null;
if ( isset( $where['parent'] ) ) {
if ( ! is_post_type_hierarchical( $post_type ) ) {
return $this->invalid_filter_error( 'where[parent]', __( 'The parent filter is only supported for hierarchical post types.' ) );
}
$parent = $this->parse_filter_int( $where['parent'], 0 );
if ( null === $parent ) {
return $this->invalid_filter_error( 'where[parent]', __( 'The parent filter must be a non-negative integer.' ) );
}
}
/*
* 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]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter is only supported for post types that support authors.' ), '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]',
/* translators: %s: Parameter. */
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;
}
}
}
/*
* An `ids` or `slugs` filter that was given but kept no valid entry must not fall
* through to an unrestricted query: WP_Query ignores an empty `post__in` or
* `post_name__in`, which would return every post of the type, the opposite of the
* caller's intent.
*/
$ids = null;
if ( isset( $where['ids'] ) ) {
$ids = $this->normalize_ids( $where );
if ( empty( $ids ) ) {
return $this->invalid_filter_error(
'where[ids]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list one or more valid post IDs.' ), 'ids' )
);
}
}
$slugs = null;
if ( isset( $where['slugs'] ) ) {
$slugs = $this->normalize_slugs( $where );
if ( empty( $slugs ) ) {
return $this->invalid_filter_error(
'where[slugs]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list one or more valid post slugs.' ), 'slugs' )
);
}
}
/*
* A `status` filter that was given but kept no status must not fall through to the
* default statuses, which with `ids` or `slugs` cover every status the current user may
* query, wider than the caller asked for.
*/
$statuses = $this->get_requested_statuses( $where );
if ( isset( $where['status'] ) && empty( $statuses ) ) {
return $this->invalid_filter_error(
'where[status]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list one or more post statuses.' ), 'status' )
);
}
/*
* The input schema lists the statuses registered when the ability was, so check them
* again: WP_Query ignores a status that is not registered, and drops the status clause
* when none is left, which would cover every status, including internal ones such as
* `trash`.
*/
if ( ! empty( array_diff( $statuses, get_post_stati( array( 'internal' => false ) ) ) ) ) {
return $this->invalid_filter_error(
'where[status]',
/* translators: %s: Parameter. */
sprintf( __( 'The %s filter must list valid post statuses.' ), 'status' )
);
}
$lists_posts = null !== $ids || null !== $slugs;
$per_page = $this->normalize_per_page( $pagination, $lists_posts );
$prime_post_caches = $this->should_prime_post_caches( $fields );
/*
* `orderby` is left unset, which orders by `post_date` descending, matching the
* default of the REST posts controller.
*
* `perm` leaves out the other users' private posts for a user who cannot read them,
* so the totals do not count them. It is not set for a user who can: when a query
* filter adds post types, WP_Query checks `read_private_multiple_post_types`
* instead, which no role has, and would leave the posts out too.
*/
$query_args = array(
'post_type' => $post_type,
'post_status' => $this->normalize_statuses( $statuses, $post_type_object, $lists_posts ),
'posts_per_page' => $per_page,
'paged' => $page,
'perm' => current_user_can( $post_type_object->cap->read_private_posts ) ? '' : 'readable',
'ignore_sticky_posts' => true,
'update_post_meta_cache' => $prime_post_caches,
'update_post_term_cache' => $prime_post_caches,
);
if ( null !== $ids ) {
$query_args['post__in'] = $ids;
}
if ( null !== $slugs ) {
$query_args['post_name__in'] = $slugs;
}
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 );
/*
* Count the pages with the page size the query ran with, as the REST posts controller
* does, since query filters such as `pre_get_posts` callbacks can change it. Without
* paging, the query returns every post on one page.
*/
$query_per_page = (int) $query->get( 'posts_per_page' );
if ( $query->get( 'nopaging' ) || $query_per_page < 1 ) {
$total_pages = $total > 0 ? 1 : 0;
} else {
$total_pages = (int) ceil( $total / $query_per_page );
}
/*
* A page past the last one does not exist, so report it as not found instead of
* returning a bare empty list. A genuinely empty result set still returns zero
* totals and no error.
*/
if ( $total > 0 && $page > $total_pages ) {
return $this->invalid_page_number_error();
}
/*
* Prime the parent and author caches with a single query each instead of one
* lookup per post, as the REST posts controller does. Hierarchical permalinks and
* inherited read permissions read the parent, and format_post() sets up every post
* with setup_postdata(), which reads the author.
*/
update_post_parent_caches( $query->posts );
update_post_author_caches( $query->posts );
$posts = array();
foreach ( $query->posts as $post ) {
/*
* Skip posts of other post types, which query filters can add, such as a
* `pre_get_posts` callback that adds post types to the blog home without an
* is_main_query() check.
*/
if ( ! $post instanceof WP_Post || $post_type !== $post->post_type ) {
continue;
}
if ( ! $this->check_read_permission( $post ) ) {
continue;
}
$posts[] = $this->format_post( $post, $fields );
}
/*
* Mirror the REST posts controller: totals come from the underlying WP_Query,
* while the row-level checks above may withhold individual returned rows. The
* totals can therefore count posts the current user cannot read, such as another
* author's draft listed in `ids`. This is deliberate: it only reveals that such a
* post exists, as a REST collection request with `include` and `status` does.
*/
return $this->prepare_output( $posts, $total, $total_pages );
}
/**
* Reads an object member of the input, such as `where` or `pagination`.
*
* Accepts what schema validation reads as an object: an array, a `stdClass`, or an
* empty string. Only the REST run controller converts input to the schema types, so
* callers that bypass it, such as a direct WP_Ability::execute() call, can pass any of them.
*
* @since 7.2.0
*
* @param array<mixed> $input The ability input.
* @param string $key The member name.
* @return array<mixed>|null The member as an array, an empty array when it is omitted,
* or null when it is not an object.
*/
private function get_input_object( array $input, string $key ): ?array {
if ( ! array_key_exists( $key, $input ) ) {
return array();
}
return rest_is_object( $input[ $key ] ) ? rest_sanitize_object( $input[ $key ] ) : null;
}
/**
* Normalizes the requested per-page value to the supported bounds.
*
* An explicit `per_page` always wins. Otherwise a request that lists posts by ID or slug
* pages to the maximum, as `core/users-query` does for its lists, so a caller loading a
* known set of posts receives them in one call rather than silently losing the ones past
* the default page size. The input schema caps each list at {@see self::MAX_PER_PAGE},
* so every post that `ids` lists fits on the first page. A slug can match several posts,
* though, so the matches of `slugs` only continue past the first page when more than
* that many posts match.
*
* @since 7.2.0
*
* @param array<mixed> $pagination The `pagination` input.
* @param bool $lists_posts Whether the query lists `ids` or `slugs`.
* @return int The clamped per-page value.
*/
private function normalize_per_page( array $pagination, bool $lists_posts ): int {
$default_per_page = $lists_posts ? self::MAX_PER_PAGE : self::DEFAULT_PER_PAGE;
return min( self::MAX_PER_PAGE, $this->parse_filter_int( $pagination['per_page'] ?? null, 1 ) ?? $default_per_page );
}
/**
* Returns the query total, recovering it when WP_Query skipped the count.
*
* WP_Query leaves `found_posts` at 0 when a requested page has no rows. Re-run a
* minimal unpaged query so the caller can distinguish an out-of-range page from
* an empty result set, matching the REST posts controller behavior.
*
* @since 7.2.0
*
* @param WP_Query $query The executed query.
* @param array<mixed> $query_args The arguments used for the executed query.
* @param int $page The requested page.
* @return int Total matching rows across all pages.
*/
private function get_query_total( WP_Query $query, array $query_args, int $page ): int {
$total = (int) $query->found_posts;
if ( $total > 0 || $page <= 1 ) {
return $total;
}
$count_args = $query_args;
$count_args['fields'] = 'ids';
$count_args['posts_per_page'] = 1;
$count_args['update_post_meta_cache'] = false;
$count_args['update_post_term_cache'] = false;
unset( $count_args['paged'] );
$count_query = new WP_Query( $count_args );
return (int) $count_query->found_posts;
}
/**
* Checks whether requested fields benefit from page-level cache priming.
*
* A whole object counts as a request for its sub-fields, so `content` primes the
* caches as `content.rendered` does.
*
* @since 7.2.0
*
* @param list<string> $fields The requested field paths.
* @return bool True when post meta and term caches should be primed.
*/
private function should_prime_post_caches( array $fields ): bool {
return array_any(
self::CACHE_PRIMING_FIELDS,
fn( $field ) => $this->is_field_requested( $field, $fields )
);
}
/**
* Checks whether a field path is requested.
*
* Matches paths as the REST API's `_fields` parameter does, with rest_is_field_included():
* a field such as `title` is requested when it or one of its paths, such as
* `title.rendered`, is requested, and a path such as `title.rendered` is requested when it
* or its whole field is.
*
* @since 7.2.0
*
* @param string $path The field path, such as `title` or `title.rendered`.
* @param list<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 );
}
/**
* Returns a post type exposed through the Abilities API.
*
* Deliberately resolved on every call rather than cached: post types can be
* unregistered or re-registered with different arguments between the ability
* being registered and the ability being used.
*
* @since 7.2.0
*
* @param mixed $post_type The post type name.
* @return WP_Post_Type|null The post type object, or null when the post type is not exposed.
*/
private function get_exposed_post_type( $post_type ): ?WP_Post_Type {
return is_string( $post_type ) && in_array( $post_type, $this->get_exposed_post_types(), true ) ? get_post_type_object( $post_type ) : null;
}
/**
* Returns the names of the post types exposed through the Abilities API.
*
* Attachments are never exposed: the media abilities handle them.
*
* @since 7.3.0
*
* @return list<string> The post type names.
*/
private function get_exposed_post_types(): array {
return array_values( array_diff( get_post_types( array( 'show_in_abilities' => true ) ), array( 'attachment' ) ) );
}
/**
* Returns the statuses the `status` filter explicitly requests.
*
* @since 7.2.0
*
* @param array<mixed> $where The `where` filters.
* @return list<string> Sanitized post status slugs; empty when none is requested.
*/
private function get_requested_statuses( array $where ): array {
return array_map( 'sanitize_key', $this->parse_list_input( $where, 'status' ) );
}
/**
* Normalizes the statuses a query covers.
*
* Explicitly requested statuses are queried as given, once the permission callback has
* allowed them. Otherwise a query covers `publish`, as in the REST posts controller,
* unless it lists `ids` or `slugs`. Such a query names the posts it wants, which may be
* drafts or private posts, so it covers every non-internal status that
* {@see self::can_query_status()} allows instead. The row-level read checks still
* withhold the posts the current user cannot read, such as other users' drafts.
*
* @since 7.2.0
*
* @param list<string> $statuses The explicitly requested statuses; empty when none is requested.
* @param WP_Post_Type $post_type_object The post type object.
* @param bool $lists_posts Whether the query lists `ids` or `slugs`.
* @return list<string> Post status slugs.
*/
private function normalize_statuses( array $statuses, WP_Post_Type $post_type_object, bool $lists_posts ): array {
if ( ! empty( $statuses ) ) {
return $statuses;
}
if ( ! $lists_posts ) {
return array( 'publish' );
}
foreach ( get_post_stati( array( 'internal' => false ) ) as $status ) {
if ( $this->can_query_status( $status, $post_type_object ) ) {
$statuses[] = $status;
}
}
return $statuses;
}
/**
* Normalizes the post IDs the `ids` filter lists.
*
* Like schema validation, it also accepts a single ID or a comma-separated string. Each
* ID is read with {@see self::parse_filter_int()}, and one that is not a whole number of
* at least 1, such as a fraction, a negative number, or a float too large to hold its
* integer exactly, is dropped rather than coerced, so it can never select another post.
* A digit string beyond the integer range saturates to PHP_INT_MAX, as REST sanitization
* does, which selects no post either.
*
* @since 7.2.0
*
* @param array<mixed> $where The `where` filters.
* @return list<int> Unique post IDs; empty when none is valid.
*/
private function normalize_ids( array $where ): array {
$ids = $where['ids'] ?? null;
if ( is_string( $ids ) ) {
$ids = wp_parse_list( $ids );
} elseif ( is_int( $ids ) || is_float( $ids ) ) {
$ids = array( $ids );
} elseif ( ! is_array( $ids ) ) {
return array();
}
$post_ids = array();
foreach ( $ids as $id ) {
$post_id = $this->parse_filter_int( $id, 1 );
if ( null !== $post_id ) {
$post_ids[] = $post_id;
}
}
return array_values( array_unique( $post_ids ) );
}
/**
* Normalizes the post slugs the `slugs` filter lists.
*
* Like schema validation, it also accepts a single slug, even one sent as a number, or a
* comma-separated string. Each slug is sanitized with sanitize_title(), as WordPress
* sanitizes a post slug when it saves the post, so `Hello-World` matches `hello-world`.
* A slug that sanitizes to an empty string, such as `!!!`, is dropped: it names no post,
* and querying it would match the posts that have no slug yet, such as drafts.
*
* @since 7.2.0
*
* @param array<mixed> $where The `where` filters.
* @return list<string> Unique post slugs; empty when none is valid.
*/
private function normalize_slugs( array $where ): array {
$slugs = array();
foreach ( $this->parse_list_input( $where, 'slugs' ) as $slug ) {
$slug = sanitize_title( $slug );
if ( '' !== $slug ) {
$slugs[] = $slug;
}
}
return array_values( array_unique( $slugs ) );
}
/**
* 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 paths are returned. The input schema has already
* validated them against the supported set before the ability executes, and
* {@see self::build_post_fields()} ignores any other path.
*
* @since 7.2.0
*
* @param array<mixed> $input The ability input.
* @return list<string> List of requested field paths.
*/
private function normalize_fields( array $input ): array {
$fields = $this->parse_list_input( $input, 'fields' );
return empty( $fields ) ? self::DEFAULT_FIELDS : $fields;
}
/**
* Returns the post field definitions, keyed by field name in output order.
*
* This is the single source of truth for the ability's post fields: the output
* 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 `title.rendered`.
* Read-context fields are returned for readable posts; the `raw` sub-fields only for
* posts the current user can edit.
*
* @since 7.2.0
*
* @return array<string, mixed> Post field definitions.
*/
private function get_post_properties(): array {
return array(
'id' => array(
'type' => 'integer',
'description' => __( 'The post ID.' ),
),
'type' => array(
'type' => 'string',
'description' => __( 'The post type.' ),
),
'status' => array(
'type' => 'string',
'description' => __( 'The post status.' ),
),
'date' => array(
'type' => 'object',
'additionalProperties' => false,