mirrored from git://develop.git.wordpress.org/
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
rest-api.php
3318 lines (2864 loc) · 92.7 KB
/
rest-api.php
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
/**
* REST API functions.
*
* @package WordPress
* @subpackage REST_API
* @since 4.4.0
*/
/**
* Version number for our API.
*
* @var string
*/
define( 'REST_API_VERSION', '2.0' );
/**
* Registers a REST API route.
*
* Note: Do not use before the {@see 'rest_api_init'} hook.
*
* @since 4.4.0
* @since 5.1.0 Added a `_doing_it_wrong()` notice when not called on or after the `rest_api_init` hook.
* @since 5.5.0 Added a `_doing_it_wrong()` notice when the required `permission_callback` argument is not set.
*
* @param string $namespace The first URL segment after core prefix. Should be unique to your package/plugin.
* @param string $route The base URL for route you are adding.
* @param array $args Optional. Either an array of options for the endpoint, or an array of arrays for
* multiple methods. Default empty array.
* @param bool $override Optional. If the route already exists, should we override it? True overrides,
* false merges (with newer overriding if duplicate keys exist). Default false.
* @return bool True on success, false on error.
*/
function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
if ( empty( $namespace ) ) {
/*
* Non-namespaced routes are not allowed, with the exception of the main
* and namespace indexes. If you really need to register a
* non-namespaced route, call `WP_REST_Server::register_route` directly.
*/
_doing_it_wrong( 'register_rest_route', __( 'Routes must be namespaced with plugin or theme name and version.' ), '4.4.0' );
return false;
} elseif ( empty( $route ) ) {
_doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
return false;
}
$clean_namespace = trim( $namespace, '/' );
if ( $clean_namespace !== $namespace ) {
_doing_it_wrong( __FUNCTION__, __( 'Namespace must not start or end with a slash.' ), '5.4.2' );
}
if ( ! did_action( 'rest_api_init' ) ) {
_doing_it_wrong(
'register_rest_route',
sprintf(
/* translators: %s: rest_api_init */
__( 'REST API routes must be registered on the %s action.' ),
'<code>rest_api_init</code>'
),
'5.1.0'
);
}
if ( isset( $args['args'] ) ) {
$common_args = $args['args'];
unset( $args['args'] );
} else {
$common_args = array();
}
if ( isset( $args['callback'] ) ) {
// Upgrade a single set to multiple.
$args = array( $args );
}
$defaults = array(
'methods' => 'GET',
'callback' => null,
'args' => array(),
);
foreach ( $args as $key => &$arg_group ) {
if ( ! is_numeric( $key ) ) {
// Route option, skip here.
continue;
}
$arg_group = array_merge( $defaults, $arg_group );
$arg_group['args'] = array_merge( $common_args, $arg_group['args'] );
if ( ! isset( $arg_group['permission_callback'] ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: 1: The REST API route being registered, 2: The argument name, 3: The suggested function name. */
__( 'The REST API route definition for %1$s is missing the required %2$s argument. For REST API routes that are intended to be public, use %3$s as the permission callback.' ),
'<code>' . $clean_namespace . '/' . trim( $route, '/' ) . '</code>',
'<code>permission_callback</code>',
'<code>__return_true</code>'
),
'5.5.0'
);
}
}
$full_route = '/' . $clean_namespace . '/' . trim( $route, '/' );
rest_get_server()->register_route( $clean_namespace, $full_route, $args, $override );
return true;
}
/**
* Registers a new field on an existing WordPress object type.
*
* @since 4.7.0
*
* @global array $wp_rest_additional_fields Holds registered fields, organized
* by object type.
*
* @param string|array $object_type Object(s) the field is being registered to,
* "post"|"term"|"comment" etc.
* @param string $attribute The attribute name.
* @param array $args {
* Optional. An array of arguments used to handle the registered field.
*
* @type callable|null $get_callback Optional. The callback function used to retrieve the field value. Default is
* 'null', the field will not be returned in the response. The function will
* be passed the prepared object data.
* @type callable|null $update_callback Optional. The callback function used to set and update the field value. Default
* is 'null', the value cannot be set or updated. The function will be passed
* the model object, like WP_Post.
* @type array|null $schema Optional. The schema for this field.
* Default is 'null', no schema entry will be returned.
* }
*/
function register_rest_field( $object_type, $attribute, $args = array() ) {
global $wp_rest_additional_fields;
$defaults = array(
'get_callback' => null,
'update_callback' => null,
'schema' => null,
);
$args = wp_parse_args( $args, $defaults );
$object_types = (array) $object_type;
foreach ( $object_types as $object_type ) {
$wp_rest_additional_fields[ $object_type ][ $attribute ] = $args;
}
}
/**
* Registers rewrite rules for the REST API.
*
* @since 4.4.0
*
* @see rest_api_register_rewrites()
* @global WP $wp Current WordPress environment instance.
*/
function rest_api_init() {
rest_api_register_rewrites();
global $wp;
$wp->add_query_var( 'rest_route' );
}
/**
* Adds REST rewrite rules.
*
* @since 4.4.0
*
* @see add_rewrite_rule()
* @global WP_Rewrite $wp_rewrite WordPress rewrite component.
*/
function rest_api_register_rewrites() {
global $wp_rewrite;
add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' );
add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' );
add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' );
add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' );
}
/**
* Registers the default REST API filters.
*
* Attached to the {@see 'rest_api_init'} action
* to make testing and disabling these filters easier.
*
* @since 4.4.0
*/
function rest_api_default_filters() {
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
// Deprecated reporting.
add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 );
add_filter( 'deprecated_function_trigger_error', '__return_false' );
add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 );
add_filter( 'deprecated_argument_trigger_error', '__return_false' );
add_action( 'doing_it_wrong_run', 'rest_handle_doing_it_wrong', 10, 3 );
add_filter( 'doing_it_wrong_trigger_error', '__return_false' );
}
// Default serving.
add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );
add_filter( 'rest_index', 'rest_add_application_passwords_to_index' );
}
/**
* Registers default REST API routes.
*
* @since 4.7.0
*/
function create_initial_rest_routes() {
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
$controller = $post_type->get_rest_controller();
if ( ! $controller ) {
continue;
}
$controller->register_routes();
if ( post_type_supports( $post_type->name, 'revisions' ) ) {
$revisions_controller = new WP_REST_Revisions_Controller( $post_type->name );
$revisions_controller->register_routes();
}
if ( 'attachment' !== $post_type->name ) {
$autosaves_controller = new WP_REST_Autosaves_Controller( $post_type->name );
$autosaves_controller->register_routes();
}
}
// Post types.
$controller = new WP_REST_Post_Types_Controller;
$controller->register_routes();
// Post statuses.
$controller = new WP_REST_Post_Statuses_Controller;
$controller->register_routes();
// Taxonomies.
$controller = new WP_REST_Taxonomies_Controller;
$controller->register_routes();
// Terms.
foreach ( get_taxonomies( array( 'show_in_rest' => true ), 'object' ) as $taxonomy ) {
$controller = $taxonomy->get_rest_controller();
if ( ! $controller ) {
continue;
}
$controller->register_routes();
}
// Users.
$controller = new WP_REST_Users_Controller;
$controller->register_routes();
// Application Passwords
$controller = new WP_REST_Application_Passwords_Controller();
$controller->register_routes();
// Comments.
$controller = new WP_REST_Comments_Controller;
$controller->register_routes();
$search_handlers = array(
new WP_REST_Post_Search_Handler(),
new WP_REST_Term_Search_Handler(),
new WP_REST_Post_Format_Search_Handler(),
);
/**
* Filters the search handlers to use in the REST search controller.
*
* @since 5.0.0
*
* @param array $search_handlers List of search handlers to use in the controller. Each search
* handler instance must extend the `WP_REST_Search_Handler` class.
* Default is only a handler for posts.
*/
$search_handlers = apply_filters( 'wp_rest_search_handlers', $search_handlers );
$controller = new WP_REST_Search_Controller( $search_handlers );
$controller->register_routes();
// Block Renderer.
$controller = new WP_REST_Block_Renderer_Controller;
$controller->register_routes();
// Block Types.
$controller = new WP_REST_Block_Types_Controller();
$controller->register_routes();
// Settings.
$controller = new WP_REST_Settings_Controller;
$controller->register_routes();
// Themes.
$controller = new WP_REST_Themes_Controller;
$controller->register_routes();
// Plugins.
$controller = new WP_REST_Plugins_Controller();
$controller->register_routes();
// Sidebars.
$controller = new WP_REST_Sidebars_Controller();
$controller->register_routes();
// Widget Types.
$controller = new WP_REST_Widget_Types_Controller();
$controller->register_routes();
// Widgets.
$controller = new WP_REST_Widgets_Controller();
$controller->register_routes();
// Block Directory.
$controller = new WP_REST_Block_Directory_Controller();
$controller->register_routes();
// Pattern Directory.
$controller = new WP_REST_Pattern_Directory_Controller();
$controller->register_routes();
// Site Health.
$site_health = WP_Site_Health::get_instance();
$controller = new WP_REST_Site_Health_Controller( $site_health );
$controller->register_routes();
// URL Details.
$controller = new WP_REST_URL_Details_Controller();
$controller->register_routes();
}
/**
* Loads the REST API.
*
* @since 4.4.0
*
* @global WP $wp Current WordPress environment instance.
*/
function rest_api_loaded() {
if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
return;
}
/**
* Whether this is a REST Request.
*
* @since 4.4.0
* @var bool
*/
define( 'REST_REQUEST', true );
// Initialize the server.
$server = rest_get_server();
// Fire off the request.
$route = untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] );
if ( empty( $route ) ) {
$route = '/';
}
$server->serve_request( $route );
// We're done.
die();
}
/**
* Retrieves the URL prefix for any API resource.
*
* @since 4.4.0
*
* @return string Prefix.
*/
function rest_get_url_prefix() {
/**
* Filters the REST URL prefix.
*
* @since 4.4.0
*
* @param string $prefix URL prefix. Default 'wp-json'.
*/
return apply_filters( 'rest_url_prefix', 'wp-json' );
}
/**
* Retrieves the URL to a REST endpoint on a site.
*
* Note: The returned URL is NOT escaped.
*
* @since 4.4.0
*
* @todo Check if this is even necessary
* @global WP_Rewrite $wp_rewrite WordPress rewrite component.
*
* @param int|null $blog_id Optional. Blog ID. Default of null returns URL for current blog.
* @param string $path Optional. REST route. Default '/'.
* @param string $scheme Optional. Sanitization scheme. Default 'rest'.
* @return string Full URL to the endpoint.
*/
function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
if ( empty( $path ) ) {
$path = '/';
}
$path = '/' . ltrim( $path, '/' );
if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
global $wp_rewrite;
if ( $wp_rewrite->using_index_permalinks() ) {
$url = get_home_url( $blog_id, $wp_rewrite->index . '/' . rest_get_url_prefix(), $scheme );
} else {
$url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
}
$url .= $path;
} else {
$url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
// nginx only allows HTTP/1.0 methods when redirecting from / to /index.php.
// To work around this, we manually add index.php to the URL, avoiding the redirect.
if ( 'index.php' !== substr( $url, 9 ) ) {
$url .= 'index.php';
}
$url = add_query_arg( 'rest_route', $path, $url );
}
if ( is_ssl() && isset( $_SERVER['SERVER_NAME'] ) ) {
// If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
if ( parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) === $_SERVER['SERVER_NAME'] ) {
$url = set_url_scheme( $url, 'https' );
}
}
if ( is_admin() && force_ssl_admin() ) {
/*
* In this situation the home URL may be http:, and `is_ssl()` may be false,
* but the admin is served over https: (one way or another), so REST API usage
* will be blocked by browsers unless it is also served over HTTPS.
*/
$url = set_url_scheme( $url, 'https' );
}
/**
* Filters the REST URL.
*
* Use this filter to adjust the url returned by the get_rest_url() function.
*
* @since 4.4.0
*
* @param string $url REST URL.
* @param string $path REST route.
* @param int|null $blog_id Blog ID.
* @param string $scheme Sanitization scheme.
*/
return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
}
/**
* Retrieves the URL to a REST endpoint.
*
* Note: The returned URL is NOT escaped.
*
* @since 4.4.0
*
* @param string $path Optional. REST route. Default empty.
* @param string $scheme Optional. Sanitization scheme. Default 'rest'.
* @return string Full URL to the endpoint.
*/
function rest_url( $path = '', $scheme = 'rest' ) {
return get_rest_url( null, $path, $scheme );
}
/**
* Do a REST request.
*
* Used primarily to route internal requests through WP_REST_Server.
*
* @since 4.4.0
*
* @param WP_REST_Request|string $request Request.
* @return WP_REST_Response REST response.
*/
function rest_do_request( $request ) {
$request = rest_ensure_request( $request );
return rest_get_server()->dispatch( $request );
}
/**
* Retrieves the current REST server instance.
*
* Instantiates a new instance if none exists already.
*
* @since 4.5.0
*
* @global WP_REST_Server $wp_rest_server REST server instance.
*
* @return WP_REST_Server REST server instance.
*/
function rest_get_server() {
/* @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
if ( empty( $wp_rest_server ) ) {
/**
* Filters the REST Server Class.
*
* This filter allows you to adjust the server class used by the REST API, using a
* different class to handle requests.
*
* @since 4.4.0
*
* @param string $class_name The name of the server class. Default 'WP_REST_Server'.
*/
$wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
$wp_rest_server = new $wp_rest_server_class;
/**
* Fires when preparing to serve a REST API request.
*
* Endpoint objects should be created and register their hooks on this action rather
* than another action to ensure they're only loaded when needed.
*
* @since 4.4.0
*
* @param WP_REST_Server $wp_rest_server Server object.
*/
do_action( 'rest_api_init', $wp_rest_server );
}
return $wp_rest_server;
}
/**
* Ensures request arguments are a request object (for consistency).
*
* @since 4.4.0
* @since 5.3.0 Accept string argument for the request path.
*
* @param array|string|WP_REST_Request $request Request to check.
* @return WP_REST_Request REST request instance.
*/
function rest_ensure_request( $request ) {
if ( $request instanceof WP_REST_Request ) {
return $request;
}
if ( is_string( $request ) ) {
return new WP_REST_Request( 'GET', $request );
}
return new WP_REST_Request( 'GET', '', $request );
}
/**
* Ensures a REST response is a response object (for consistency).
*
* This implements WP_REST_Response, allowing usage of `set_status`/`header`/etc
* without needing to double-check the object. Will also allow WP_Error to indicate error
* responses, so users should immediately check for this value.
*
* @since 4.4.0
*
* @param WP_REST_Response|WP_Error|WP_HTTP_Response|mixed $response Response to check.
* @return WP_REST_Response|WP_Error If response generated an error, WP_Error, if response
* is already an instance, WP_REST_Response, otherwise
* returns a new WP_REST_Response instance.
*/
function rest_ensure_response( $response ) {
if ( is_wp_error( $response ) ) {
return $response;
}
if ( $response instanceof WP_REST_Response ) {
return $response;
}
// While WP_HTTP_Response is the base class of WP_REST_Response, it doesn't provide
// all the required methods used in WP_REST_Server::dispatch().
if ( $response instanceof WP_HTTP_Response ) {
return new WP_REST_Response(
$response->get_data(),
$response->get_status(),
$response->get_headers()
);
}
return new WP_REST_Response( $response );
}
/**
* Handles _deprecated_function() errors.
*
* @since 4.4.0
*
* @param string $function The function that was called.
* @param string $replacement The function that should have been called.
* @param string $version Version.
*/
function rest_handle_deprecated_function( $function, $replacement, $version ) {
if ( ! WP_DEBUG || headers_sent() ) {
return;
}
if ( ! empty( $replacement ) ) {
/* translators: 1: Function name, 2: WordPress version number, 3: New function name. */
$string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
} else {
/* translators: 1: Function name, 2: WordPress version number. */
$string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
}
header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
}
/**
* Handles _deprecated_argument() errors.
*
* @since 4.4.0
*
* @param string $function The function that was called.
* @param string $message A message regarding the change.
* @param string $version Version.
*/
function rest_handle_deprecated_argument( $function, $message, $version ) {
if ( ! WP_DEBUG || headers_sent() ) {
return;
}
if ( $message ) {
/* translators: 1: Function name, 2: WordPress version number, 3: Error message. */
$string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $message );
} else {
/* translators: 1: Function name, 2: WordPress version number. */
$string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
}
header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
}
/**
* Handles _doing_it_wrong errors.
*
* @since 5.5.0
*
* @param string $function The function that was called.
* @param string $message A message explaining what has been done incorrectly.
* @param string|null $version The version of WordPress where the message was added.
*/
function rest_handle_doing_it_wrong( $function, $message, $version ) {
if ( ! WP_DEBUG || headers_sent() ) {
return;
}
if ( $version ) {
/* translators: Developer debugging message. 1: PHP function name, 2: WordPress version number, 3: Explanatory message. */
$string = __( '%1$s (since %2$s; %3$s)' );
$string = sprintf( $string, $function, $version, $message );
} else {
/* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message. */
$string = __( '%1$s (%2$s)' );
$string = sprintf( $string, $function, $message );
}
header( sprintf( 'X-WP-DoingItWrong: %s', $string ) );
}
/**
* Sends Cross-Origin Resource Sharing headers with API requests.
*
* @since 4.4.0
*
* @param mixed $value Response data.
* @return mixed Response data.
*/
function rest_send_cors_headers( $value ) {
$origin = get_http_origin();
if ( $origin ) {
// Requests from file:// and data: URLs send "Origin: null".
if ( 'null' !== $origin ) {
$origin = esc_url_raw( $origin );
}
header( 'Access-Control-Allow-Origin: ' . $origin );
header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Vary: Origin', false );
} elseif ( ! headers_sent() && 'GET' === $_SERVER['REQUEST_METHOD'] && ! is_user_logged_in() ) {
header( 'Vary: Origin', false );
}
return $value;
}
/**
* Handles OPTIONS requests for the server.
*
* This is handled outside of the server code, as it doesn't obey normal route
* mapping.
*
* @since 4.4.0
*
* @param mixed $response Current response, either response or `null` to indicate pass-through.
* @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
* @param WP_REST_Request $request The request that was used to make current response.
* @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
*/
function rest_handle_options_request( $response, $handler, $request ) {
if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
return $response;
}
$response = new WP_REST_Response();
$data = array();
foreach ( $handler->get_routes() as $route => $endpoints ) {
$match = preg_match( '@^' . $route . '$@i', $request->get_route(), $matches );
if ( ! $match ) {
continue;
}
$args = array();
foreach ( $matches as $param => $value ) {
if ( ! is_int( $param ) ) {
$args[ $param ] = $value;
}
}
foreach ( $endpoints as $endpoint ) {
// Remove the redundant preg_match() argument.
unset( $args[0] );
$request->set_url_params( $args );
$request->set_attributes( $endpoint );
}
$data = $handler->get_data_for_route( $route, $endpoints, 'help' );
$response->set_matched_route( $route );
break;
}
$response->set_data( $data );
return $response;
}
/**
* Sends the "Allow" header to state all methods that can be sent to the current route.
*
* @since 4.4.0
*
* @param WP_REST_Response $response Current response being served.
* @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
* @param WP_REST_Request $request The request that was used to make current response.
* @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
*/
function rest_send_allow_header( $response, $server, $request ) {
$matched_route = $response->get_matched_route();
if ( ! $matched_route ) {
return $response;
}
$routes = $server->get_routes();
$allowed_methods = array();
// Get the allowed methods across the routes.
foreach ( $routes[ $matched_route ] as $_handler ) {
foreach ( $_handler['methods'] as $handler_method => $value ) {
if ( ! empty( $_handler['permission_callback'] ) ) {
$permission = call_user_func( $_handler['permission_callback'], $request );
$allowed_methods[ $handler_method ] = true === $permission;
} else {
$allowed_methods[ $handler_method ] = true;
}
}
}
// Strip out all the methods that are not allowed (false values).
$allowed_methods = array_filter( $allowed_methods );
if ( $allowed_methods ) {
$response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
}
return $response;
}
/**
* Recursively computes the intersection of arrays using keys for comparison.
*
* @since 5.3.0
*
* @param array $array1 The array with master keys to check.
* @param array $array2 An array to compare keys against.
* @return array An associative array containing all the entries of array1 which have keys
* that are present in all arguments.
*/
function _rest_array_intersect_key_recursive( $array1, $array2 ) {
$array1 = array_intersect_key( $array1, $array2 );
foreach ( $array1 as $key => $value ) {
if ( is_array( $value ) && is_array( $array2[ $key ] ) ) {
$array1[ $key ] = _rest_array_intersect_key_recursive( $value, $array2[ $key ] );
}
}
return $array1;
}
/**
* Filters the REST API response to include only a white-listed set of response object fields.
*
* @since 4.8.0
*
* @param WP_REST_Response $response Current response being served.
* @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
* @param WP_REST_Request $request The request that was used to make current response.
* @return WP_REST_Response Response to be served, trimmed down to contain a subset of fields.
*/
function rest_filter_response_fields( $response, $server, $request ) {
if ( ! isset( $request['_fields'] ) || $response->is_error() ) {
return $response;
}
$data = $response->get_data();
$fields = wp_parse_list( $request['_fields'] );
if ( 0 === count( $fields ) ) {
return $response;
}
// Trim off outside whitespace from the comma delimited list.
$fields = array_map( 'trim', $fields );
// Create nested array of accepted field hierarchy.
$fields_as_keyed = array();
foreach ( $fields as $field ) {
$parts = explode( '.', $field );
$ref = &$fields_as_keyed;
while ( count( $parts ) > 1 ) {
$next = array_shift( $parts );
if ( isset( $ref[ $next ] ) && true === $ref[ $next ] ) {
// Skip any sub-properties if their parent prop is already marked for inclusion.
break 2;
}
$ref[ $next ] = isset( $ref[ $next ] ) ? $ref[ $next ] : array();
$ref = &$ref[ $next ];
}
$last = array_shift( $parts );
$ref[ $last ] = true;
}
if ( wp_is_numeric_array( $data ) ) {
$new_data = array();
foreach ( $data as $item ) {
$new_data[] = _rest_array_intersect_key_recursive( $item, $fields_as_keyed );
}
} else {
$new_data = _rest_array_intersect_key_recursive( $data, $fields_as_keyed );
}
$response->set_data( $new_data );
return $response;
}
/**
* Given an array of fields to include in a response, some of which may be
* `nested.fields`, determine whether the provided field should be included
* in the response body.
*
* If a parent field is passed in, the presence of any nested field within
* that parent will cause the method to return `true`. For example "title"
* will return true if any of `title`, `title.raw` or `title.rendered` is
* provided.
*
* @since 5.3.0
*
* @param string $field A field to test for inclusion in the response body.
* @param array $fields An array of string fields supported by the endpoint.
* @return bool Whether to include the field or not.
*/
function rest_is_field_included( $field, $fields ) {
if ( in_array( $field, $fields, true ) ) {
return true;
}
foreach ( $fields as $accepted_field ) {
// Check to see if $field is the parent of any item in $fields.
// A field "parent" should be accepted if "parent.child" is accepted.
if ( strpos( $accepted_field, "$field." ) === 0 ) {
return true;
}
// Conversely, if "parent" is accepted, all "parent.child" fields
// should also be accepted.
if ( strpos( $field, "$accepted_field." ) === 0 ) {
return true;
}
}
return false;
}
/**
* Adds the REST API URL to the WP RSD endpoint.
*
* @since 4.4.0
*
* @see get_rest_url()
*/
function rest_output_rsd() {
$api_root = get_rest_url();
if ( empty( $api_root ) ) {
return;
}
?>
<api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
<?php
}
/**
* Outputs the REST API link tag into page header.
*
* @since 4.4.0
*
* @see get_rest_url()
*/
function rest_output_link_wp_head() {
$api_root = get_rest_url();
if ( empty( $api_root ) ) {
return;
}
printf( '<link rel="https://api.w.org/" href="%s" />', esc_url( $api_root ) );
$resource = rest_get_queried_resource_route();
if ( $resource ) {
printf( '<link rel="alternate" type="application/json" href="%s" />', esc_url( rest_url( $resource ) ) );
}
}
/**
* Sends a Link header for the REST API.
*
* @since 4.4.0
*/
function rest_output_link_header() {
if ( headers_sent() ) {
return;
}
$api_root = get_rest_url();
if ( empty( $api_root ) ) {
return;
}
header( sprintf( 'Link: <%s>; rel="https://api.w.org/"', esc_url_raw( $api_root ) ), false );
$resource = rest_get_queried_resource_route();
if ( $resource ) {
header( sprintf( 'Link: <%s>; rel="alternate"; type="application/json"', esc_url_raw( rest_url( $resource ) ) ), false );
}
}
/**
* Checks for errors when using cookie-based authentication.
*
* WordPress' built-in cookie authentication is always active
* for logged in users. However, the API has to check nonces
* for each request to ensure users are not vulnerable to CSRF.
*
* @since 4.4.0
*
* @global mixed $wp_rest_auth_cookie
*
* @param WP_Error|mixed $result Error from another authentication handler,
* null if we should handle it, or another value if not.
* @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
*/
function rest_cookie_check_errors( $result ) {