Repository navigation
Expand file tree
/
Copy pathclass-wp-abilities-content.php
More file actions
2856 lines (2617 loc) · 107 KB
/
Copy pathclass-wp-abilities-content.php
File metadata and controls
2856 lines (2617 loc) · 107 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.
*
* Also registers `core/content-create`, `core/content-update`, and `core/content-delete`,
* which create, update, and trash or delete one post of such a post type. Create and update
* return the written post in the same shape as a `core/content-query` item, and delete
* returns whether the post was trashed or deleted.
*
* Unlike the core abilities registered directly in wp_register_core_abilities() as
* self-contained closures, the four content abilities live in one dedicated class because
* their callbacks and schemas share helpers as private methods, such as the read check,
* the field projection, and the input parsing: 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.
*
* 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 call 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
* @since 7.3.0 Added the `core/content-create`, `core/content-update`, and `core/content-delete` abilities.
*/
public function register(): void {
/*
* Post types must be registered with `show_in_abilities` before the abilities are
* registered so they are included in the input schemas. Without one, no content
* ability is registered.
*/
$post_types = array_values( get_post_types( array( 'show_in_abilities' => true ) ) );
if ( empty( $post_types ) ) {
return;
}
// The statuses that can be set: the ones that are not internal.
$statuses = array_values( get_post_stati( array( 'internal' => false ) ) );
$this->register_content_query( $post_types, $statuses );
$this->register_content_write_abilities( $post_types, $statuses );
}
/**
* Registers the read-only `core/content-query` ability.
*
* @since 7.2.0
* @since 7.3.0 Added the `$post_types` and `$statuses` parameters, and support for `trash`
* in the `where.status` filter.
*
* @param list<string> $post_types Exposed post type names.
* @param list<string> $statuses Post status slugs that are not internal.
*/
private function register_content_query( array $post_types, array $statuses ): void {
/*
* Of the internal statuses, only `trash` can be requested, and only by name: it is never
* one of the statuses a query covers by default. The others, such as `inherit`, can never
* be queried, so the posts of post types that rely on them (attachments) cannot be
* queried, not even by ID. Revisit if such a post type is ever exposed via
* `show_in_abilities`.
*/
$statuses[] = 'trash';
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_query_permission( $input );
},
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'public' => true,
),
)
);
}
/**
* Registers the `core/content-create`, `core/content-update`, and `core/content-delete` abilities.
*
* @since 7.3.0
*
* @param list<string> $post_types Exposed post type names.
* @param list<string> $statuses Post status slugs that can be set.
*/
private function register_content_write_abilities( array $post_types, array $statuses ): void {
wp_register_ability(
'core/content-create',
array(
'label' => __( 'Create Content' ),
'description' => __( 'Creates a post of a post type exposed to abilities and returns it. Requires an authenticated user who can create posts of that type. The post is saved as a draft unless another status is given.' ),
'category' => self::CATEGORY,
'input_schema' => $this->get_content_create_input_schema( $post_types, $statuses ),
'output_schema' => $this->get_content_output_schema(),
'execute_callback' => function ( $input ) {
return $this->execute_content_create( $input );
},
'permission_callback' => function ( $input ): bool {
return $this->check_create_permission( $input );
},
'meta' => array(
'annotations' => array(
'readonly' => false,
'destructive' => false,
'idempotent' => false,
),
'public' => true,
),
)
);
wp_register_ability(
'core/content-update',
array(
'label' => __( 'Update Content' ),
'description' => __( 'Updates the given attributes of a post of a post type exposed to abilities and returns it. Attributes that are left out keep their stored values. Requires an authenticated user who can edit the post.' ),
'category' => self::CATEGORY,
'input_schema' => $this->get_content_update_input_schema( $post_types, $statuses ),
'output_schema' => $this->get_content_output_schema(),
'execute_callback' => function ( $input ) {
return $this->execute_content_update( $input );
},
'permission_callback' => function ( $input ): bool {
return $this->check_post_permission( $input, 'edit_post' );
},
'meta' => array(
'annotations' => array(
'readonly' => false,
'destructive' => false,
'idempotent' => true,
),
'public' => true,
),
)
);
wp_register_ability(
'core/content-delete',
array(
'label' => __( 'Delete Content' ),
'description' => __( 'Moves a post of a post type exposed to abilities to the Trash, or deletes it permanently when `permanent` is true. Requires an authenticated user who can delete the post.' ),
'category' => self::CATEGORY,
'input_schema' => $this->get_content_delete_input_schema( $post_types ),
'output_schema' => $this->get_content_delete_output_schema(),
'execute_callback' => function ( $input ) {
return $this->execute_content_delete( $input );
},
'permission_callback' => function ( $input ): bool {
return $this->check_post_permission( $input, 'delete_post' );
},
'meta' => array(
'annotations' => array(
'readonly' => false,
'destructive' => true,
'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_query_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 );
}
/**
* Permission callback for the `core/content-create` ability.
*
* Requires a logged-in user, a `data.type` that is exposed to abilities, the capability
* to create posts of that type, and the capabilities that the sent attributes need,
* see {@see self::can_set_attributes()}.
*
* @since 7.3.0
*
* @param mixed $input The ability input, which is not prepared when
* WP_Ability::check_permissions() is called directly.
* @return bool True if the request may proceed, false otherwise.
*/
private function check_create_permission( $input ): bool {
if ( ! is_user_logged_in() ) {
return false;
}
$data = $this->get_input_object( rest_sanitize_object( $input ), 'data' ) ?? array();
$post_type_object = $this->get_exposed_post_type( $data['type'] ?? null );
return null !== $post_type_object
&& current_user_can( $post_type_object->cap->create_posts )
&& $this->can_set_attributes( $data, $post_type_object, null );
}
/**
* Checks the capabilities that the sent `status`, `author`, `parent` and `slug` need.
*
* A status that makes the post visible needs the capability to publish posts of the type,
* and an author other than the current user needs the capability to edit the posts of
* others. A parent must be a post the current user can read, of a type exposed to
* abilities; a missing post is refused the same way, so the refusal never tells whether a
* post exists. The slug of a post that will be pending needs the capability to publish the
* post. A value that keeps the stored one needs none of these, see
* {@see self::get_changed_data()}. Every other rule on these attributes is checked by the
* execute callbacks.
*
* @since 7.3.0
*
* @param array<mixed> $data The `data` input.
* @param WP_Post_Type $post_type_object The post type of the post being written.
* @param WP_Post|null $post The stored post on update, or null on create.
* @return bool True if the user may set the sent attributes, false otherwise.
*/
private function can_set_attributes( array $data, WP_Post_Type $post_type_object, ?WP_Post $post ): bool {
$data = $this->get_changed_data( $data, $post );
if ( array_key_exists( 'status', $data ) ) {
$status = $data['status'];
if ( ! is_string( $status ) ) {
return false;
}
/*
* Intentionally strict: every status that makes a post visible needs the capability
* to publish posts of the type, including custom ones.
*/
$status_object = get_post_status_object( $status );
$makes_visible = $status_object instanceof stdClass
&& ( 'future' === $status || ! empty( $status_object->public ) || ! empty( $status_object->private ) || is_post_status_viewable( $status_object ) );
if ( $makes_visible && ! current_user_can( $post_type_object->cap->publish_posts ) ) {
return false;
}
}
if ( array_key_exists( 'author', $data ) ) {
$author_id = $this->parse_filter_int( $data['author'], 1 );
if ( null === $author_id ) {
return false;
}
if ( get_current_user_id() !== $author_id && ! current_user_can( $post_type_object->cap->edit_others_posts ) ) {
return false;
}
}
// A parent sent for a post type that is not hierarchical is refused by the execute callbacks.
if ( array_key_exists( 'parent', $data ) && is_post_type_hierarchical( $post_type_object->name ) ) {
$parent_id = $this->parse_filter_int( $data['parent'], 0 );
if ( null === $parent_id ) {
return false;
}
if ( 0 !== $parent_id ) {
$parent = get_post( $parent_id );
if ( ! $parent instanceof WP_Post || ! $this->check_read_permission( $parent ) ) {
return false;
}
}
}
if ( array_key_exists( 'slug', $data ) ) {
// Without a changed status, the save keeps the stored status, or defaults to `draft`.
$status = $data['status'] ?? ( $post ? $post->post_status : 'draft' );
/*
* Intentionally strict: the save drops the slug of a pending post when the user
* cannot publish it, so a changed slug is refused instead of being dropped without
* notice. The stored slug sent back is accepted as unchanged, although the save
* still drops it.
*/
if ( 'pending' === $status ) {
$can_publish = $post
? current_user_can( 'publish_post', $post->ID )
: current_user_can( $post_type_object->cap->publish_posts );
if ( ! $can_publish ) {
return false;
}
}
}
return true;
}
/**
* Removes the sent `status`, `author`, `parent` and `slug` that keep their stored values.
*
* Keeping a stored value, also the empty slug of a draft, changes nothing, so it needs no
* capability and is not checked or saved again. The IDs are read with
* {@see self::parse_filter_int()}, as the permission callbacks read them. On create,
* nothing is stored, so the data is returned as given.
*
* @since 7.3.0
*
* @param array<mixed> $data The `data` input.
* @param WP_Post|null $post The stored post on update, or null on create.
* @return array<mixed> The `data` input without the attributes that keep their stored values.
*/
private function get_changed_data( array $data, ?WP_Post $post ): array {
if ( ! $post ) {
return $data;
}
$stored = array(
'status' => $post->post_status,
'author' => (int) $post->post_author,
'parent' => (int) $post->post_parent,
'slug' => $post->post_name,
);
foreach ( $stored as $attribute => $stored_value ) {
if ( ! array_key_exists( $attribute, $data ) ) {
continue;
}
// An author ID is at least 1, a parent ID at least 0.
$value = is_int( $stored_value ) ? $this->parse_filter_int( $data[ $attribute ], 'author' === $attribute ? 1 : 0 ) : $data[ $attribute ];
if ( $stored_value === $value ) {
unset( $data[ $attribute ] );
}
}
return $data;
}
/**
* Permission callback for the `core/content-update` and `core/content-delete` abilities.
*
* Requires a logged-in user, a `where.type` that is exposed to abilities, and the given
* capability on the post that `where` names. An update with `edit_post` also requires the
* capabilities that the sent attributes need, see {@see self::can_set_attributes()}. When
* `where` names no post of that type, such as a missing ID or the ID of a post of another
* type, the request is let through so that the execute callback can report it as not found.
*
* @since 7.3.0
*
* @param mixed $input The ability input, which is not prepared when
* WP_Ability::check_permissions() is called directly.
* @param string $capability The capability required on the post: `edit_post` for an
* update, or `delete_post` for a delete.
* @return bool True if the request may proceed, false otherwise.
*/
private function check_post_permission( $input, string $capability ): bool {
if ( ! is_user_logged_in() ) {
return false;
}
$input = rest_sanitize_object( $input );
$where = $this->get_input_object( $input, 'where' ) ?? array();
if ( ! $this->get_exposed_post_type( $where['type'] ?? null ) ) {
return false;
}
$post = $this->get_requested_post( $where );
if ( ! $post ) {
return true;
}
if ( ! current_user_can( $capability, $post->ID ) ) {
return false;
}
// get_requested_post() only returns posts of an exposed post type.
return 'edit_post' !== $capability
|| $this->can_set_attributes( $this->get_input_object( $input, 'data' ) ?? array(), get_post_type_object( $post->post_type ), $post );
}
/**
* 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".
* WP_Ability::execute() converts input to the schema types, but
* WP_Ability::check_permissions() does not, so a permission callback can receive any of them.
* 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_query_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`: the input schema leaves out every internal status other than `trash`,
* and the statuses a query covers by default hold no internal status. A query
* filter such as a `pre_get_posts` callback can still add it, though, 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_query_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_query_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 $this->not_found_error();
}
$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`. Of the internal statuses, only `trash` can be requested, by name.
*/
if ( ! empty( array_diff( $statuses, get_post_stati( array( 'internal' => false ) ), array( 'trash' ) ) ) ) {
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 or a trashed post 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 );
}
/**
* Executes the `core/content-create` ability.
*
* The post type is checked first, then every attribute rule, and only then is the post
* saved, so a rejected call writes nothing. The capabilities are checked by
* {@see self::check_create_permission()}.
*
* @since 7.3.0