-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbilities.php
More file actions
1982 lines (1728 loc) · 56.5 KB
/
Copy pathAbilities.php
File metadata and controls
1982 lines (1728 loc) · 56.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
/**
* Ability catalog for WordPress MCP.
*
* @package WP_Forge
*/
namespace WP_Forge;
use WP_Forge\Tools\ContentManagementTools;
use WP_Forge\Tools\CommentManagementTools;
use WP_Forge\Tools\ErrorLogTools;
use WP_Forge\Tools\GlobalStylesTools;
use WP_Forge\Tools\MediaTools;
use WP_Forge\Tools\OptionManagementTools;
use WP_Forge\Tools\PluginManagementTools;
use WP_Forge\Tools\RestCatalogTools;
use WP_Forge\Tools\SiteManagementTools;
use WP_Forge\Tools\SiteHealthTools;
use WP_Forge\Tools\TaxonomyTools;
use WP_Forge\Tools\ThemeManagementTools;
use WP_Forge\Tools\WPCLITools;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Registers wp-forge abilities and dispatches calls.
*/
class Abilities {
use ContentManagementTools;
use CommentManagementTools;
use ErrorLogTools;
use GlobalStylesTools;
use MediaTools;
use OptionManagementTools;
use PluginManagementTools;
use RestCatalogTools;
use SiteManagementTools;
use SiteHealthTools;
use TaxonomyTools;
use ThemeManagementTools;
use WPCLITools;
const INTERNAL_PREFIX = 'wp-forge/';
const TOOL_PREFIX = 'wp-forge-';
/**
* Ability definitions.
*
* @var array<string,array<string,mixed>>
*/
private $abilities = array();
/**
* Constructor.
*/
public function __construct() {
$this->register_default_abilities();
}
/**
* List abilities with optional filtering.
*
* @param array<string,mixed> $filters Filter arguments.
* @return array<int,array<string,mixed>>
*/
public function list_abilities( $filters = array() ) {
$search = isset( $filters['search'] ) ? strtolower( (string) $filters['search'] ) : '';
$name_prefix = isset( $filters['name_prefix'] ) ? $this->normalize_tool_name( (string) $filters['name_prefix'] ) : '';
$items = array();
foreach ( $this->abilities as $name => $ability ) {
$tool_name = $this->ability_to_tool_name( $name );
if ( $name_prefix && 0 !== strpos( $tool_name, $name_prefix ) ) {
continue;
}
if ( $search ) {
$haystack = strtolower( $tool_name . ' ' . $ability['label'] . ' ' . $ability['description'] );
if ( false === strpos( $haystack, $search ) ) {
continue;
}
}
$items[] = array(
'name' => $tool_name,
'label' => $ability['label'],
'description' => $ability['description'],
'annotations' => $ability['annotations'],
);
}
return $items;
}
/**
* List all registered abilities as top-level MCP tools.
*
* @return array<int,array<string,mixed>>
*/
public function list_tools() {
$tools = array();
foreach ( $this->abilities as $name => $ability ) {
$tools[] = array(
'name' => $this->ability_to_tool_name( $name ),
'description' => $ability['description'],
'inputSchema' => $this->resolve_input_schema( $ability['input_schema'] ),
'annotations' => $ability['annotations'],
);
}
return $tools;
}
/**
* Get an ability schema by MCP tool name or internal ability name.
*
* @param string $name Ability name.
* @return array<string,mixed>|null
*/
public function get_schema( $name ) {
$internal = $this->tool_to_ability_name( $name );
if ( ! isset( $this->abilities[ $internal ] ) ) {
return null;
}
$ability = $this->abilities[ $internal ];
return array(
'name' => $this->ability_to_tool_name( $internal ),
'label' => $ability['label'],
'description' => $ability['description'],
'input_schema' => $this->resolve_input_schema( $ability['input_schema'] ),
'annotations' => $ability['annotations'],
);
}
/**
* Get WordPress ability names for the MCP adapter server.
*
* @return array<int,string>
*/
public function get_wordpress_ability_names() {
return array_keys( $this->abilities );
}
/**
* Register every wp-forge ability with the WordPress Abilities API.
*
* @return void
*/
public function register_wordpress_abilities() {
if ( ! function_exists( 'wp_register_ability' ) ) {
return;
}
foreach ( $this->abilities as $name => $ability ) {
$capability = isset( $ability['capability'] ) ? $ability['capability'] : 'edit_posts';
wp_register_ability(
$name,
array(
'label' => $ability['label'],
'description' => $ability['description'],
'category' => 'site',
'input_schema' => $this->resolve_input_schema( $ability['input_schema'] ),
'output_schema' => $this->response_schema(),
'execute_callback' => function ( $input ) use ( $name ) {
return $this->call( $name, is_array( $input ) ? $input : array() );
},
'permission_callback' => function () use ( $capability ) {
return function_exists( 'current_user_can' ) ? current_user_can( $capability ) : false;
},
'meta' => array(
'annotations' => $ability['meta_annotations'],
'show_in_rest' => true,
),
)
);
}
}
/**
* Call an ability.
*
* @param string $name Ability name.
* @param array<string,mixed> $parameters Ability parameters.
* @return array<string,mixed>
*/
public function call( $name, $parameters = array() ) {
$internal = $this->tool_to_ability_name( $name );
if ( ! isset( $this->abilities[ $internal ] ) ) {
return Response::error( 'Unknown ability: ' . $name, 404 );
}
$capability = isset( $this->abilities[ $internal ]['capability'] ) ? $this->abilities[ $internal ]['capability'] : 'edit_posts';
if ( function_exists( 'current_user_can' ) && ! current_user_can( $capability ) ) {
return Response::error( 'Access denied for ability: ' . $this->ability_to_tool_name( $internal ), 403 );
}
$callback = $this->abilities[ $internal ]['callback'];
$result = call_user_func( $callback, is_array( $parameters ) ? $parameters : array() );
$result = Response::unwrap_wp_error( $result );
if ( is_array( $result ) && isset( $result['statusCode'], $result['status'], $result['message'] ) ) {
return $result;
}
return Response::success( $result );
}
/**
* Convert internal ability name to MCP tool name.
*
* @param string $name Internal ability name.
* @return string
*/
public function ability_to_tool_name( $name ) {
return str_replace( '/', '-', $name );
}
/**
* Convert MCP tool name to internal ability name.
*
* @param string $name MCP tool name or internal name.
* @return string
*/
public function tool_to_ability_name( $name ) {
$name = (string) $name;
if ( 0 === strpos( $name, self::INTERNAL_PREFIX ) ) {
return $name;
}
if ( 0 === strpos( $name, self::TOOL_PREFIX ) ) {
return self::INTERNAL_PREFIX . substr( $name, strlen( self::TOOL_PREFIX ) );
}
return $name;
}
/**
* Register an ability.
*
* @param string $name Internal ability name.
* @param string $label Human label.
* @param string $description Description.
* @param array<string,mixed>|callable $input_schema JSON schema or schema factory.
* @param callable $callback Callback.
* @param bool $read_only Whether ability is read-only.
* @param string $capability Required WordPress capability.
* @param array<string,bool> $annotations Core ability annotation overrides.
* @return void
*/
private function add_ability( $name, $label, $description, $input_schema, $callback, $read_only = true, $capability = 'edit_posts', $annotations = array() ) {
$core_annotations = $this->core_ability_annotations( $read_only, $annotations );
$this->abilities[ $name ] = array(
'label' => $label,
'description' => $description,
'input_schema' => $input_schema,
'callback' => $callback,
'annotations' => $this->mcp_tool_annotations( $core_annotations ),
'meta_annotations' => $core_annotations,
'capability' => $capability,
);
}
/**
* Build WordPress Abilities API annotations for a tool.
*
* @param bool $read_only Whether ability is read-only.
* @param array<string,bool> $overrides Annotation overrides.
* @return array<string,bool>
*/
private function core_ability_annotations( $read_only, $overrides = array() ) {
$annotations = array(
'readonly' => (bool) $read_only,
'destructive' => false,
'idempotent' => (bool) $read_only,
);
foreach ( array( 'readonly', 'destructive', 'idempotent' ) as $key ) {
if ( array_key_exists( $key, $overrides ) ) {
$annotations[ $key ] = (bool) $overrides[ $key ];
}
}
return $annotations;
}
/**
* Convert core ability annotations to MCP tool hints.
*
* @param array<string,bool> $annotations Core ability annotations.
* @return array<string,bool>
*/
private function mcp_tool_annotations( $annotations ) {
return array(
'readOnlyHint' => ! empty( $annotations['readonly'] ),
'destructiveHint' => ! empty( $annotations['destructive'] ),
'idempotentHint' => ! empty( $annotations['idempotent'] ),
);
}
/**
* Resolve an ability input schema.
*
* Some schema fields depend on WordPress runtime registrations that plugins
* commonly add during init, so schema factories are evaluated only when the
* schema is exposed.
*
* @param array<string,mixed>|callable $input_schema JSON schema or schema factory.
* @return array<string,mixed>
*/
private function resolve_input_schema( $input_schema ) {
return is_callable( $input_schema ) ? call_user_func( $input_schema ) : $input_schema;
}
/**
* Generic response schema used by all ability wrappers.
*
* @return array<string,mixed>
*/
private function response_schema() {
return array(
'type' => 'object',
'properties' => array(
'status' => array(
'type' => 'string',
'description' => 'The response status.',
),
'statusCode' => array(
'type' => 'integer',
'description' => 'The HTTP-style response status code.',
),
'message' => array(
'description' => 'The ability result payload or an error message.',
'type' => array( 'array', 'object', 'string', 'number', 'boolean', 'null' ),
),
'data' => array(
'description' => 'The ability result data.',
'type' => array( 'array', 'object', 'string', 'number', 'boolean', 'null' ),
),
),
'additionalProperties' => true,
);
}
/**
* Register all non-WooCommerce abilities.
*
* @return void
*/
private function register_default_abilities() {
$this->add_content_abilities();
$this->add_taxonomy_abilities();
$this->add_media_abilities();
$this->add_site_abilities();
$this->add_plugin_abilities();
$this->add_theme_abilities();
$this->add_option_abilities();
$this->add_comment_abilities();
$this->add_site_health_abilities();
$this->add_error_log_abilities();
$this->add_wp_cli_abilities();
$this->add_style_abilities();
$this->add_rest_catalog_abilities();
}
/**
* JSON object schema helper.
*
* @param array<string,mixed> $properties Properties.
* @param array<int,string> $required Required keys.
* @return array<string,mixed>
*/
private function schema( $properties = array(), $required = array() ) {
$schema = array(
'type' => 'object',
'properties' => $properties ? $properties : new \stdClass(),
'additionalProperties' => false,
'default' => new \stdClass(),
);
if ( $required ) {
$schema['required'] = $required;
}
return $schema;
}
/**
* String schema property.
*
* @param string $description Description.
* @param string|null $default Default value.
* @return array<string,mixed>
*/
private function string_prop( $description, $default = null ) {
$prop = array(
'type' => 'string',
'description' => $description,
);
if ( null !== $default ) {
$prop['default'] = $default;
}
return $prop;
}
/**
* String schema property with a runtime enum when values are discoverable.
*
* @param string $description Description.
* @param array<int,string> $values Enum values.
* @param string|null $default Default value.
* @return array<string,mixed>
*/
private function enum_string_prop( $description, $values, $default = null ) {
$values = array_values( array_unique( array_filter( array_map( 'strval', $values ), 'strlen' ) ) );
sort( $values );
$prop = $this->string_prop( $description, $default );
if ( $values ) {
$prop['enum'] = $values;
}
return $prop;
}
/**
* Get registered post type slugs.
*
* @return array<int,string>
*/
private function get_registered_post_type_slugs() {
return function_exists( 'get_post_types' ) ? array_values( get_post_types( array(), 'names' ) ) : array();
}
/**
* Get registered taxonomy slugs.
*
* @return array<int,string>
*/
private function get_registered_taxonomy_slugs() {
return function_exists( 'get_taxonomies' ) ? array_values( get_taxonomies( array(), 'names' ) ) : array();
}
/**
* Get registered post status names.
*
* @param bool $include_any Include the WP_Query any pseudo-status.
* @return array<int,string>
*/
private function get_registered_post_status_names( $include_any = false ) {
$statuses = function_exists( 'get_post_stati' ) ? array_values( get_post_stati( array(), 'names' ) ) : array();
if ( $include_any ) {
$statuses[] = 'any';
}
return $statuses;
}
/**
* Get editable role slugs.
*
* @return array<int,string>
*/
private function get_editable_role_slugs() {
if ( function_exists( 'get_editable_roles' ) ) {
return array_keys( get_editable_roles() );
}
if ( function_exists( 'wp_roles' ) ) {
$roles = wp_roles();
if ( isset( $roles->roles ) && is_array( $roles->roles ) ) {
return array_keys( $roles->roles );
}
}
return array();
}
/**
* Get allowed MIME types.
*
* @return array<int,string>
*/
private function get_allowed_mime_types() {
return function_exists( 'get_allowed_mime_types' ) ? array_values( get_allowed_mime_types() ) : array();
}
/**
* Integer schema property.
*
* @param string $description Description.
* @param int|null $default Default value.
* @return array<string,mixed>
*/
private function int_prop( $description, $default = null ) {
$prop = array(
'type' => 'integer',
'description' => $description,
);
if ( null !== $default ) {
$prop['default'] = $default;
}
return $prop;
}
/**
* Boolean schema property.
*
* @param string $description Description.
* @param bool|null $default Default value.
* @return array<string,mixed>
*/
private function bool_prop( $description, $default = null ) {
$prop = array(
'type' => 'boolean',
'description' => $description,
);
if ( null !== $default ) {
$prop['default'] = $default;
}
return $prop;
}
/**
* Normalize a WordPress key-like value.
*
* @param mixed $value Value to normalize.
* @return string
*/
private function sanitize_key_value( $value ) {
if ( function_exists( 'sanitize_key' ) ) {
return sanitize_key( $value );
}
return preg_replace( '/[^a-z0-9_\-]/', '', strtolower( trim( (string) $value ) ) );
}
/**
* Normalize a name prefix to MCP tool hyphen form.
*
* @param string $name Name.
* @return string
*/
private function normalize_tool_name( $name ) {
$name = trim( str_replace( '/', '-', $name ), '-' );
return $name ? $name : '';
}
/**
* Ensure WordPress runtime exists.
*
* @return array<string,mixed>|null
*/
private function require_wordpress() {
if ( ! function_exists( 'get_posts' ) ) {
return Response::error( 'This ability requires a WordPress runtime.', 500 );
}
return null;
}
/**
* Search content items.
*
* @param string $post_type Post type.
* @param array<string,mixed> $params Params.
* @return array<string,mixed>|array<int,array<string,mixed>>
*/
private function search_content_items( $post_type, $params ) {
if ( isset( $params['status'] ) ) {
$status_check = $this->validate_post_status( $params['status'], 'query' );
if ( isset( $status_check['status'] ) && 'error' === $status_check['status'] ) {
return $status_check;
}
$params['status'] = $status_check['post_status'];
}
if ( isset( $params['mime_type'] ) ) {
$mime_type_check = $this->validate_mime_type( $params['mime_type'] );
if ( isset( $mime_type_check['status'] ) && 'error' === $mime_type_check['status'] ) {
return $mime_type_check;
}
$params['mime_type'] = $mime_type_check['mime_type'];
}
$missing = $this->require_wordpress();
if ( $missing ) {
return $missing;
}
$args = array(
'post_type' => $post_type,
'post_status' => isset( $params['status'] ) ? $params['status'] : 'publish',
's' => isset( $params['search'] ) ? $params['search'] : '',
'paged' => isset( $params['page'] ) ? max( 1, (int) $params['page'] ) : 1,
'posts_per_page' => isset( $params['per_page'] ) ? max( 1, min( 100, (int) $params['per_page'] ) ) : 10,
);
if ( isset( $params['mime_type'] ) ) {
$args['post_mime_type'] = $params['mime_type'];
}
return array_map( array( $this, 'format_content_item' ), get_posts( $args ) );
}
/**
* Search content for any registered post type.
*
* @param array<string,mixed> $params Params.
* @return array<string,mixed>|array<int,array<string,mixed>>
*/
private function search_content( $params ) {
$post_type_check = $this->validate_post_type( $params['post_type'] );
if ( isset( $post_type_check['status'] ) && 'error' === $post_type_check['status'] ) {
return $post_type_check;
}
if ( isset( $params['status'] ) ) {
$status_check = $this->validate_post_status( $params['status'], 'query' );
if ( isset( $status_check['status'] ) && 'error' === $status_check['status'] ) {
return $status_check;
}
$params['status'] = $status_check['post_status'];
}
$missing = $this->require_wordpress();
if ( $missing ) {
return $missing;
}
$args = array(
'post_type' => $post_type_check['post_type'],
'post_status' => isset( $params['status'] ) ? $params['status'] : 'publish',
's' => isset( $params['query'] ) ? $params['query'] : '',
'paged' => isset( $params['page'] ) ? max( 1, (int) $params['page'] ) : 1,
'posts_per_page' => isset( $params['per_page'] ) ? max( 1, min( 100, (int) $params['per_page'] ) ) : 10,
'orderby' => $this->normalize_content_orderby( isset( $params['orderby'] ) ? $params['orderby'] : 'date' ),
'order' => $this->normalize_sort_order( isset( $params['order'] ) ? $params['order'] : 'desc' ),
);
if ( isset( $params['author'] ) ) {
$args['author'] = (int) $params['author'];
}
if ( ! empty( $params['taxonomy_query'] ) && is_array( $params['taxonomy_query'] ) ) {
$taxonomy = isset( $params['taxonomy_query']['taxonomy'] ) ? (string) $params['taxonomy_query']['taxonomy'] : '';
$terms = isset( $params['taxonomy_query']['terms'] ) && is_array( $params['taxonomy_query']['terms'] ) ? $params['taxonomy_query']['terms'] : array();
$taxonomy_check = $this->validate_post_type_taxonomy( $post_type_check, $taxonomy );
if ( isset( $taxonomy_check['status'] ) && 'error' === $taxonomy_check['status'] ) {
return $taxonomy_check;
}
if ( '' === $taxonomy || array() === $terms ) {
return Response::error( 'taxonomy_query requires a taxonomy and at least one term.', 400 );
}
$args['tax_query'] = array(
array(
'taxonomy' => $taxonomy,
'field' => $this->taxonomy_terms_are_ids( $terms ) ? 'term_id' : 'slug',
'terms' => $terms,
),
);
}
if ( ! empty( $params['date_query'] ) && is_array( $params['date_query'] ) ) {
$date_query = array();
foreach ( array( 'after', 'before' ) as $key ) {
if ( ! empty( $params['date_query'][ $key ] ) ) {
$date_query[ $key ] = (string) $params['date_query'][ $key ];
}
}
if ( $date_query ) {
$args['date_query'] = array( $date_query );
}
}
return array_map( array( $this, 'format_content_item' ), get_posts( $args ) );
}
/**
* Get content by ID or slug.
*
* @param array<string,mixed> $params Params.
* @return array<string,mixed>
*/
private function get_content( $params ) {
$post_type_check = $this->validate_post_type( $params['post_type'] );
if ( isset( $post_type_check['status'] ) && 'error' === $post_type_check['status'] ) {
return $post_type_check;
}
if ( isset( $params['id'] ) ) {
$item = $this->get_content_item( (int) $params['id'], $post_type_check['post_type'] );
} elseif ( ! empty( $params['slug'] ) ) {
$item = $this->get_content_item_by_slug( $post_type_check['post_type'], (string) $params['slug'] );
} else {
return Response::error( 'content_get requires either id or slug.', 400 );
}
if ( isset( $item['status'] ) && 'error' === $item['status'] ) {
return $item;
}
return $this->filter_content_fields( $item, isset( $params['fields'] ) && is_array( $params['fields'] ) ? $params['fields'] : array() );
}
/**
* Create or update content.
*
* @param array<string,mixed> $params Params.
* @return array<string,mixed>
*/
private function save_content( $params ) {
$post_type_check = $this->validate_post_type( $params['post_type'] );
if ( isset( $post_type_check['status'] ) && 'error' === $post_type_check['status'] ) {
return $post_type_check;
}
$is_update = isset( $params['id'] );
if ( ! $is_update && ( ! isset( $params['title'] ) || '' === trim( (string) $params['title'] ) ) ) {
return Response::error( 'content_save requires title when creating content.', 400 );
}
if ( isset( $params['status'] ) ) {
$status_check = $this->validate_post_status( $params['status'], 'write' );
if ( isset( $status_check['status'] ) && 'error' === $status_check['status'] ) {
return $status_check;
}
$params['status'] = $status_check['post_status'];
}
if ( isset( $params['parent_id'] ) ) {
$parent_check = $this->validate_content_parent( $post_type_check, (int) $params['parent_id'] );
if ( isset( $parent_check['status'] ) && 'error' === $parent_check['status'] ) {
return $parent_check;
}
}
if ( isset( $params['taxonomies'] ) ) {
$taxonomy_check = $this->validate_content_taxonomies( $post_type_check, $params['taxonomies'] );
if ( isset( $taxonomy_check['status'] ) && 'error' === $taxonomy_check['status'] ) {
return $taxonomy_check;
}
}
if ( ! function_exists( 'wp_insert_post' ) || ! function_exists( 'wp_update_post' ) ) {
return Response::error( 'This ability requires a WordPress runtime.', 500 );
}
$post = $this->content_post_args( $post_type_check['post_type'], $params );
if ( $is_update ) {
$existing = get_post( (int) $params['id'] );
if ( ! $existing ) {
return Response::error( 'Content item not found.', 404 );
}
if ( $post_type_check['post_type'] !== $existing->post_type ) {
return Response::error( 'Content item ' . (int) $params['id'] . ' is not a ' . $post_type_check['post_type'] . '.', 400 );
}
$post['ID'] = (int) $params['id'];
$id = Response::unwrap_wp_error( wp_update_post( $post, true ) );
} else {
$id = Response::unwrap_wp_error( wp_insert_post( $post, true ) );
}
if ( is_array( $id ) && isset( $id['status'] ) && 'error' === $id['status'] ) {
return $id;
}
$this->apply_content_taxonomies( (int) $id, isset( $params['taxonomies'] ) && is_array( $params['taxonomies'] ) ? $params['taxonomies'] : array() );
$this->apply_content_meta( (int) $id, isset( $params['meta'] ) && is_array( $params['meta'] ) ? $params['meta'] : array() );
if ( isset( $params['featured_media_id'] ) ) {
$this->apply_featured_media( (int) $id, (int) $params['featured_media_id'] );
}
return $this->get_content_item( (int) $id, $post_type_check['post_type'] );
}
/**
* Delete content.
*
* @param array<string,mixed> $params Params.
* @return array<string,mixed>
*/
private function delete_content( $params ) {
$item = $this->get_content_item( (int) $params['id'], $params['post_type'] );
if ( isset( $item['status'] ) && 'error' === $item['status'] ) {
return $item;
}
$force = isset( $params['force'] ) ? (bool) $params['force'] : false;
$result = function_exists( 'wp_delete_post' ) ? wp_delete_post( (int) $params['id'], $force ) : false;
return array(
'id' => (int) $params['id'],
'deleted' => (bool) $result,
'force' => $force,
);
}
/**
* Get a content item.
*
* @param int $id Post ID.
* @param string $post_type Expected post type.
* @return array<string,mixed>
*/
private function get_content_item( $id, $post_type ) {
$missing = $this->require_wordpress();
if ( $missing ) {
return $missing;
}
$post = get_post( $id );
if ( ! $post || $post_type !== $post->post_type ) {
return Response::error( 'Item not found.', 404 );
}
return $this->format_content_item( $post );
}
/**
* Get a content item by slug.
*
* @param string $post_type Post type.
* @param string $slug Post slug.
* @return array<string,mixed>
*/
private function get_content_item_by_slug( $post_type, $slug ) {
$missing = $this->require_wordpress();
if ( $missing ) {
return $missing;
}
$posts = get_posts(
array(
'post_type' => $post_type,
'name' => $slug,
'post_status' => 'any',
'posts_per_page' => 1,
)
);
if ( empty( $posts ) ) {
return Response::error( 'Item not found.', 404 );
}
return $this->format_content_item( $posts[0] );
}
/**
* Insert a content item.
*
* @param string $post_type Post type.
* @param array<string,mixed> $params Params.
* @return array<string,mixed>
*/
private function insert_content_item( $post_type, $params ) {
$missing = $this->require_wordpress();
if ( $missing ) {
return $missing;
}
$id = wp_insert_post(
array(
'post_type' => $post_type,
'post_title' => isset( $params['title'] ) ? $params['title'] : '',
'post_content' => isset( $params['content'] ) ? $params['content'] : '',
'post_excerpt' => isset( $params['excerpt'] ) ? $params['excerpt'] : '',
'post_status' => isset( $params['status'] ) ? $params['status'] : 'draft',
),
true
);
return Response::unwrap_wp_error( $id );
}
/**
* Update a content item.
*
* @param int $id Post ID.
* @param string $post_type Post type.
* @param array<string,mixed> $params Params.
* @return array<string,mixed>|int
*/
private function update_content_item( $id, $post_type, $params ) {
$item = $this->get_content_item( $id, $post_type );
if ( isset( $item['status'] ) && 'error' === $item['status'] ) {
return $item;
}
$post = array( 'ID' => $id );
foreach ( array( 'title' => 'post_title', 'content' => 'post_content', 'excerpt' => 'post_excerpt', 'status' => 'post_status' ) as $param => $field ) {
if ( isset( $params[ $param ] ) ) {
$post[ $field ] = $params[ $param ];
}
}
return Response::unwrap_wp_error( wp_update_post( $post, true ) );
}
/**
* Delete a content item.
*
* @param int $id Post ID.
* @param string $post_type Post type.
* @return array<string,mixed>|bool
*/
private function delete_content_item( $id, $post_type ) {
$item = $this->get_content_item( $id, $post_type );
if ( isset( $item['status'] ) && 'error' === $item['status'] ) {
return $item;
}
return (bool) wp_delete_post( $id, true );
}
/**
* Format a content item.
*
* @param mixed $post Post object.
* @return array<string,mixed>
*/
private function format_content_item( $post ) {
return array(
'id' => (int) $post->ID,
'type' => $post->post_type,
'status' => $post->post_status,
'title' => function_exists( 'get_the_title' ) ? get_the_title( $post ) : $post->post_title,
'slug' => $post->post_name,
'link' => function_exists( 'get_permalink' ) ? get_permalink( $post ) : '',
'date' => $post->post_date,
'modified' => $post->post_modified,
'excerpt' => $post->post_excerpt,
'content' => $post->post_content,
'author' => isset( $post->post_author ) ? (int) $post->post_author : 0,
'parent_id' => isset( $post->post_parent ) ? (int) $post->post_parent : 0,
'featured_media_id' => function_exists( 'get_post_thumbnail_id' ) ? (int) get_post_thumbnail_id( $post ) : 0,
'mime_type' => isset( $post->post_mime_type ) ? $post->post_mime_type : '',
'source_url' => function_exists( 'wp_get_attachment_url' ) && 'attachment' === $post->post_type ? wp_get_attachment_url( $post->ID ) : '',
);
}
/**
* Validate a post type and return its runtime metadata.
*
* @param string $post_type Post type slug.
* @return array<string,mixed>
*/
private function validate_post_type( $post_type ) {
if ( ! function_exists( 'get_post_types' ) ) {
return Response::error( 'This ability requires a WordPress runtime.', 500 );
}
$post_type = $this->sanitize_key_value( $post_type );
$type = function_exists( 'get_post_type_object' ) ? get_post_type_object( $post_type ) : null;
if ( ! $type ) {
$types = get_post_types( array(), 'objects' );
$type = isset( $types[ $post_type ] ) ? $types[ $post_type ] : null;
}
if ( ! $type ) {
return Response::error( 'Unknown post type: ' . $post_type, 404 );
}
return array(
'post_type' => $post_type,
'type' => $type,
'hierarchical' => (bool) $type->hierarchical,
'taxonomies' => $this->get_post_type_taxonomies( $post_type, $type ),
);
}
/**
* Validate parent assignment for a content type.
*
* @param array<string,mixed> $post_type_check Post type metadata.
* @param int $parent_id Parent content ID.
* @return array<string,mixed>