| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * REST API functions. 4 * 5 * @package WordPress 6 * @subpackage REST_API 7 * @since 4.4.0 8 */ 9 10 /** 11 * Version number for our API. 12 */ 13 define( 'REST_API_VERSION', '2.0' ); 14 15 /** 16 * Registers a REST API route. 17 * 18 * Note: Do not use before the {@see 'rest_api_init'} hook. 19 * 20 * @since 4.4.0 21 * @since 5.1.0 Added a `_doing_it_wrong()` notice when not called on or after the `rest_api_init` hook. 22 * @since 5.5.0 Added a `_doing_it_wrong()` notice when the required `permission_callback` argument is not set. 23 * 24 * @param string $route_namespace The first URL segment after core prefix. Should be unique to your package/plugin. 25 * @param string $route The base URL for route you are adding. 26 * @param array $args Optional. Either an array of options for the endpoint, or an array of arrays for 27 * multiple methods. Default empty array. 28 * @param bool $override Optional. If the route already exists, should we override it? True overrides, 29 * false merges (with newer overriding if duplicate keys exist). Default false. 30 * @return bool True on success, false on error. 31 */ 32 function register_rest_route( $route_namespace, $route, $args = array(), $override = false ) { 33 if ( empty( $route_namespace ) ) { 34 /* 35 * Non-namespaced routes are not allowed, with the exception of the main 36 * and namespace indexes. If you really need to register a 37 * non-namespaced route, call `WP_REST_Server::register_route` directly. 38 */ 39 _doing_it_wrong( 40 __FUNCTION__, 41 sprintf( 42 /* translators: 1: string value of the namespace, 2: string value of the route. */ 43 __( 'Routes must be namespaced with plugin or theme name and version. Instead there seems to be an empty namespace \'%1$s\' for route \'%2$s\'.' ), 44 '<code>' . $route_namespace . '</code>', 45 '<code>' . $route . '</code>' 46 ), 47 '4.4.0' 48 ); 49 return false; 50 } elseif ( empty( $route ) ) { 51 _doing_it_wrong( 52 __FUNCTION__, 53 sprintf( 54 /* translators: 1: string value of the namespace, 2: string value of the route. */ 55 __( 'Route must be specified. Instead within the namespace \'%1$s\', there seems to be an empty route \'%2$s\'.' ), 56 '<code>' . $route_namespace . '</code>', 57 '<code>' . $route . '</code>' 58 ), 59 '4.4.0' 60 ); 61 return false; 62 } 63 64 $clean_namespace = trim( $route_namespace, '/' ); 65 66 if ( $clean_namespace !== $route_namespace ) { 67 _doing_it_wrong( 68 __FUNCTION__, 69 sprintf( 70 /* translators: 1: string value of the namespace, 2: string value of the route. */ 71 __( 'Namespace must not start or end with a slash. Instead namespace \'%1$s\' for route \'%2$s\' seems to contain a slash.' ), 72 '<code>' . $route_namespace . '</code>', 73 '<code>' . $route . '</code>' 74 ), 75 '5.4.2' 76 ); 77 } 78 79 if ( ! did_action( 'rest_api_init' ) ) { 80 _doing_it_wrong( 81 __FUNCTION__, 82 sprintf( 83 /* translators: 1: rest_api_init, 2: string value of the route, 3: string value of the namespace. */ 84 __( 'REST API routes must be registered on the %1$s action. Instead route \'%2$s\' with namespace \'%3$s\' was not registered on this action.' ), 85 '<code>rest_api_init</code>', 86 '<code>' . $route . '</code>', 87 '<code>' . $route_namespace . '</code>' 88 ), 89 '5.1.0' 90 ); 91 } 92 93 if ( isset( $args['args'] ) ) { 94 $common_args = $args['args']; 95 unset( $args['args'] ); 96 } else { 97 $common_args = array(); 98 } 99 100 if ( isset( $args['callback'] ) ) { 101 // Upgrade a single set to multiple. 102 $args = array( $args ); 103 } 104 105 $defaults = array( 106 'methods' => 'GET', 107 'callback' => null, 108 'args' => array(), 109 ); 110 111 foreach ( $args as $key => &$arg_group ) { 112 if ( ! is_numeric( $key ) ) { 113 // Route option, skip here. 114 continue; 115 } 116 117 $arg_group = array_merge( $defaults, $arg_group ); 118 $arg_group['args'] = array_merge( $common_args, $arg_group['args'] ); 119 120 if ( ! isset( $arg_group['permission_callback'] ) ) { 121 _doing_it_wrong( 122 __FUNCTION__, 123 sprintf( 124 /* translators: 1: The REST API route being registered, 2: The argument name, 3: The suggested function name. */ 125 __( '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.' ), 126 '<code>' . $clean_namespace . '/' . trim( $route, '/' ) . '</code>', 127 '<code>permission_callback</code>', 128 '<code>__return_true</code>' 129 ), 130 '5.5.0' 131 ); 132 } 133 134 foreach ( $arg_group['args'] as $arg ) { 135 if ( ! is_array( $arg ) ) { 136 _doing_it_wrong( 137 __FUNCTION__, 138 sprintf( 139 /* translators: 1: $args, 2: The REST API route being registered. */ 140 __( 'REST API %1$s should be an array of arrays. Non-array value detected for %2$s.' ), 141 '<code>$args</code>', 142 '<code>' . $clean_namespace . '/' . trim( $route, '/' ) . '</code>' 143 ), 144 '6.1.0' 145 ); 146 break; // Leave the foreach loop once a non-array argument was found. 147 } 148 } 149 } 150 151 $full_route = '/' . $clean_namespace . '/' . trim( $route, '/' ); 152 rest_get_server()->register_route( $clean_namespace, $full_route, $args, $override ); 153 return true; 154 } 155 156 /** 157 * Registers a new field on an existing WordPress object type. 158 * 159 * @since 4.7.0 160 * 161 * @global array $wp_rest_additional_fields Holds registered fields, organized 162 * by object type. 163 * 164 * @param string|array $object_type Object(s) the field is being registered to, 165 * "post"|"term"|"comment" etc. 166 * @param string $attribute The attribute name. 167 * @param array $args { 168 * Optional. An array of arguments used to handle the registered field. 169 * 170 * @type callable|null $get_callback Optional. The callback function used to retrieve the field value. Default is 171 * 'null', the field will not be returned in the response. The function will 172 * be passed the prepared object data. 173 * @type callable|null $update_callback Optional. The callback function used to set and update the field value. Default 174 * is 'null', the value cannot be set or updated. The function will be passed 175 * the model object, like WP_Post. 176 * @type array|null $schema Optional. The schema for this field. 177 * Default is 'null', no schema entry will be returned. 178 * } 179 */ 180 function register_rest_field( $object_type, $attribute, $args = array() ) { 181 global $wp_rest_additional_fields; 182 183 $defaults = array( 184 'get_callback' => null, 185 'update_callback' => null, 186 'schema' => null, 187 ); 188 189 $args = wp_parse_args( $args, $defaults ); 190 191 $object_types = (array) $object_type; 192 193 foreach ( $object_types as $object_type ) { 194 $wp_rest_additional_fields[ $object_type ][ $attribute ] = $args; 195 } 196 } 197 198 /** 199 * Registers rewrite rules for the REST API. 200 * 201 * @since 4.4.0 202 * 203 * @see rest_api_register_rewrites() 204 * @global WP $wp Current WordPress environment instance. 205 */ 206 function rest_api_init() { 207 rest_api_register_rewrites(); 208 209 global $wp; 210 $wp->add_query_var( 'rest_route' ); 211 } 212 213 /** 214 * Adds REST rewrite rules. 215 * 216 * @since 4.4.0 217 * 218 * @see add_rewrite_rule() 219 * @global WP_Rewrite $wp_rewrite WordPress rewrite component. 220 */ 221 function rest_api_register_rewrites() { 222 global $wp_rewrite; 223 224 add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' ); 225 add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' ); 226 add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' ); 227 add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' ); 228 } 229 230 /** 231 * Registers the default REST API filters. 232 * 233 * Attached to the {@see 'rest_api_init'} action 234 * to make testing and disabling these filters easier. 235 * 236 * @since 4.4.0 237 */ 238 function rest_api_default_filters() { 239 if ( wp_is_serving_rest_request() ) { 240 // Deprecated reporting. 241 add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 ); 242 add_filter( 'deprecated_function_trigger_error', '__return_false' ); 243 add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 ); 244 add_filter( 'deprecated_argument_trigger_error', '__return_false' ); 245 add_action( 'doing_it_wrong_run', 'rest_handle_doing_it_wrong', 10, 3 ); 246 add_filter( 'doing_it_wrong_trigger_error', '__return_false' ); 247 } 248 249 // Default serving. 250 add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers', 10, 4 ); 251 add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 ); 252 add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 ); 253 254 add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 ); 255 add_filter( 'rest_index', 'rest_add_application_passwords_to_index' ); 256 } 257 258 /** 259 * Registers default REST API routes. 260 * 261 * @since 4.7.0 262 */ 263 function create_initial_rest_routes() { 264 foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) { 265 $controller = $post_type->get_rest_controller(); 266 267 if ( ! $controller ) { 268 continue; 269 } 270 271 if ( ! $post_type->late_route_registration ) { 272 $controller->register_routes(); 273 } 274 275 $revisions_controller = $post_type->get_revisions_rest_controller(); 276 if ( $revisions_controller ) { 277 $revisions_controller->register_routes(); 278 } 279 280 $autosaves_controller = $post_type->get_autosave_rest_controller(); 281 if ( $autosaves_controller ) { 282 $autosaves_controller->register_routes(); 283 } 284 285 if ( $post_type->late_route_registration ) { 286 $controller->register_routes(); 287 } 288 } 289 290 // Post types. 291 $controller = new WP_REST_Post_Types_Controller(); 292 $controller->register_routes(); 293 294 // Post statuses. 295 $controller = new WP_REST_Post_Statuses_Controller(); 296 $controller->register_routes(); 297 298 // Taxonomies. 299 $controller = new WP_REST_Taxonomies_Controller(); 300 $controller->register_routes(); 301 302 // Terms. 303 foreach ( get_taxonomies( array( 'show_in_rest' => true ), 'object' ) as $taxonomy ) { 304 $controller = $taxonomy->get_rest_controller(); 305 306 if ( ! $controller ) { 307 continue; 308 } 309 310 $controller->register_routes(); 311 } 312 313 // Users. 314 $controller = new WP_REST_Users_Controller(); 315 $controller->register_routes(); 316 317 // Application Passwords 318 $controller = new WP_REST_Application_Passwords_Controller(); 319 $controller->register_routes(); 320 321 // Comments. 322 $controller = new WP_REST_Comments_Controller(); 323 $controller->register_routes(); 324 325 $search_handlers = array( 326 new WP_REST_Post_Search_Handler(), 327 new WP_REST_Term_Search_Handler(), 328 new WP_REST_Post_Format_Search_Handler(), 329 ); 330 331 /** 332 * Filters the search handlers to use in the REST search controller. 333 * 334 * @since 5.0.0 335 * 336 * @param array $search_handlers List of search handlers to use in the controller. Each search 337 * handler instance must extend the `WP_REST_Search_Handler` class. 338 * Default is only a handler for posts. 339 */ 340 $search_handlers = apply_filters( 'wp_rest_search_handlers', $search_handlers ); 341 342 $controller = new WP_REST_Search_Controller( $search_handlers ); 343 $controller->register_routes(); 344 345 // Block Renderer. 346 $controller = new WP_REST_Block_Renderer_Controller(); 347 $controller->register_routes(); 348 349 // Block Types. 350 $controller = new WP_REST_Block_Types_Controller(); 351 $controller->register_routes(); 352 353 // Settings. 354 $controller = new WP_REST_Settings_Controller(); 355 $controller->register_routes(); 356 357 // Themes. 358 $controller = new WP_REST_Themes_Controller(); 359 $controller->register_routes(); 360 361 // Plugins. 362 $controller = new WP_REST_Plugins_Controller(); 363 $controller->register_routes(); 364 365 // Sidebars. 366 $controller = new WP_REST_Sidebars_Controller(); 367 $controller->register_routes(); 368 369 // Widget Types. 370 $controller = new WP_REST_Widget_Types_Controller(); 371 $controller->register_routes(); 372 373 // Widgets. 374 $controller = new WP_REST_Widgets_Controller(); 375 $controller->register_routes(); 376 377 // Block Directory. 378 $controller = new WP_REST_Block_Directory_Controller(); 379 $controller->register_routes(); 380 381 // Pattern Directory. 382 $controller = new WP_REST_Pattern_Directory_Controller(); 383 $controller->register_routes(); 384 385 // Block Patterns. 386 $controller = new WP_REST_Block_Patterns_Controller(); 387 $controller->register_routes(); 388 389 // Block Pattern Categories. 390 $controller = new WP_REST_Block_Pattern_Categories_Controller(); 391 $controller->register_routes(); 392 393 // Site Health. 394 $site_health = WP_Site_Health::get_instance(); 395 $controller = new WP_REST_Site_Health_Controller( $site_health ); 396 $controller->register_routes(); 397 398 // URL Details. 399 $controller = new WP_REST_URL_Details_Controller(); 400 $controller->register_routes(); 401 402 // Menu Locations. 403 $controller = new WP_REST_Menu_Locations_Controller(); 404 $controller->register_routes(); 405 406 // Site Editor Export. 407 $controller = new WP_REST_Edit_Site_Export_Controller(); 408 $controller->register_routes(); 409 410 // Navigation Fallback. 411 $controller = new WP_REST_Navigation_Fallback_Controller(); 412 $controller->register_routes(); 413 414 // Font Collections. 415 $font_collections_controller = new WP_REST_Font_Collections_Controller(); 416 $font_collections_controller->register_routes(); 417 418 // Abilities. 419 $abilities_categories_controller = new WP_REST_Abilities_V1_Categories_Controller(); 420 $abilities_categories_controller->register_routes(); 421 $abilities_run_controller = new WP_REST_Abilities_V1_Run_Controller(); 422 $abilities_run_controller->register_routes(); 423 $abilities_list_controller = new WP_REST_Abilities_V1_List_Controller(); 424 $abilities_list_controller->register_routes(); 425 426 // Icons. 427 $icons_controller = new WP_REST_Icons_Controller(); 428 $icons_controller->register_routes(); 429 430 // Icon Collections. 431 $icon_collections_controller = new WP_REST_Icon_Collections_Controller(); 432 $icon_collections_controller->register_routes(); 433 434 // View Config. 435 $view_config_controller = new WP_REST_View_Config_Controller(); 436 $view_config_controller->register_routes(); 437 438 // Entity Actions. 439 $entity_actions_controller = new WP_REST_Entity_Actions_Controller(); 440 $entity_actions_controller->register_routes(); 441 442 // Entity Fields. 443 $entity_fields_controller = new WP_REST_Entity_Fields_Controller(); 444 $entity_fields_controller->register_routes(); 445 } 446 447 /** 448 * Loads the REST API. 449 * 450 * @since 4.4.0 451 * 452 * @global WP $wp Current WordPress environment instance. 453 */ 454 function rest_api_loaded() { 455 /* 456 * Admin screens call wp() for list queries; they are never REST entry points. 457 * Check WP_ADMIN rather than is_admin(), which follows the current screen. 458 */ 459 if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) || defined( 'WP_ADMIN' ) ) { 460 return; 461 } 462 463 // Short-circuit before define()/die() if a REST dispatch is already in flight. 464 // serve_request() enforces this too; guarding here avoids the trailing die(). 465 if ( isset( $GLOBALS['wp_rest_server'] ) 466 && $GLOBALS['wp_rest_server'] instanceof WP_REST_Server 467 && $GLOBALS['wp_rest_server']->is_dispatching() 468 ) { 469 return; 470 } 471 472 // Return an error message if query_var is not a string. 473 if ( ! is_string( $GLOBALS['wp']->query_vars['rest_route'] ) ) { 474 $rest_type_error = new WP_Error( 475 'rest_path_invalid_type', 476 __( 'The REST route parameter must be a string.' ), 477 array( 'status' => 400 ) 478 ); 479 wp_die( $rest_type_error ); 480 } 481 482 /** 483 * Whether this is a REST Request. 484 * 485 * @since 4.4.0 486 */ 487 define( 'REST_REQUEST', true ); 488 489 // Initialize the server. 490 $server = rest_get_server(); 491 492 // Fire off the request. 493 $route = untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] ); 494 if ( empty( $route ) ) { 495 $route = '/'; 496 } 497 $server->serve_request( $route ); 498 499 // We're done. 500 die(); 501 } 502 503 /** 504 * Retrieves the URL prefix for any API resource. 505 * 506 * @since 4.4.0 507 * 508 * @return string Prefix. 509 */ 510 function rest_get_url_prefix() { 511 /** 512 * Filters the REST URL prefix. 513 * 514 * @since 4.4.0 515 * 516 * @param string $prefix URL prefix. Default 'wp-json'. 517 */ 518 return apply_filters( 'rest_url_prefix', 'wp-json' ); 519 } 520 521 /** 522 * Retrieves the URL to a REST endpoint on a site. 523 * 524 * Note: The returned URL is NOT escaped. 525 * 526 * @since 4.4.0 527 * 528 * @todo Check if this is even necessary 529 * @global WP_Rewrite $wp_rewrite WordPress rewrite component. 530 * 531 * @param int|null $blog_id Optional. Blog ID. Default of null returns URL for current blog. 532 * @param string $path Optional. REST route. Default '/'. 533 * @param string $scheme Optional. Sanitization scheme. Default 'rest'. 534 * @return string Full URL to the endpoint. 535 * 536 * @phpstan-return non-falsy-string 537 */ 538 function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) { 539 if ( empty( $path ) ) { 540 $path = '/'; 541 } 542 543 $path = '/' . ltrim( $path, '/' ); 544 545 if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) { 546 global $wp_rewrite; 547 548 if ( $wp_rewrite->using_index_permalinks() ) { 549 $url = get_home_url( $blog_id, $wp_rewrite->index . '/' . rest_get_url_prefix(), $scheme ); 550 } else { 551 $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme ); 552 } 553 554 $url .= $path; 555 } else { 556 $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) ); 557 /* 558 * nginx only allows HTTP/1.0 methods when redirecting from / to /index.php. 559 * To work around this, we manually add index.php to the URL, avoiding the redirect. 560 */ 561 if ( ! str_ends_with( $url, 'index.php' ) ) { 562 $url .= 'index.php'; 563 } 564 565 $url = add_query_arg( 'rest_route', $path, $url ); 566 } 567 568 if ( is_ssl() && isset( $_SERVER['SERVER_NAME'] ) ) { 569 // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS. 570 if ( parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) === $_SERVER['SERVER_NAME'] ) { 571 $url = set_url_scheme( $url, 'https' ); 572 } 573 } 574 575 if ( is_admin() && force_ssl_admin() ) { 576 /* 577 * In this situation the home URL may be http:, and `is_ssl()` may be false, 578 * but the admin is served over https: (one way or another), so REST API usage 579 * will be blocked by browsers unless it is also served over HTTPS. 580 */ 581 $url = set_url_scheme( $url, 'https' ); 582 } 583 584 /** 585 * Filters the REST URL. 586 * 587 * Use this filter to adjust the url returned by the get_rest_url() function. 588 * 589 * @since 4.4.0 590 * 591 * @param string $url REST URL. 592 * @param string $path REST route. 593 * @param int|null $blog_id Blog ID. 594 * @param string $scheme Sanitization scheme. 595 * 596 * @phpstan-param non-falsy-string $url 597 */ 598 return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme ); 599 } 600 601 /** 602 * Retrieves the URL to a REST endpoint. 603 * 604 * Note: The returned URL is NOT escaped. 605 * 606 * @since 4.4.0 607 * 608 * @param string $path Optional. REST route. Default empty. 609 * @param string $scheme Optional. Sanitization scheme. Default 'rest'. 610 * @return string Full URL to the endpoint. 611 * 612 * @phpstan-return non-falsy-string 613 */ 614 function rest_url( $path = '', $scheme = 'rest' ) { 615 return get_rest_url( null, $path, $scheme ); 616 } 617 618 /** 619 * Do a REST request. 620 * 621 * Used primarily to route internal requests through WP_REST_Server. 622 * 623 * @since 4.4.0 624 * 625 * @param WP_REST_Request|string $request Request. 626 * @return WP_REST_Response REST response. 627 */ 628 function rest_do_request( $request ) { 629 $request = rest_ensure_request( $request ); 630 return rest_get_server()->dispatch( $request ); 631 } 632 633 /** 634 * Retrieves the current REST server instance. 635 * 636 * Instantiates a new instance if none exists already. 637 * 638 * @since 4.5.0 639 * 640 * @global WP_REST_Server $wp_rest_server REST server instance. 641 * 642 * @return WP_REST_Server REST server instance. 643 */ 644 function rest_get_server() { 645 /* @var WP_REST_Server $wp_rest_server */ 646 global $wp_rest_server; 647 648 if ( empty( $wp_rest_server ) ) { 649 /** 650 * Filters the REST Server Class. 651 * 652 * This filter allows you to adjust the server class used by the REST API, using a 653 * different class to handle requests. 654 * 655 * @since 4.4.0 656 * 657 * @param string $class_name The name of the server class. Default 'WP_REST_Server'. 658 */ 659 $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' ); 660 $wp_rest_server = new $wp_rest_server_class(); 661 662 /** 663 * Fires when preparing to serve a REST API request. 664 * 665 * Endpoint objects should be created and register their hooks on this action rather 666 * than another action to ensure they're only loaded when needed. 667 * 668 * @since 4.4.0 669 * 670 * @param WP_REST_Server $wp_rest_server Server object. 671 */ 672 do_action( 'rest_api_init', $wp_rest_server ); 673 } 674 675 return $wp_rest_server; 676 } 677 678 /** 679 * Ensures request arguments are a request object (for consistency). 680 * 681 * @since 4.4.0 682 * @since 5.3.0 Accept string argument for the request path. 683 * 684 * @param array|string|WP_REST_Request $request Request to check. 685 * @return WP_REST_Request REST request instance. 686 */ 687 function rest_ensure_request( $request ) { 688 if ( $request instanceof WP_REST_Request ) { 689 return $request; 690 } 691 692 if ( is_string( $request ) ) { 693 return new WP_REST_Request( 'GET', $request ); 694 } 695 696 return new WP_REST_Request( 'GET', '', $request ); 697 } 698 699 /** 700 * Ensures a REST response is a response object (for consistency). 701 * 702 * This implements WP_REST_Response, allowing usage of `set_status`/`header`/etc 703 * without needing to double-check the object. Will also allow WP_Error to indicate error 704 * responses, so users should immediately check for this value. 705 * 706 * @since 4.4.0 707 * 708 * @param WP_REST_Response|WP_Error|WP_HTTP_Response|mixed $response Response to check. 709 * @return WP_REST_Response|WP_Error If response generated an error, WP_Error, if response 710 * is already an instance, WP_REST_Response, otherwise 711 * returns a new WP_REST_Response instance. 712 * 713 * @phpstan-return ( $response is WP_Error ? WP_Error : WP_REST_Response ) 714 */ 715 function rest_ensure_response( $response ) { 716 if ( is_wp_error( $response ) ) { 717 return $response; 718 } 719 720 if ( $response instanceof WP_REST_Response ) { 721 return $response; 722 } 723 724 /* 725 * While WP_HTTP_Response is the base class of WP_REST_Response, it doesn't provide 726 * all the required methods used in WP_REST_Server::dispatch(). 727 */ 728 if ( $response instanceof WP_HTTP_Response ) { 729 return new WP_REST_Response( 730 $response->get_data(), 731 $response->get_status(), 732 $response->get_headers() 733 ); 734 } 735 736 return new WP_REST_Response( $response ); 737 } 738 739 /** 740 * Handles _deprecated_function() errors. 741 * 742 * @since 4.4.0 743 * 744 * @param string $function_name The function that was called. 745 * @param string $replacement The function that should have been called. 746 * @param string $version Version. 747 */ 748 function rest_handle_deprecated_function( $function_name, $replacement, $version ) { 749 if ( ! WP_DEBUG || headers_sent() ) { 750 return; 751 } 752 if ( ! empty( $replacement ) ) { 753 /* translators: 1: Function name, 2: WordPress version number, 3: New function name. */ 754 $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function_name, $version, $replacement ); 755 } else { 756 /* translators: 1: Function name, 2: WordPress version number. */ 757 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function_name, $version ); 758 } 759 760 header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) ); 761 } 762 763 /** 764 * Handles _deprecated_argument() errors. 765 * 766 * @since 4.4.0 767 * 768 * @param string $function_name The function that was called. 769 * @param string $message A message regarding the change. 770 * @param string $version Version. 771 */ 772 function rest_handle_deprecated_argument( $function_name, $message, $version ) { 773 if ( ! WP_DEBUG || headers_sent() ) { 774 return; 775 } 776 if ( $message ) { 777 /* translators: 1: Function name, 2: WordPress version number, 3: Error message. */ 778 $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function_name, $version, $message ); 779 } else { 780 /* translators: 1: Function name, 2: WordPress version number. */ 781 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function_name, $version ); 782 } 783 784 header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) ); 785 } 786 787 /** 788 * Handles _doing_it_wrong errors. 789 * 790 * @since 5.5.0 791 * 792 * @param string $function_name The function that was called. 793 * @param string $message A message explaining what has been done incorrectly. 794 * @param string|null $version The version of WordPress where the message was added. 795 */ 796 function rest_handle_doing_it_wrong( $function_name, $message, $version ) { 797 if ( ! WP_DEBUG || headers_sent() ) { 798 return; 799 } 800 801 if ( $version ) { 802 /* translators: Developer debugging message. 1: PHP function name, 2: WordPress version number, 3: Explanatory message. */ 803 $string = __( '%1$s (since %2$s; %3$s)' ); 804 $string = sprintf( $string, $function_name, $version, $message ); 805 } else { 806 /* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message. */ 807 $string = __( '%1$s (%2$s)' ); 808 $string = sprintf( $string, $function_name, $message ); 809 } 810 811 header( sprintf( 'X-WP-DoingItWrong: %s', $string ) ); 812 } 813 814 /** 815 * Sends Cross-Origin Resource Sharing headers with API requests. 816 * 817 * @since 4.4.0 818 * @since 7.2.0 Added the `$result`, `$request`, and `$server` parameters and the `rest_allowed_cors_methods` filter. 819 * 820 * @param mixed $value Response data. 821 * @param WP_HTTP_Response|null $result Optional. Result to send to the client. Default null. 822 * @param WP_REST_Request|null $request Optional. The request in context. Default null. 823 * @param WP_REST_Server|null $server Optional. The server instance. Default null. 824 * @return mixed Response data. 825 */ 826 function rest_send_cors_headers( $value, $result = null, $request = null, $server = null ) { 827 $origin = get_http_origin(); 828 829 if ( $origin ) { 830 // Requests from file:// and data: URLs send "Origin: null". 831 if ( 'null' !== $origin ) { 832 $origin = sanitize_url( $origin ); 833 } 834 835 /* 836 * Send through the server when serving a REST request. A direct call without one 837 * sends the headers itself, so that it does not set up the REST server. 838 */ 839 if ( ! $server instanceof WP_REST_Server ) { 840 $server = null; 841 } 842 $send_header = static function ( string $key, string $header_value ) use ( $server ): void { 843 if ( $server ) { 844 $server->send_header( $key, $header_value ); 845 } elseif ( ! headers_sent() ) { 846 header( "{$key}: {$header_value}" ); 847 } 848 }; 849 850 $send_header( 'Access-Control-Allow-Origin', $origin ); 851 852 /* 853 * The response's own headers have already been sent, and header() replaces them, 854 * so seed the list from any value the response set rather than discarding it. 855 */ 856 $response_headers = ( $result instanceof WP_HTTP_Response ) ? $result->get_headers() : array(); 857 $response_headers = array_change_key_case( $response_headers ); 858 859 /** 860 * Parses a list of methods, keeping only syntactically valid method tokens (RFC 9110, section 9.1). 861 * 862 * @phpstan-var Closure(mixed): list<non-empty-string> $parse_methods 863 */ 864 $parse_methods = static function ( $methods ): array { 865 if ( is_array( $methods ) ) { 866 // Join the entries so that each one is split like a string value, as in array( 'GET, POST' ). 867 $methods = implode( ',', array_filter( $methods, 'is_string' ) ); 868 } elseif ( ! is_string( $methods ) ) { 869 return array(); 870 } 871 $methods = preg_grep( '/^[!#$%&\'*+.^_`|~0-9A-Za-z-]+$/D', array_unique( wp_parse_list( $methods ) ) ); 872 return is_array( $methods ) ? array_values( $methods ) : array(); 873 }; 874 875 // Fall back to the default list when the response names no valid methods. 876 $allow_methods = $parse_methods( $response_headers['access-control-allow-methods'] ?? null ); 877 if ( empty( $allow_methods ) ) { 878 $allow_methods = array( 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' ); 879 } 880 881 /** 882 * Filters the list of HTTP methods advertised to REST API CORS requests. 883 * 884 * The allowed methods are passed to the browser to specify which methods 885 * may be used in a cross-origin request to the REST API. The list is a 886 * fixed default and is not derived from the registered routes, so a site 887 * serving routes that accept other methods can advertise them here. 888 * 889 * If the response already set its own `Access-Control-Allow-Methods` header 890 * naming valid methods, `$allow_methods` is those methods instead of the default list. 891 * Entries that are not valid method tokens are dropped, and an empty list 892 * omits the header. A value that is neither an array nor a string is ignored. 893 * 894 * @since 7.2.0 895 * 896 * @param string[] $allow_methods The list of HTTP methods to allow. 897 * @param WP_REST_Request|null $request The request in context, if available. 898 */ 899 $filtered_methods = apply_filters( 'rest_allowed_cors_methods', $allow_methods, $request instanceof WP_REST_Request ? $request : null ); 900 901 // Keep the unfiltered list for a callback that does not return one, rather than omitting the header. 902 if ( is_array( $filtered_methods ) || is_string( $filtered_methods ) ) { 903 $allow_methods = $parse_methods( $filtered_methods ); 904 } 905 906 if ( ! empty( $allow_methods ) ) { 907 $send_header( 'Access-Control-Allow-Methods', implode( ', ', $allow_methods ) ); 908 } elseif ( $server ) { 909 // Remove a value the response already sent. 910 $server->remove_header( 'Access-Control-Allow-Methods' ); 911 } elseif ( ! headers_sent() ) { 912 header_remove( 'Access-Control-Allow-Methods' ); 913 } 914 915 $send_header( 'Access-Control-Allow-Credentials', 'true' ); 916 917 // WP_REST_Server::send_header() replaces a header, and Vary must be appended to. 918 if ( ! headers_sent() ) { 919 header( 'Vary: Origin', false ); 920 } 921 } elseif ( ! headers_sent() && 'GET' === $_SERVER['REQUEST_METHOD'] && ! is_user_logged_in() ) { 922 header( 'Vary: Origin', false ); 923 } 924 925 return $value; 926 } 927 928 /** 929 * Handles OPTIONS requests for the server. 930 * 931 * This is handled outside of the server code, as it doesn't obey normal route 932 * mapping. 933 * 934 * @since 4.4.0 935 * 936 * @param mixed $response Current response, either response or `null` to indicate pass-through. 937 * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server). 938 * @param WP_REST_Request $request The request that was used to make current response. 939 * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through. 940 */ 941 function rest_handle_options_request( $response, $handler, $request ) { 942 if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) { 943 return $response; 944 } 945 946 $response = new WP_REST_Response(); 947 $data = array(); 948 949 foreach ( $handler->get_routes() as $route => $endpoints ) { 950 $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $matches ); 951 952 if ( ! $match ) { 953 continue; 954 } 955 956 $args = array(); 957 foreach ( $matches as $param => $value ) { 958 if ( ! is_int( $param ) ) { 959 $args[ $param ] = $value; 960 } 961 } 962 963 foreach ( $endpoints as $endpoint ) { 964 $request->set_url_params( $args ); 965 $request->set_attributes( $endpoint ); 966 } 967 968 $data = $handler->get_data_for_route( $route, $endpoints, 'help' ); 969 $response->set_matched_route( $route ); 970 break; 971 } 972 973 $response->set_data( $data ); 974 return $response; 975 } 976 977 /** 978 * Sends the "Allow" header to state all methods that can be sent to the current route. 979 * 980 * @since 4.4.0 981 * 982 * @param WP_REST_Response $response Current response being served. 983 * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server). 984 * @param WP_REST_Request $request The request that was used to make current response. 985 * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods. 986 */ 987 function rest_send_allow_header( $response, $server, $request ) { 988 $matched_route = $response->get_matched_route(); 989 990 if ( ! $matched_route ) { 991 return $response; 992 } 993 994 $routes = $server->get_routes(); 995 996 $allowed_methods = array(); 997 998 // Get the allowed methods across the routes. 999 foreach ( $routes[ $matched_route ] as $_handler ) { 1000 foreach ( $_handler['methods'] as $handler_method => $value ) { 1001 1002 if ( ! empty( $_handler['permission_callback'] ) ) { 1003 1004 $permission = call_user_func( $_handler['permission_callback'], $request ); 1005 1006 $allowed_methods[ $handler_method ] = true === $permission; 1007 } else { 1008 $allowed_methods[ $handler_method ] = true; 1009 } 1010 } 1011 } 1012 1013 // Strip out all the methods that are not allowed (false values). 1014 $allowed_methods = array_filter( $allowed_methods ); 1015 1016 if ( $allowed_methods ) { 1017 $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) ); 1018 } 1019 1020 return $response; 1021 } 1022 1023 /** 1024 * Recursively computes the intersection of arrays using keys for comparison. 1025 * 1026 * @since 5.3.0 1027 * 1028 * @param array $array1 The array with master keys to check. 1029 * @param array $array2 An array to compare keys against. 1030 * @return array An associative array containing all the entries of array1 which have keys 1031 * that are present in all arguments. 1032 */ 1033 function _rest_array_intersect_key_recursive( $array1, $array2 ) { 1034 $array1 = array_intersect_key( $array1, $array2 ); 1035 foreach ( $array1 as $key => $value ) { 1036 if ( is_array( $value ) && is_array( $array2[ $key ] ) ) { 1037 $array1[ $key ] = _rest_array_intersect_key_recursive( $value, $array2[ $key ] ); 1038 } 1039 } 1040 return $array1; 1041 } 1042 1043 /** 1044 * Filters the REST API response to include only an allow-listed set of response object fields. 1045 * 1046 * @since 4.8.0 1047 * @since 7.2.0 The response is left unchanged when the route turns off the `fields` response 1048 * processing or when the response data is not an array. 1049 * 1050 * @param WP_REST_Response $response Current response being served. 1051 * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server). 1052 * @param WP_REST_Request $request The request that was used to make current response. 1053 * @return WP_REST_Response Response to be served, trimmed down to contain a subset of fields. 1054 */ 1055 function rest_filter_response_fields( $response, $server, $request ) { 1056 if ( ! isset( $request['_fields'] ) || $response->is_error() ) { 1057 return $response; 1058 } 1059 1060 $processing = $response->get_data_processing(); 1061 if ( ! $processing['fields'] ) { 1062 return $response; 1063 } 1064 1065 $data = $response->get_data(); 1066 1067 // Only arrays have fields to filter. 1068 if ( ! is_array( $data ) ) { 1069 return $response; 1070 } 1071 1072 $fields = wp_parse_list( $request['_fields'] ); 1073 1074 if ( 0 === count( $fields ) ) { 1075 return $response; 1076 } 1077 1078 // Trim off outside whitespace from the comma delimited list. 1079 $fields = array_map( 'trim', $fields ); 1080 1081 // Create nested array of accepted field hierarchy. 1082 /** @var array<string, mixed> $fields_as_keyed */ 1083 $fields_as_keyed = array(); 1084 foreach ( $fields as $field ) { 1085 $parts = explode( '.', $field ); 1086 $ref = &$fields_as_keyed; 1087 while ( count( $parts ) > 1 ) { 1088 $next = array_shift( $parts ); 1089 if ( isset( $ref[ $next ] ) && true === $ref[ $next ] ) { 1090 // Skip any sub-properties if their parent prop is already marked for inclusion. 1091 break 2; 1092 } 1093 $ref[ $next ] ??= array(); 1094 $ref = &$ref[ $next ]; 1095 } 1096 $last = array_shift( $parts ); 1097 $ref[ $last ] = true; 1098 } 1099 1100 if ( wp_is_numeric_array( $data ) ) { 1101 $new_data = array(); 1102 foreach ( $data as $item ) { 1103 $new_data[] = is_array( $item ) ? _rest_array_intersect_key_recursive( $item, $fields_as_keyed ) : $item; 1104 } 1105 } else { 1106 $new_data = _rest_array_intersect_key_recursive( $data, $fields_as_keyed ); 1107 } 1108 1109 $response->set_data( $new_data ); 1110 1111 return $response; 1112 } 1113 1114 /** 1115 * Given an array of fields to include in a response, some of which may be 1116 * `nested.fields`, determine whether the provided field should be included 1117 * in the response body. 1118 * 1119 * If a parent field is passed in, the presence of any nested field within 1120 * that parent will cause the method to return `true`. For example "title" 1121 * will return true if any of `title`, `title.raw` or `title.rendered` is 1122 * provided. 1123 * 1124 * @since 5.3.0 1125 * 1126 * @param string $field A field to test for inclusion in the response body. 1127 * @param array $fields An array of string fields supported by the endpoint. 1128 * @return bool Whether to include the field or not. 1129 */ 1130 function rest_is_field_included( $field, $fields ) { 1131 if ( in_array( $field, $fields, true ) ) { 1132 return true; 1133 } 1134 1135 foreach ( $fields as $accepted_field ) { 1136 /* 1137 * Check to see if $field is the parent of any item in $fields. 1138 * A field "parent" should be accepted if "parent.child" is accepted. 1139 */ 1140 if ( str_starts_with( $accepted_field, "$field." ) ) { 1141 return true; 1142 } 1143 /* 1144 * Conversely, if "parent" is accepted, all "parent.child" fields 1145 * should also be accepted. 1146 */ 1147 if ( str_starts_with( $field, "$accepted_field." ) ) { 1148 return true; 1149 } 1150 } 1151 1152 return false; 1153 } 1154 1155 /** 1156 * Adds the REST API URL to the WP RSD endpoint. 1157 * 1158 * @since 4.4.0 1159 * 1160 * @see get_rest_url() 1161 */ 1162 function rest_output_rsd() { 1163 $api_root = get_rest_url(); 1164 1165 if ( empty( $api_root ) ) { 1166 return; 1167 } 1168 ?> 1169 <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" /> 1170 <?php 1171 } 1172 1173 /** 1174 * Outputs the REST API link tag into page header. 1175 * 1176 * @since 4.4.0 1177 * 1178 * @see get_rest_url() 1179 */ 1180 function rest_output_link_wp_head() { 1181 $api_root = get_rest_url(); 1182 1183 if ( empty( $api_root ) ) { 1184 return; 1185 } 1186 1187 printf( '<link rel="https://api.w.org/" href="%s" />', esc_url( $api_root ) ); 1188 1189 $resource = rest_get_queried_resource_route(); 1190 1191 if ( $resource ) { 1192 printf( 1193 '<link rel="alternate" title="%1$s" type="application/json" href="%2$s" />', 1194 _x( 'JSON', 'REST API resource link name' ), 1195 esc_url( rest_url( $resource ) ) 1196 ); 1197 } 1198 } 1199 1200 /** 1201 * Sends a Link header for the REST API. 1202 * 1203 * @since 4.4.0 1204 */ 1205 function rest_output_link_header() { 1206 if ( headers_sent() ) { 1207 return; 1208 } 1209 1210 $api_root = get_rest_url(); 1211 1212 if ( empty( $api_root ) ) { 1213 return; 1214 } 1215 1216 header( sprintf( 'Link: <%s>; rel="https://api.w.org/"', sanitize_url( $api_root ) ), false ); 1217 1218 $resource = rest_get_queried_resource_route(); 1219 1220 if ( $resource ) { 1221 header( 1222 sprintf( 1223 'Link: <%1$s>; rel="alternate"; title="%2$s"; type="application/json"', 1224 sanitize_url( rest_url( $resource ) ), 1225 _x( 'JSON', 'REST API resource link name' ) 1226 ), 1227 false 1228 ); 1229 } 1230 } 1231 1232 /** 1233 * Checks for errors when using cookie-based authentication. 1234 * 1235 * WordPress' built-in cookie authentication is always active 1236 * for logged in users. However, the API has to check nonces 1237 * for each request to ensure users are not vulnerable to CSRF. 1238 * 1239 * @since 4.4.0 1240 * 1241 * @global mixed $wp_rest_auth_cookie 1242 * 1243 * @param WP_Error|mixed $result Error from another authentication handler, 1244 * null if we should handle it, or another value if not. 1245 * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true. 1246 */ 1247 function rest_cookie_check_errors( $result ) { 1248 if ( ! empty( $result ) ) { 1249 return $result; 1250 } 1251 1252 global $wp_rest_auth_cookie; 1253 1254 /* 1255 * Is cookie authentication being used? (If we get an auth 1256 * error, but we're still logged in, another authentication 1257 * must have been used). 1258 */ 1259 if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) { 1260 return $result; 1261 } 1262 1263 // Determine if there is a nonce. 1264 $nonce = null; 1265 1266 if ( isset( $_REQUEST['_wpnonce'] ) ) { 1267 $nonce = $_REQUEST['_wpnonce']; 1268 } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) { 1269 $nonce = $_SERVER['HTTP_X_WP_NONCE']; 1270 } 1271 1272 if ( null === $nonce ) { 1273 // No nonce at all, so act as if it's an unauthenticated request. 1274 wp_set_current_user( 0 ); 1275 return true; 1276 } 1277 1278 // Check the nonce. 1279 $result = wp_verify_nonce( $nonce, 'wp_rest' ); 1280 1281 if ( ! $result ) { 1282 add_filter( 'rest_send_nocache_headers', '__return_true', 20 ); 1283 return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie check failed' ), array( 'status' => 403 ) ); 1284 } 1285 1286 // Send a refreshed nonce in header. 1287 rest_get_server()->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) ); 1288 1289 return true; 1290 } 1291 1292 /** 1293 * Collects cookie authentication status. 1294 * 1295 * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors. 1296 * 1297 * @since 4.4.0 1298 * 1299 * @see current_action() 1300 * @global mixed $wp_rest_auth_cookie 1301 */ 1302 function rest_cookie_collect_status() { 1303 global $wp_rest_auth_cookie; 1304 1305 $status_type = current_action(); 1306 1307 if ( 'auth_cookie_valid' !== $status_type ) { 1308 $wp_rest_auth_cookie = substr( $status_type, 12 ); 1309 return; 1310 } 1311 1312 $wp_rest_auth_cookie = true; 1313 } 1314 1315 /** 1316 * Collects the status of authenticating with an application password. 1317 * 1318 * @since 5.6.0 1319 * @since 5.7.0 Added the `$app_password` parameter. 1320 * 1321 * @global WP_User|WP_Error|null $wp_rest_application_password_status 1322 * @global string|null $wp_rest_application_password_uuid 1323 * 1324 * @param WP_Error $user_or_error The authenticated user or error instance. 1325 * @param array $app_password The Application Password used to authenticate. 1326 */ 1327 function rest_application_password_collect_status( $user_or_error, $app_password = array() ) { 1328 global $wp_rest_application_password_status, $wp_rest_application_password_uuid; 1329 1330 $wp_rest_application_password_status = $user_or_error; 1331 1332 if ( empty( $app_password['uuid'] ) ) { 1333 $wp_rest_application_password_uuid = null; 1334 } else { 1335 $wp_rest_application_password_uuid = $app_password['uuid']; 1336 } 1337 } 1338 1339 /** 1340 * Gets the Application Password used for authenticating the request. 1341 * 1342 * @since 5.7.0 1343 * 1344 * @global string|null $wp_rest_application_password_uuid 1345 * 1346 * @return string|null The Application Password UUID, or null if Application Passwords was not used. 1347 */ 1348 function rest_get_authenticated_app_password() { 1349 global $wp_rest_application_password_uuid; 1350 1351 return $wp_rest_application_password_uuid; 1352 } 1353 1354 /** 1355 * Checks for errors when using application password-based authentication. 1356 * 1357 * @since 5.6.0 1358 * 1359 * @global WP_User|WP_Error|null $wp_rest_application_password_status 1360 * 1361 * @param WP_Error|null|true $result Error from another authentication handler, 1362 * null if we should handle it, or another value if not. 1363 * @return WP_Error|null|true WP_Error if the application password is invalid, the $result, otherwise true. 1364 */ 1365 function rest_application_password_check_errors( $result ) { 1366 global $wp_rest_application_password_status; 1367 1368 if ( ! empty( $result ) ) { 1369 return $result; 1370 } 1371 1372 if ( is_wp_error( $wp_rest_application_password_status ) ) { 1373 $data = $wp_rest_application_password_status->get_error_data(); 1374 1375 if ( ! isset( $data['status'] ) ) { 1376 $data['status'] = 401; 1377 } 1378 1379 $wp_rest_application_password_status->add_data( $data ); 1380 1381 return $wp_rest_application_password_status; 1382 } 1383 1384 if ( $wp_rest_application_password_status instanceof WP_User ) { 1385 return true; 1386 } 1387 1388 return $result; 1389 } 1390 1391 /** 1392 * Adds Application Passwords info to the REST API index. 1393 * 1394 * @since 5.6.0 1395 * 1396 * @param WP_REST_Response $response The index response object. 1397 * @return WP_REST_Response 1398 */ 1399 function rest_add_application_passwords_to_index( $response ) { 1400 if ( ! wp_is_application_passwords_available() ) { 1401 return $response; 1402 } 1403 1404 $response->data['authentication']['application-passwords'] = array( 1405 'endpoints' => array( 1406 'authorization' => admin_url( 'authorize-application.php' ), 1407 ), 1408 ); 1409 1410 return $response; 1411 } 1412 1413 /** 1414 * Retrieves the avatar URLs in various sizes. 1415 * 1416 * @since 4.7.0 1417 * 1418 * @see get_avatar_url() 1419 * 1420 * @param mixed $id_or_email The avatar to retrieve a URL for. Accepts a user ID, Gravatar MD5 hash, 1421 * user email, WP_User object, WP_Post object, or WP_Comment object. 1422 * @return (string|false)[] Avatar URLs keyed by size. Each value can be a URL string or boolean false. 1423 */ 1424 function rest_get_avatar_urls( $id_or_email ) { 1425 $avatar_sizes = rest_get_avatar_sizes(); 1426 1427 $urls = array(); 1428 foreach ( $avatar_sizes as $size ) { 1429 $urls[ $size ] = get_avatar_url( $id_or_email, array( 'size' => $size ) ); 1430 } 1431 1432 return $urls; 1433 } 1434 1435 /** 1436 * Retrieves the pixel sizes for avatars. 1437 * 1438 * @since 4.7.0 1439 * 1440 * @return int[] List of pixel sizes for avatars. Default `[ 24, 48, 96 ]`. 1441 */ 1442 function rest_get_avatar_sizes() { 1443 /** 1444 * Filters the REST avatar sizes. 1445 * 1446 * Use this filter to adjust the array of sizes returned by the 1447 * `rest_get_avatar_sizes` function. 1448 * 1449 * @since 4.4.0 1450 * 1451 * @param int[] $sizes An array of int values that are the pixel sizes for avatars. 1452 * Default `[ 24, 48, 96 ]`. 1453 */ 1454 return apply_filters( 'rest_avatar_sizes', array( 24, 48, 96 ) ); 1455 } 1456 1457 /** 1458 * Parses an RFC3339 time into a Unix timestamp. 1459 * 1460 * Explicitly check for `false` to detect failure, as zero is a valid return 1461 * value on success. 1462 * 1463 * @since 4.4.0 1464 * 1465 * @param string $date RFC3339 timestamp. 1466 * @param bool $force_utc Optional. Whether to force UTC timezone instead of using 1467 * the timestamp's timezone. Default false. 1468 * @return int|false Unix timestamp on success, false on failure. 1469 */ 1470 function rest_parse_date( $date, $force_utc = false ) { 1471 if ( $force_utc ) { 1472 $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date ); 1473 } 1474 1475 $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#'; 1476 1477 if ( ! preg_match( $regex, $date, $matches ) ) { 1478 return false; 1479 } 1480 1481 return strtotime( $date ); 1482 } 1483 1484 /** 1485 * Parses a 3 or 6 digit hex color (with #). 1486 * 1487 * @since 5.4.0 1488 * 1489 * @param string $color 3 or 6 digit hex color (with #). 1490 * @return string|false Color value on success, false on failure. 1491 */ 1492 function rest_parse_hex_color( $color ) { 1493 $regex = '|^#([A-Fa-f0-9]{3}){1,2}$|'; 1494 if ( ! preg_match( $regex, $color, $matches ) ) { 1495 return false; 1496 } 1497 1498 return $color; 1499 } 1500 1501 /** 1502 * Parses a date into both its local and UTC equivalent, in MySQL datetime format. 1503 * 1504 * @since 4.4.0 1505 * 1506 * @see rest_parse_date() 1507 * 1508 * @param string $date RFC3339 timestamp. 1509 * @param bool $is_utc Whether the provided date should be interpreted as UTC. Default false. 1510 * @return array|null { 1511 * Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s), 1512 * null on failure. 1513 * 1514 * @type string $0 Local datetime string. 1515 * @type string $1 UTC datetime string. 1516 * } 1517 */ 1518 function rest_get_date_with_gmt( $date, $is_utc = false ) { 1519 /* 1520 * Whether or not the original date actually has a timezone string 1521 * changes the way we need to do timezone conversion. 1522 * Store this info before parsing the date, and use it later. 1523 */ 1524 $has_timezone = preg_match( '#(Z|[+-]\d{2}(:\d{2})?)$#', $date ); 1525 1526 $date = rest_parse_date( $date ); 1527 1528 if ( false === $date ) { 1529 return null; 1530 } 1531 1532 /* 1533 * At this point $date could either be a local date (if we were passed 1534 * a *local* date without a timezone offset) or a UTC date (otherwise). 1535 * Timezone conversion needs to be handled differently between these two cases. 1536 */ 1537 if ( ! $is_utc && ! $has_timezone ) { 1538 $local = gmdate( 'Y-m-d H:i:s', $date ); 1539 $utc = get_gmt_from_date( $local ); 1540 } else { 1541 $utc = gmdate( 'Y-m-d H:i:s', $date ); 1542 $local = get_date_from_gmt( $utc ); 1543 } 1544 1545 return array( $local, $utc ); 1546 } 1547 1548 /** 1549 * Returns a contextual HTTP error code for authorization failure. 1550 * 1551 * @since 4.7.0 1552 * 1553 * @return int 401 if the user is not logged in, 403 if the user is logged in. 1554 * 1555 * @phpstan-return 401|403 1556 */ 1557 function rest_authorization_required_code() { 1558 return is_user_logged_in() ? 403 : 401; 1559 } 1560 1561 /** 1562 * Validate a request argument based on details registered to the route. 1563 * 1564 * @since 4.7.0 1565 * 1566 * @param mixed $value 1567 * @param WP_REST_Request $request 1568 * @param string $param 1569 * @return true|WP_Error 1570 */ 1571 function rest_validate_request_arg( $value, $request, $param ) { 1572 $attributes = $request->get_attributes(); 1573 if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) { 1574 return true; 1575 } 1576 $args = $attributes['args'][ $param ]; 1577 1578 return rest_validate_value_from_schema( $value, $args, $param ); 1579 } 1580 1581 /** 1582 * Sanitize a request argument based on details registered to the route. 1583 * 1584 * @since 4.7.0 1585 * 1586 * @param mixed $value 1587 * @param WP_REST_Request $request 1588 * @param string $param 1589 * @return mixed 1590 */ 1591 function rest_sanitize_request_arg( $value, $request, $param ) { 1592 $attributes = $request->get_attributes(); 1593 if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) { 1594 return $value; 1595 } 1596 $args = $attributes['args'][ $param ]; 1597 1598 return rest_sanitize_value_from_schema( $value, $args, $param ); 1599 } 1600 1601 /** 1602 * Parse a request argument based on details registered to the route. 1603 * 1604 * Runs a validation check and sanitizes the value, primarily to be used via 1605 * the `sanitize_callback` arguments in the endpoint args registration. 1606 * 1607 * @since 4.7.0 1608 * 1609 * @param mixed $value 1610 * @param WP_REST_Request $request 1611 * @param string $param 1612 * @return mixed 1613 */ 1614 function rest_parse_request_arg( $value, $request, $param ) { 1615 $is_valid = rest_validate_request_arg( $value, $request, $param ); 1616 1617 if ( is_wp_error( $is_valid ) ) { 1618 return $is_valid; 1619 } 1620 1621 $value = rest_sanitize_request_arg( $value, $request, $param ); 1622 1623 return $value; 1624 } 1625 1626 /** 1627 * Determines if an IP address is valid. 1628 * 1629 * Handles both IPv4 and IPv6 addresses. 1630 * 1631 * @since 4.7.0 1632 * 1633 * @param string $ip IP address. 1634 * @return string|false The valid IP address, otherwise false. 1635 */ 1636 function rest_is_ip_address( $ip ) { 1637 $ipv4_pattern = '/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/'; 1638 1639 if ( ! preg_match( $ipv4_pattern, $ip ) && ! WpOrg\Requests\Ipv6::check_ipv6( $ip ) ) { 1640 return false; 1641 } 1642 1643 return $ip; 1644 } 1645 1646 /** 1647 * Changes a boolean-like value into the proper boolean value. 1648 * 1649 * @since 4.7.0 1650 * 1651 * @param bool|string|int $value The value being evaluated. 1652 * @return bool Returns the proper associated boolean value. 1653 * 1654 * @phpstan-return ( 1655 * $value is false|''|'0'|0|'false'|'False'|'FALSE' 1656 * ? false 1657 * : ( $value is true|int|lowercase-string ? true : bool ) 1658 * ) 1659 */ 1660 function rest_sanitize_boolean( $value ) { 1661 // String values are translated to `true`; make sure 'false' is false. 1662 if ( is_string( $value ) ) { 1663 $value = strtolower( $value ); 1664 if ( in_array( $value, array( 'false', '0' ), true ) ) { 1665 $value = false; 1666 } 1667 } 1668 1669 // Everything else will map nicely to boolean. 1670 return (bool) $value; 1671 } 1672 1673 /** 1674 * Determines if a given value is boolean-like. 1675 * 1676 * @since 4.7.0 1677 * 1678 * @param bool|string $maybe_bool The value being evaluated. 1679 * @return bool True if a boolean, otherwise false. 1680 */ 1681 function rest_is_boolean( $maybe_bool ) { 1682 if ( is_bool( $maybe_bool ) ) { 1683 return true; 1684 } 1685 1686 if ( is_string( $maybe_bool ) ) { 1687 $maybe_bool = strtolower( $maybe_bool ); 1688 1689 $valid_boolean_values = array( 1690 'false', 1691 'true', 1692 '0', 1693 '1', 1694 ); 1695 1696 return in_array( $maybe_bool, $valid_boolean_values, true ); 1697 } 1698 1699 if ( is_int( $maybe_bool ) ) { 1700 return in_array( $maybe_bool, array( 0, 1 ), true ); 1701 } 1702 1703 return false; 1704 } 1705 1706 /** 1707 * Determines if a given value is integer-like. 1708 * 1709 * This reports whether the value represents an integer; it does not guarantee that the 1710 * value can be represented as a native PHP integer. Values whose magnitude exceeds 1711 * `PHP_INT_MAX` are still reported as integer-like, even though the `(int)` cast that 1712 * {@see rest_sanitize_value_from_schema()} applies for the 'integer' type cannot round-trip 1713 * them: an out-of-range numeric *string* saturates to `PHP_INT_MAX` or `PHP_INT_MIN`, while 1714 * an out-of-range *float* is an undefined conversion in PHP that yields an arbitrary wrapped 1715 * value. Likewise, a numeric value with a fractional part that is too large for the fraction 1716 * to be represented as a float (greater than 2 ** 53) is reported as integer-like. 1717 * 1718 * @since 5.5.0 1719 * 1720 * @param mixed $maybe_integer The value being evaluated. 1721 * @return bool True if an integer, otherwise false. 1722 */ 1723 function rest_is_integer( $maybe_integer ): bool { 1724 if ( is_int( $maybe_integer ) ) { 1725 return true; 1726 } 1727 1728 // A canonical integer string of any magnitude — verified without float conversion. 1729 if ( is_string( $maybe_integer ) && preg_match( '/^\s*[+-]?[0-9]+\s*$/', $maybe_integer ) ) { 1730 return true; 1731 } 1732 1733 // Decimal and scientific-notation strings (and floats) keep their historical behavior. 1734 if ( ! is_numeric( $maybe_integer ) ) { 1735 return false; 1736 } 1737 $float_value = (float) $maybe_integer; 1738 1739 /* 1740 * The strict equality here is not the unreliable "are two computed floats equal" comparison 1741 * (e.g. 0.1 + 0.2 === 0.3, which is false). It compares a float to its own floor() to ask 1742 * "does this float have a fractional part?". A float is whole exactly when it equals its floor, 1743 * so the comparison is exact and safe regardless of floating-point representation error. 1744 */ 1745 return floor( $float_value ) === $float_value; 1746 } 1747 1748 /** 1749 * Determines if a given value is array-like. 1750 * 1751 * @since 5.5.0 1752 * 1753 * @param mixed $maybe_array The value being evaluated. 1754 * @return bool 1755 */ 1756 function rest_is_array( $maybe_array ) { 1757 if ( is_scalar( $maybe_array ) ) { 1758 $maybe_array = wp_parse_list( $maybe_array ); 1759 } 1760 1761 return wp_is_numeric_array( $maybe_array ); 1762 } 1763 1764 /** 1765 * Converts an array-like value to an array. 1766 * 1767 * @since 5.5.0 1768 * 1769 * @param mixed $maybe_array The value being evaluated. 1770 * @return array Returns the array extracted from the value. 1771 */ 1772 function rest_sanitize_array( $maybe_array ) { 1773 if ( is_scalar( $maybe_array ) ) { 1774 return wp_parse_list( $maybe_array ); 1775 } 1776 1777 if ( ! is_array( $maybe_array ) ) { 1778 return array(); 1779 } 1780 1781 // Normalize to numeric array so nothing unexpected is in the keys. 1782 return array_values( $maybe_array ); 1783 } 1784 1785 /** 1786 * Determines if a given value is object-like. 1787 * 1788 * @since 5.5.0 1789 * 1790 * @param mixed $maybe_object The value being evaluated. 1791 * @return bool True if object like, otherwise false. 1792 */ 1793 function rest_is_object( $maybe_object ) { 1794 if ( '' === $maybe_object ) { 1795 return true; 1796 } 1797 1798 if ( $maybe_object instanceof stdClass ) { 1799 return true; 1800 } 1801 1802 if ( $maybe_object instanceof JsonSerializable ) { 1803 $maybe_object = $maybe_object->jsonSerialize(); 1804 } 1805 1806 return is_array( $maybe_object ); 1807 } 1808 1809 /** 1810 * Converts an object-like value to an array. 1811 * 1812 * @since 5.5.0 1813 * 1814 * @param mixed $maybe_object The value being evaluated. 1815 * @return array Returns the object extracted from the value as an associative array. 1816 */ 1817 function rest_sanitize_object( $maybe_object ) { 1818 if ( '' === $maybe_object ) { 1819 return array(); 1820 } 1821 1822 if ( $maybe_object instanceof stdClass ) { 1823 return (array) $maybe_object; 1824 } 1825 1826 if ( $maybe_object instanceof JsonSerializable ) { 1827 $maybe_object = $maybe_object->jsonSerialize(); 1828 } 1829 1830 if ( ! is_array( $maybe_object ) ) { 1831 return array(); 1832 } 1833 1834 return $maybe_object; 1835 } 1836 1837 /** 1838 * Gets the best type for a value. 1839 * 1840 * @since 5.5.0 1841 * 1842 * @param mixed $value The value to check. 1843 * @param string[] $types The list of possible types. 1844 * @return string The best matching type, an empty string if no types match. 1845 */ 1846 function rest_get_best_type_for_value( $value, $types ) { 1847 static $checks = array( 1848 'array' => 'rest_is_array', 1849 'object' => 'rest_is_object', 1850 'integer' => 'rest_is_integer', 1851 'number' => 'is_numeric', 1852 'boolean' => 'rest_is_boolean', 1853 'string' => 'is_string', 1854 'null' => 'is_null', 1855 ); 1856 1857 /* 1858 * Both arrays and objects allow empty strings to be converted to their types. 1859 * But the best answer for this type is a string. 1860 */ 1861 if ( '' === $value && in_array( 'string', $types, true ) ) { 1862 return 'string'; 1863 } 1864 1865 foreach ( $types as $type ) { 1866 if ( isset( $checks[ $type ] ) && $checks[ $type ]( $value ) ) { 1867 return $type; 1868 } 1869 } 1870 1871 return ''; 1872 } 1873 1874 /** 1875 * Handles getting the best type for a multi-type schema. 1876 * 1877 * This is a wrapper for {@see rest_get_best_type_for_value()} that handles 1878 * backward compatibility for schemas that use invalid types. 1879 * 1880 * @since 5.5.0 1881 * 1882 * @param mixed $value The value to check. 1883 * @param array $args The schema array to use. 1884 * @param string $param The parameter name, used in error messages. 1885 * @return string 1886 */ 1887 function rest_handle_multi_type_schema( $value, $args, $param = '' ) { 1888 $allowed_types = array( 'array', 'object', 'string', 'number', 'integer', 'boolean', 'null' ); 1889 $invalid_types = array_diff( $args['type'], $allowed_types ); 1890 1891 if ( $invalid_types ) { 1892 _doing_it_wrong( 1893 __FUNCTION__, 1894 /* translators: 1: Parameter, 2: List of allowed types. */ 1895 wp_sprintf( __( 'The "type" schema keyword for %1$s can only contain the built-in types: %2$l.' ), $param, $allowed_types ), 1896 '5.5.0' 1897 ); 1898 } 1899 1900 $best_type = rest_get_best_type_for_value( $value, $args['type'] ); 1901 1902 if ( ! $best_type ) { 1903 if ( ! $invalid_types ) { 1904 return ''; 1905 } 1906 1907 // Backward compatibility for previous behavior which allowed the value if there was an invalid type used. 1908 $best_type = reset( $invalid_types ); 1909 } 1910 1911 return $best_type; 1912 } 1913 1914 /** 1915 * Checks if an array is made up of unique items. 1916 * 1917 * @since 5.5.0 1918 * 1919 * @param array $input_array The array to check. 1920 * @return bool True if the array contains unique items, false otherwise. 1921 */ 1922 function rest_validate_array_contains_unique_items( $input_array ) { 1923 $seen = array(); 1924 1925 foreach ( $input_array as $item ) { 1926 $stabilized = rest_stabilize_value( $item ); 1927 $key = serialize( $stabilized ); 1928 1929 if ( ! isset( $seen[ $key ] ) ) { 1930 $seen[ $key ] = true; 1931 1932 continue; 1933 } 1934 1935 return false; 1936 } 1937 1938 return true; 1939 } 1940 1941 /** 1942 * Stabilizes a value following JSON Schema semantics. 1943 * 1944 * For lists, order is preserved. For objects, properties are reordered alphabetically. 1945 * 1946 * @since 5.5.0 1947 * 1948 * @param mixed $value The value to stabilize. Must already be sanitized. Objects should have been converted to arrays. 1949 * @return mixed The stabilized value. 1950 */ 1951 function rest_stabilize_value( $value ) { 1952 if ( is_scalar( $value ) || is_null( $value ) ) { 1953 return $value; 1954 } 1955 1956 if ( is_object( $value ) ) { 1957 _doing_it_wrong( __FUNCTION__, __( 'Cannot stabilize objects. Convert the object to an array first.' ), '5.5.0' ); 1958 1959 return $value; 1960 } 1961 1962 ksort( $value ); 1963 1964 foreach ( $value as $k => $v ) { 1965 $value[ $k ] = rest_stabilize_value( $v ); 1966 } 1967 1968 return $value; 1969 } 1970 1971 /** 1972 * Validates if the JSON Schema pattern matches a value. 1973 * 1974 * @since 5.6.0 1975 * 1976 * @param string $pattern The pattern to match against. 1977 * @param string $value The value to check. 1978 * @return bool True if the pattern matches the given value, false otherwise. 1979 */ 1980 function rest_validate_json_schema_pattern( $pattern, $value ) { 1981 $escaped_pattern = str_replace( '#', '\\#', $pattern ); 1982 1983 return 1 === preg_match( '#' . $escaped_pattern . '#u', $value ); 1984 } 1985 1986 /** 1987 * Finds the schema for a property using the patternProperties keyword. 1988 * 1989 * @since 5.6.0 1990 * 1991 * @param string $property The property name to check. 1992 * @param array $args The schema array to use. 1993 * @return array|null The schema of matching pattern property, or null if no patterns match. 1994 */ 1995 function rest_find_matching_pattern_property_schema( $property, $args ) { 1996 if ( isset( $args['patternProperties'] ) ) { 1997 foreach ( $args['patternProperties'] as $pattern => $child_schema ) { 1998 if ( rest_validate_json_schema_pattern( $pattern, $property ) ) { 1999 return $child_schema; 2000 } 2001 } 2002 } 2003 2004 return null; 2005 } 2006 2007 /** 2008 * Formats a combining operation error into a WP_Error object. 2009 * 2010 * @since 5.6.0 2011 * 2012 * @param string $param The parameter name. 2013 * @param array $error The error details. 2014 * @return WP_Error 2015 */ 2016 function rest_format_combining_operation_error( $param, $error ) { 2017 $position = $error['index']; 2018 $reason = $error['error_object']->get_error_message(); 2019 2020 if ( isset( $error['schema']['title'] ) ) { 2021 $title = $error['schema']['title']; 2022 2023 return new WP_Error( 2024 'rest_no_matching_schema', 2025 /* translators: 1: Parameter, 2: Schema title, 3: Reason. */ 2026 sprintf( __( '%1$s is not a valid %2$s. Reason: %3$s' ), $param, $title, $reason ), 2027 array( 'position' => $position ) 2028 ); 2029 } 2030 2031 return new WP_Error( 2032 'rest_no_matching_schema', 2033 /* translators: 1: Parameter, 2: Reason. */ 2034 sprintf( __( '%1$s does not match the expected format. Reason: %2$s' ), $param, $reason ), 2035 array( 'position' => $position ) 2036 ); 2037 } 2038 2039 /** 2040 * Gets the error of combining operation. 2041 * 2042 * @since 5.6.0 2043 * 2044 * @param array $value The value to validate. 2045 * @param string $param The parameter name, used in error messages. 2046 * @param array $errors The errors array, to search for possible error. 2047 * @return WP_Error The combining operation error. 2048 */ 2049 function rest_get_combining_operation_error( $value, $param, $errors ) { 2050 // If there is only one error, simply return it. 2051 if ( 1 === count( $errors ) ) { 2052 return rest_format_combining_operation_error( $param, $errors[0] ); 2053 } 2054 2055 // Filter out all errors related to type validation. 2056 $filtered_errors = array(); 2057 foreach ( $errors as $error ) { 2058 $error_code = $error['error_object']->get_error_code(); 2059 $error_data = $error['error_object']->get_error_data(); 2060 2061 if ( 'rest_invalid_type' !== $error_code || ( isset( $error_data['param'] ) && $param !== $error_data['param'] ) ) { 2062 $filtered_errors[] = $error; 2063 } 2064 } 2065 2066 // If there is only one error left, simply return it. 2067 if ( 1 === count( $filtered_errors ) ) { 2068 return rest_format_combining_operation_error( $param, $filtered_errors[0] ); 2069 } 2070 2071 // If there are only errors related to object validation, try choosing the most appropriate one. 2072 if ( count( $filtered_errors ) > 1 && 'object' === $filtered_errors[0]['schema']['type'] ) { 2073 $result = null; 2074 $number = 0; 2075 2076 foreach ( $filtered_errors as $error ) { 2077 if ( isset( $error['schema']['properties'] ) ) { 2078 $n = count( array_intersect_key( $error['schema']['properties'], $value ) ); 2079 if ( $n > $number ) { 2080 $result = $error; 2081 $number = $n; 2082 } 2083 } 2084 } 2085 2086 if ( null !== $result ) { 2087 return rest_format_combining_operation_error( $param, $result ); 2088 } 2089 } 2090 2091 // If each schema has a title, include those titles in the error message. 2092 $schema_titles = array(); 2093 foreach ( $errors as $error ) { 2094 if ( isset( $error['schema']['title'] ) ) { 2095 $schema_titles[] = $error['schema']['title']; 2096 } 2097 } 2098 2099 if ( count( $schema_titles ) === count( $errors ) ) { 2100 /* translators: 1: Parameter, 2: Schema titles. */ 2101 return new WP_Error( 'rest_no_matching_schema', wp_sprintf( __( '%1$s is not a valid %2$l.' ), $param, $schema_titles ) ); 2102 } 2103 2104 /* translators: %s: Parameter. */ 2105 return new WP_Error( 'rest_no_matching_schema', sprintf( __( '%s does not match any of the expected formats.' ), $param ) ); 2106 } 2107 2108 /** 2109 * Finds the matching schema among the "anyOf" schemas. 2110 * 2111 * @since 5.6.0 2112 * 2113 * @param mixed $value The value to validate. 2114 * @param array $args The schema array to use. 2115 * @param string $param The parameter name, used in error messages. 2116 * @return array|WP_Error The matching schema or WP_Error instance if all schemas do not match. 2117 */ 2118 function rest_find_any_matching_schema( $value, $args, $param ) { 2119 $errors = array(); 2120 2121 foreach ( $args['anyOf'] as $index => $schema ) { 2122 if ( ! isset( $schema['type'] ) && isset( $args['type'] ) ) { 2123 $schema['type'] = $args['type']; 2124 } 2125 2126 $is_valid = rest_validate_value_from_schema( $value, $schema, $param ); 2127 if ( ! is_wp_error( $is_valid ) ) { 2128 return $schema; 2129 } 2130 2131 $errors[] = array( 2132 'error_object' => $is_valid, 2133 'schema' => $schema, 2134 'index' => $index, 2135 ); 2136 } 2137 2138 return rest_get_combining_operation_error( $value, $param, $errors ); 2139 } 2140 2141 /** 2142 * Finds the matching schema among the "oneOf" schemas. 2143 * 2144 * @since 5.6.0 2145 * 2146 * @param mixed $value The value to validate. 2147 * @param array $args The schema array to use. 2148 * @param string $param The parameter name, used in error messages. 2149 * @param bool $stop_after_first_match Optional. Whether the process should stop after the first successful match. 2150 * @return array|WP_Error The matching schema or WP_Error instance if the number of matching schemas is not equal to one. 2151 */ 2152 function rest_find_one_matching_schema( $value, $args, $param, $stop_after_first_match = false ) { 2153 $matching_schemas = array(); 2154 $errors = array(); 2155 2156 foreach ( $args['oneOf'] as $index => $schema ) { 2157 if ( ! isset( $schema['type'] ) && isset( $args['type'] ) ) { 2158 $schema['type'] = $args['type']; 2159 } 2160 2161 $is_valid = rest_validate_value_from_schema( $value, $schema, $param ); 2162 if ( ! is_wp_error( $is_valid ) ) { 2163 if ( $stop_after_first_match ) { 2164 return $schema; 2165 } 2166 2167 $matching_schemas[] = array( 2168 'schema_object' => $schema, 2169 'index' => $index, 2170 ); 2171 } else { 2172 $errors[] = array( 2173 'error_object' => $is_valid, 2174 'schema' => $schema, 2175 'index' => $index, 2176 ); 2177 } 2178 } 2179 2180 if ( ! $matching_schemas ) { 2181 return rest_get_combining_operation_error( $value, $param, $errors ); 2182 } 2183 2184 if ( count( $matching_schemas ) > 1 ) { 2185 $schema_positions = array(); 2186 $schema_titles = array(); 2187 2188 foreach ( $matching_schemas as $schema ) { 2189 $schema_positions[] = $schema['index']; 2190 2191 if ( isset( $schema['schema_object']['title'] ) ) { 2192 $schema_titles[] = $schema['schema_object']['title']; 2193 } 2194 } 2195 2196 // If each schema has a title, include those titles in the error message. 2197 if ( count( $schema_titles ) === count( $matching_schemas ) ) { 2198 return new WP_Error( 2199 'rest_one_of_multiple_matches', 2200 /* translators: 1: Parameter, 2: Schema titles. */ 2201 wp_sprintf( __( '%1$s matches %2$l, but should match only one.' ), $param, $schema_titles ), 2202 array( 'positions' => $schema_positions ) 2203 ); 2204 } 2205 2206 return new WP_Error( 2207 'rest_one_of_multiple_matches', 2208 /* translators: %s: Parameter. */ 2209 sprintf( __( '%s matches more than one of the expected formats.' ), $param ), 2210 array( 'positions' => $schema_positions ) 2211 ); 2212 } 2213 2214 return $matching_schemas[0]['schema_object']; 2215 } 2216 2217 /** 2218 * Checks the equality of two values, following JSON Schema semantics. 2219 * 2220 * Property order is ignored for objects. 2221 * 2222 * Values must have been previously sanitized/coerced to their native types. 2223 * 2224 * @since 5.7.0 2225 * 2226 * @param mixed $value1 The first value to check. 2227 * @param mixed $value2 The second value to check. 2228 * @return bool True if the values are equal or false otherwise. 2229 */ 2230 function rest_are_values_equal( $value1, $value2 ) { 2231 if ( is_array( $value1 ) && is_array( $value2 ) ) { 2232 if ( count( $value1 ) !== count( $value2 ) ) { 2233 return false; 2234 } 2235 2236 return array_all( 2237 $value1, 2238 fn( $value, $index ) => array_key_exists( $index, $value2 ) && rest_are_values_equal( $value, $value2[ $index ] ) 2239 ); 2240 } 2241 2242 if ( is_int( $value1 ) && is_float( $value2 ) 2243 || is_float( $value1 ) && is_int( $value2 ) 2244 ) { 2245 return (float) $value1 === (float) $value2; 2246 } 2247 2248 return $value1 === $value2; 2249 } 2250 2251 /** 2252 * Validates that the given value is a member of the JSON Schema "enum". 2253 * 2254 * @since 5.7.0 2255 * 2256 * @param mixed $value The value to validate. 2257 * @param array $args The schema array to use. 2258 * @param string $param The parameter name, used in error messages. 2259 * @return true|WP_Error True if the "enum" contains the value or a WP_Error instance otherwise. 2260 */ 2261 function rest_validate_enum( $value, $args, $param ) { 2262 $sanitized_value = rest_sanitize_value_from_schema( $value, $args, $param ); 2263 if ( is_wp_error( $sanitized_value ) ) { 2264 return $sanitized_value; 2265 } 2266 2267 foreach ( $args['enum'] as $enum_value ) { 2268 if ( rest_are_values_equal( $sanitized_value, $enum_value ) ) { 2269 return true; 2270 } 2271 } 2272 2273 $encoded_enum_values = array(); 2274 foreach ( $args['enum'] as $enum_value ) { 2275 $encoded_enum_values[] = is_scalar( $enum_value ) ? $enum_value : wp_json_encode( $enum_value ); 2276 } 2277 2278 if ( count( $encoded_enum_values ) === 1 ) { 2279 /* translators: 1: Parameter, 2: Valid values. */ 2280 return new WP_Error( 'rest_not_in_enum', wp_sprintf( __( '%1$s is not %2$s.' ), $param, $encoded_enum_values[0] ) ); 2281 } 2282 2283 /* translators: 1: Parameter, 2: List of valid values. */ 2284 return new WP_Error( 'rest_not_in_enum', wp_sprintf( __( '%1$s is not one of %2$l.' ), $param, $encoded_enum_values ) ); 2285 } 2286 2287 /** 2288 * Get all valid JSON schema properties. 2289 * 2290 * @since 5.6.0 2291 * 2292 * @return string[] All valid JSON schema properties. 2293 */ 2294 function rest_get_allowed_schema_keywords() { 2295 return array( 2296 'title', 2297 'description', 2298 'default', 2299 'type', 2300 'format', 2301 'enum', 2302 'items', 2303 'properties', 2304 'additionalProperties', 2305 'patternProperties', 2306 'minProperties', 2307 'maxProperties', 2308 'minimum', 2309 'maximum', 2310 'exclusiveMinimum', 2311 'exclusiveMaximum', 2312 'multipleOf', 2313 'minLength', 2314 'maxLength', 2315 'pattern', 2316 'minItems', 2317 'maxItems', 2318 'uniqueItems', 2319 'anyOf', 2320 'oneOf', 2321 ); 2322 } 2323 2324 /** 2325 * Validate a value based on a schema. 2326 * 2327 * @since 4.7.0 2328 * @since 4.9.0 Support the "object" type. 2329 * @since 5.2.0 Support validating "additionalProperties" against a schema. 2330 * @since 5.3.0 Support multiple types. 2331 * @since 5.4.0 Convert an empty string to an empty object. 2332 * @since 5.5.0 Add the "uuid" and "hex-color" formats. 2333 * Support the "minLength", "maxLength" and "pattern" keywords for strings. 2334 * Support the "minItems", "maxItems" and "uniqueItems" keywords for arrays. 2335 * Validate required properties. 2336 * @since 5.6.0 Support the "minProperties" and "maxProperties" keywords for objects. 2337 * Support the "multipleOf" keyword for numbers and integers. 2338 * Support the "patternProperties" keyword for objects. 2339 * Support the "anyOf" and "oneOf" keywords. 2340 * 2341 * @param mixed $value The value to validate. 2342 * @param array $args Schema array to use for validation. 2343 * @param string $param The parameter name, used in error messages. 2344 * @return true|WP_Error 2345 */ 2346 function rest_validate_value_from_schema( $value, $args, $param = '' ) { 2347 if ( isset( $args['anyOf'] ) ) { 2348 $matching_schema = rest_find_any_matching_schema( $value, $args, $param ); 2349 if ( is_wp_error( $matching_schema ) ) { 2350 return $matching_schema; 2351 } 2352 2353 if ( ! isset( $args['type'] ) && isset( $matching_schema['type'] ) ) { 2354 $args['type'] = $matching_schema['type']; 2355 } 2356 } 2357 2358 if ( isset( $args['oneOf'] ) ) { 2359 $matching_schema = rest_find_one_matching_schema( $value, $args, $param ); 2360 if ( is_wp_error( $matching_schema ) ) { 2361 return $matching_schema; 2362 } 2363 2364 if ( ! isset( $args['type'] ) && isset( $matching_schema['type'] ) ) { 2365 $args['type'] = $matching_schema['type']; 2366 } 2367 } 2368 2369 $allowed_types = array( 'array', 'object', 'string', 'number', 'integer', 'boolean', 'null' ); 2370 2371 if ( ! isset( $args['type'] ) ) { 2372 /* translators: %s: Parameter. */ 2373 _doing_it_wrong( __FUNCTION__, sprintf( __( 'The "type" schema keyword for %s is required.' ), $param ), '5.5.0' ); 2374 } 2375 2376 if ( is_array( $args['type'] ) ) { 2377 $best_type = rest_handle_multi_type_schema( $value, $args, $param ); 2378 2379 if ( ! $best_type ) { 2380 return new WP_Error( 2381 'rest_invalid_type', 2382 /* translators: 1: Parameter, 2: List of types. */ 2383 sprintf( __( '%1$s is not of type %2$s.' ), $param, implode( ',', $args['type'] ) ), 2384 array( 'param' => $param ) 2385 ); 2386 } 2387 2388 $args['type'] = $best_type; 2389 } 2390 2391 if ( ! in_array( $args['type'], $allowed_types, true ) ) { 2392 _doing_it_wrong( 2393 __FUNCTION__, 2394 /* translators: 1: Parameter, 2: The list of allowed types. */ 2395 wp_sprintf( __( 'The "type" schema keyword for %1$s can only be one of the built-in types: %2$l.' ), $param, $allowed_types ), 2396 '5.5.0' 2397 ); 2398 } 2399 2400 switch ( $args['type'] ) { 2401 case 'null': 2402 $is_valid = rest_validate_null_value_from_schema( $value, $param ); 2403 break; 2404 case 'boolean': 2405 $is_valid = rest_validate_boolean_value_from_schema( $value, $param ); 2406 break; 2407 case 'object': 2408 $is_valid = rest_validate_object_value_from_schema( $value, $args, $param ); 2409 break; 2410 case 'array': 2411 $is_valid = rest_validate_array_value_from_schema( $value, $args, $param ); 2412 break; 2413 case 'number': 2414 $is_valid = rest_validate_number_value_from_schema( $value, $args, $param ); 2415 break; 2416 case 'string': 2417 $is_valid = rest_validate_string_value_from_schema( $value, $args, $param ); 2418 break; 2419 case 'integer': 2420 $is_valid = rest_validate_integer_value_from_schema( $value, $args, $param ); 2421 break; 2422 default: 2423 $is_valid = true; 2424 break; 2425 } 2426 2427 if ( is_wp_error( $is_valid ) ) { 2428 return $is_valid; 2429 } 2430 2431 if ( ! empty( $args['enum'] ) ) { 2432 $enum_contains_value = rest_validate_enum( $value, $args, $param ); 2433 if ( is_wp_error( $enum_contains_value ) ) { 2434 return $enum_contains_value; 2435 } 2436 } 2437 2438 /* 2439 * The "format" keyword should only be applied to strings. However, for backward compatibility, 2440 * we allow the "format" keyword if the type keyword was not specified, or was set to an invalid value. 2441 */ 2442 if ( isset( $args['format'] ) 2443 && ( ! isset( $args['type'] ) || 'string' === $args['type'] || ! in_array( $args['type'], $allowed_types, true ) ) 2444 ) { 2445 switch ( $args['format'] ) { 2446 case 'hex-color': 2447 if ( ! rest_parse_hex_color( $value ) ) { 2448 return new WP_Error( 'rest_invalid_hex_color', __( 'Invalid hex color.' ) ); 2449 } 2450 break; 2451 2452 case 'date-time': 2453 if ( false === rest_parse_date( $value ) ) { 2454 return new WP_Error( 'rest_invalid_date', __( 'Invalid date.' ) ); 2455 } 2456 break; 2457 2458 case 'email': 2459 if ( ! is_email( $value ) ) { 2460 return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ) ); 2461 } 2462 break; 2463 case 'ip': 2464 if ( ! rest_is_ip_address( $value ) ) { 2465 /* translators: %s: IP address. */ 2466 return new WP_Error( 'rest_invalid_ip', sprintf( __( '%s is not a valid IP address.' ), $param ) ); 2467 } 2468 break; 2469 case 'uuid': 2470 if ( ! wp_is_uuid( $value ) ) { 2471 /* translators: %s: The name of a JSON field expecting a valid UUID. */ 2472 return new WP_Error( 'rest_invalid_uuid', sprintf( __( '%s is not a valid UUID.' ), $param ) ); 2473 } 2474 break; 2475 } 2476 } 2477 2478 return true; 2479 } 2480 2481 /** 2482 * Validates a null value based on a schema. 2483 * 2484 * @since 5.7.0 2485 * 2486 * @param mixed $value The value to validate. 2487 * @param string $param The parameter name, used in error messages. 2488 * @return true|WP_Error 2489 */ 2490 function rest_validate_null_value_from_schema( $value, $param ) { 2491 if ( null !== $value ) { 2492 return new WP_Error( 2493 'rest_invalid_type', 2494 /* translators: 1: Parameter, 2: Type name. */ 2495 sprintf( __( '%1$s is not of type %2$s.' ), $param, 'null' ), 2496 array( 'param' => $param ) 2497 ); 2498 } 2499 2500 return true; 2501 } 2502 2503 /** 2504 * Validates a boolean value based on a schema. 2505 * 2506 * @since 5.7.0 2507 * 2508 * @param mixed $value The value to validate. 2509 * @param string $param The parameter name, used in error messages. 2510 * @return true|WP_Error 2511 */ 2512 function rest_validate_boolean_value_from_schema( $value, $param ) { 2513 if ( ! rest_is_boolean( $value ) ) { 2514 return new WP_Error( 2515 'rest_invalid_type', 2516 /* translators: 1: Parameter, 2: Type name. */ 2517 sprintf( __( '%1$s is not of type %2$s.' ), $param, 'boolean' ), 2518 array( 'param' => $param ) 2519 ); 2520 } 2521 2522 return true; 2523 } 2524 2525 /** 2526 * Validates an object value based on a schema. 2527 * 2528 * @since 5.7.0 2529 * 2530 * @param mixed $value The value to validate. 2531 * @param array $args Schema array to use for validation. 2532 * @param string $param The parameter name, used in error messages. 2533 * @return true|WP_Error 2534 */ 2535 function rest_validate_object_value_from_schema( $value, $args, $param ) { 2536 if ( ! rest_is_object( $value ) ) { 2537 return new WP_Error( 2538 'rest_invalid_type', 2539 /* translators: 1: Parameter, 2: Type name. */ 2540 sprintf( __( '%1$s is not of type %2$s.' ), $param, 'object' ), 2541 array( 'param' => $param ) 2542 ); 2543 } 2544 2545 $value = rest_sanitize_object( $value ); 2546 2547 if ( isset( $args['required'] ) && is_array( $args['required'] ) ) { // schema version 4 2548 foreach ( $args['required'] as $name ) { 2549 if ( ! array_key_exists( $name, $value ) ) { 2550 return new WP_Error( 2551 'rest_property_required', 2552 /* translators: 1: Property of an object, 2: Parameter. */ 2553 sprintf( __( '%1$s is a required property of %2$s.' ), $name, $param ) 2554 ); 2555 } 2556 } 2557 } elseif ( isset( $args['properties'] ) ) { // schema version 3 2558 foreach ( $args['properties'] as $name => $property ) { 2559 if ( isset( $property['required'] ) && true === $property['required'] && ! array_key_exists( $name, $value ) ) { 2560 return new WP_Error( 2561 'rest_property_required', 2562 /* translators: 1: Property of an object, 2: Parameter. */ 2563 sprintf( __( '%1$s is a required property of %2$s.' ), $name, $param ) 2564 ); 2565 } 2566 } 2567 } 2568 2569 foreach ( $value as $property => $v ) { 2570 if ( isset( $args['properties'][ $property ] ) ) { 2571 $is_valid = rest_validate_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' ); 2572 if ( is_wp_error( $is_valid ) ) { 2573 return $is_valid; 2574 } 2575 continue; 2576 } 2577 2578 $pattern_property_schema = rest_find_matching_pattern_property_schema( $property, $args ); 2579 if ( null !== $pattern_property_schema ) { 2580 $is_valid = rest_validate_value_from_schema( $v, $pattern_property_schema, $param . '[' . $property . ']' ); 2581 if ( is_wp_error( $is_valid ) ) { 2582 return $is_valid; 2583 } 2584 continue; 2585 } 2586 2587 if ( isset( $args['additionalProperties'] ) ) { 2588 if ( false === $args['additionalProperties'] ) { 2589 return new WP_Error( 2590 'rest_additional_properties_forbidden', 2591 /* translators: %s: Property of an object. */ 2592 sprintf( __( '%1$s is not a valid property of Object.' ), $property ) 2593 ); 2594 } 2595 2596 if ( is_array( $args['additionalProperties'] ) ) { 2597 $is_valid = rest_validate_value_from_schema( $v, $args['additionalProperties'], $param . '[' . $property . ']' ); 2598 if ( is_wp_error( $is_valid ) ) { 2599 return $is_valid; 2600 } 2601 } 2602 } 2603 } 2604 2605 if ( isset( $args['minProperties'] ) && count( $value ) < $args['minProperties'] ) { 2606 return new WP_Error( 2607 'rest_too_few_properties', 2608 sprintf( 2609 /* translators: 1: Parameter, 2: Number. */ 2610 _n( 2611 '%1$s must contain at least %2$s property.', 2612 '%1$s must contain at least %2$s properties.', 2613 $args['minProperties'] 2614 ), 2615 $param, 2616 number_format_i18n( $args['minProperties'] ) 2617 ) 2618 ); 2619 } 2620 2621 if ( isset( $args['maxProperties'] ) && count( $value ) > $args['maxProperties'] ) { 2622 return new WP_Error( 2623 'rest_too_many_properties', 2624 sprintf( 2625 /* translators: 1: Parameter, 2: Number. */ 2626 _n( 2627 '%1$s must contain at most %2$s property.', 2628 '%1$s must contain at most %2$s properties.', 2629 $args['maxProperties'] 2630 ), 2631 $param, 2632 number_format_i18n( $args['maxProperties'] ) 2633 ) 2634 ); 2635 } 2636 2637 return true; 2638 } 2639 2640 /** 2641 * Validates an array value based on a schema. 2642 * 2643 * @since 5.7.0 2644 * 2645 * @param mixed $value The value to validate. 2646 * @param array $args Schema array to use for validation. 2647 * @param string $param The parameter name, used in error messages. 2648 * @return true|WP_Error 2649 */ 2650 function rest_validate_array_value_from_schema( $value, $args, $param ) { 2651 if ( ! rest_is_array( $value ) ) { 2652 return new WP_Error( 2653 'rest_invalid_type', 2654 /* translators: 1: Parameter, 2: Type name. */ 2655 sprintf( __( '%1$s is not of type %2$s.' ), $param, 'array' ), 2656 array( 'param' => $param ) 2657 ); 2658 } 2659 2660 $value = rest_sanitize_array( $value ); 2661 2662 if ( isset( $args['items'] ) ) { 2663 foreach ( $value as $index => $v ) { 2664 $is_valid = rest_validate_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' ); 2665 if ( is_wp_error( $is_valid ) ) { 2666 return $is_valid; 2667 } 2668 } 2669 } 2670 2671 if ( isset( $args['minItems'] ) && count( $value ) < $args['minItems'] ) { 2672 return new WP_Error( 2673 'rest_too_few_items', 2674 sprintf( 2675 /* translators: 1: Parameter, 2: Number. */ 2676 _n( 2677 '%1$s must contain at least %2$s item.', 2678 '%1$s must contain at least %2$s items.', 2679 $args['minItems'] 2680 ), 2681 $param, 2682 number_format_i18n( $args['minItems'] ) 2683 ) 2684 ); 2685 } 2686 2687 if ( isset( $args['maxItems'] ) && count( $value ) > $args['maxItems'] ) { 2688 return new WP_Error( 2689 'rest_too_many_items', 2690 sprintf( 2691 /* translators: 1: Parameter, 2: Number. */ 2692 _n( 2693 '%1$s must contain at most %2$s item.', 2694 '%1$s must contain at most %2$s items.', 2695 $args['maxItems'] 2696 ), 2697 $param, 2698 number_format_i18n( $args['maxItems'] ) 2699 ) 2700 ); 2701 } 2702 2703 if ( ! empty( $args['uniqueItems'] ) && ! rest_validate_array_contains_unique_items( $value ) ) { 2704 /* translators: %s: Parameter. */ 2705 return new WP_Error( 'rest_duplicate_items', sprintf( __( '%s has duplicate items.' ), $param ) ); 2706 } 2707 2708 return true; 2709 } 2710 2711 /** 2712 * Validates a number value based on a schema. 2713 * 2714 * @since 5.7.0 2715 * 2716 * @param mixed $value The value to validate. 2717 * @param array $args Schema array to use for validation. 2718 * @param string $param The parameter name, used in error messages. 2719 * @return true|WP_Error 2720 */ 2721 function rest_validate_number_value_from_schema( $value, $args, $param ) { 2722 if ( ! is_numeric( $value ) ) { 2723 return new WP_Error( 2724 'rest_invalid_type', 2725 /* translators: 1: Parameter, 2: Type name. */ 2726 sprintf( __( '%1$s is not of type %2$s.' ), $param, $args['type'] ), 2727 array( 'param' => $param ) 2728 ); 2729 } 2730 2731 if ( isset( $args['multipleOf'] ) && fmod( $value, $args['multipleOf'] ) !== 0.0 ) { 2732 return new WP_Error( 2733 'rest_invalid_multiple', 2734 /* translators: 1: Parameter, 2: Multiplier. */ 2735 sprintf( __( '%1$s must be a multiple of %2$s.' ), $param, $args['multipleOf'] ) 2736 ); 2737 } 2738 2739 if ( isset( $args['minimum'] ) && ! isset( $args['maximum'] ) ) { 2740 if ( ! empty( $args['exclusiveMinimum'] ) && $value <= $args['minimum'] ) { 2741 return new WP_Error( 2742 'rest_out_of_bounds', 2743 /* translators: 1: Parameter, 2: Minimum number. */ 2744 sprintf( __( '%1$s must be greater than %2$d' ), $param, $args['minimum'] ) 2745 ); 2746 } 2747 2748 if ( empty( $args['exclusiveMinimum'] ) && $value < $args['minimum'] ) { 2749 return new WP_Error( 2750 'rest_out_of_bounds', 2751 /* translators: 1: Parameter, 2: Minimum number. */ 2752 sprintf( __( '%1$s must be greater than or equal to %2$d' ), $param, $args['minimum'] ) 2753 ); 2754 } 2755 } 2756 2757 if ( isset( $args['maximum'] ) && ! isset( $args['minimum'] ) ) { 2758 if ( ! empty( $args['exclusiveMaximum'] ) && $value >= $args['maximum'] ) { 2759 return new WP_Error( 2760 'rest_out_of_bounds', 2761 /* translators: 1: Parameter, 2: Maximum number. */ 2762 sprintf( __( '%1$s must be less than %2$d' ), $param, $args['maximum'] ) 2763 ); 2764 } 2765 2766 if ( empty( $args['exclusiveMaximum'] ) && $value > $args['maximum'] ) { 2767 return new WP_Error( 2768 'rest_out_of_bounds', 2769 /* translators: 1: Parameter, 2: Maximum number. */ 2770 sprintf( __( '%1$s must be less than or equal to %2$d' ), $param, $args['maximum'] ) 2771 ); 2772 } 2773 } 2774 2775 if ( isset( $args['minimum'], $args['maximum'] ) ) { 2776 if ( ! empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) { 2777 if ( $value >= $args['maximum'] || $value <= $args['minimum'] ) { 2778 return new WP_Error( 2779 'rest_out_of_bounds', 2780 sprintf( 2781 /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */ 2782 __( '%1$s must be between %2$d (exclusive) and %3$d (exclusive)' ), 2783 $param, 2784 $args['minimum'], 2785 $args['maximum'] 2786 ) 2787 ); 2788 } 2789 } 2790 2791 if ( ! empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) { 2792 if ( $value > $args['maximum'] || $value <= $args['minimum'] ) { 2793 return new WP_Error( 2794 'rest_out_of_bounds', 2795 sprintf( 2796 /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */ 2797 __( '%1$s must be between %2$d (exclusive) and %3$d (inclusive)' ), 2798 $param, 2799 $args['minimum'], 2800 $args['maximum'] 2801 ) 2802 ); 2803 } 2804 } 2805 2806 if ( ! empty( $args['exclusiveMaximum'] ) && empty( $args['exclusiveMinimum'] ) ) { 2807 if ( $value >= $args['maximum'] || $value < $args['minimum'] ) { 2808 return new WP_Error( 2809 'rest_out_of_bounds', 2810 sprintf( 2811 /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */ 2812 __( '%1$s must be between %2$d (inclusive) and %3$d (exclusive)' ), 2813 $param, 2814 $args['minimum'], 2815 $args['maximum'] 2816 ) 2817 ); 2818 } 2819 } 2820 2821 if ( empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) { 2822 if ( $value > $args['maximum'] || $value < $args['minimum'] ) { 2823 return new WP_Error( 2824 'rest_out_of_bounds', 2825 sprintf( 2826 /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */ 2827 __( '%1$s must be between %2$d (inclusive) and %3$d (inclusive)' ), 2828 $param, 2829 $args['minimum'], 2830 $args['maximum'] 2831 ) 2832 ); 2833 } 2834 } 2835 } 2836 2837 return true; 2838 } 2839 2840 /** 2841 * Validates a string value based on a schema. 2842 * 2843 * @since 5.7.0 2844 * 2845 * @param mixed $value The value to validate. 2846 * @param array $args Schema array to use for validation. 2847 * @param string $param The parameter name, used in error messages. 2848 * @return true|WP_Error 2849 */ 2850 function rest_validate_string_value_from_schema( $value, $args, $param ) { 2851 if ( ! is_string( $value ) ) { 2852 return new WP_Error( 2853 'rest_invalid_type', 2854 /* translators: 1: Parameter, 2: Type name. */ 2855 sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ), 2856 array( 'param' => $param ) 2857 ); 2858 } 2859 2860 if ( isset( $args['minLength'] ) && mb_strlen( $value ) < $args['minLength'] ) { 2861 return new WP_Error( 2862 'rest_too_short', 2863 sprintf( 2864 /* translators: 1: Parameter, 2: Number of characters. */ 2865 _n( 2866 '%1$s must be at least %2$s character long.', 2867 '%1$s must be at least %2$s characters long.', 2868 $args['minLength'] 2869 ), 2870 $param, 2871 number_format_i18n( $args['minLength'] ) 2872 ) 2873 ); 2874 } 2875 2876 if ( isset( $args['maxLength'] ) && mb_strlen( $value ) > $args['maxLength'] ) { 2877 return new WP_Error( 2878 'rest_too_long', 2879 sprintf( 2880 /* translators: 1: Parameter, 2: Number of characters. */ 2881 _n( 2882 '%1$s must be at most %2$s character long.', 2883 '%1$s must be at most %2$s characters long.', 2884 $args['maxLength'] 2885 ), 2886 $param, 2887 number_format_i18n( $args['maxLength'] ) 2888 ) 2889 ); 2890 } 2891 2892 if ( isset( $args['pattern'] ) && ! rest_validate_json_schema_pattern( $args['pattern'], $value ) ) { 2893 return new WP_Error( 2894 'rest_invalid_pattern', 2895 /* translators: 1: Parameter, 2: Pattern. */ 2896 sprintf( __( '%1$s does not match pattern %2$s.' ), $param, $args['pattern'] ) 2897 ); 2898 } 2899 2900 return true; 2901 } 2902 2903 /** 2904 * Validates an integer value based on a schema. 2905 * 2906 * @since 5.7.0 2907 * 2908 * @param mixed $value The value to validate. 2909 * @param array $args Schema array to use for validation. 2910 * @param string $param The parameter name, used in error messages. 2911 * @return true|WP_Error 2912 */ 2913 function rest_validate_integer_value_from_schema( $value, $args, $param ) { 2914 $is_valid_number = rest_validate_number_value_from_schema( $value, $args, $param ); 2915 if ( is_wp_error( $is_valid_number ) ) { 2916 return $is_valid_number; 2917 } 2918 2919 if ( ! rest_is_integer( $value ) ) { 2920 return new WP_Error( 2921 'rest_invalid_type', 2922 /* translators: 1: Parameter, 2: Type name. */ 2923 sprintf( __( '%1$s is not of type %2$s.' ), $param, 'integer' ), 2924 array( 'param' => $param ) 2925 ); 2926 } 2927 2928 return true; 2929 } 2930 2931 /** 2932 * Sanitize a value based on a schema. 2933 * 2934 * @since 4.7.0 2935 * @since 5.5.0 Added the `$param` parameter. 2936 * @since 5.6.0 Support the "anyOf" and "oneOf" keywords. 2937 * @since 5.9.0 Added `text-field` and `textarea-field` formats. 2938 * 2939 * @param mixed $value The value to sanitize. 2940 * @param array $args Schema array to use for sanitization. 2941 * @param string $param The parameter name, used in error messages. 2942 * @return mixed|WP_Error The sanitized value or a WP_Error instance if the value cannot be safely sanitized. 2943 */ 2944 function rest_sanitize_value_from_schema( $value, $args, $param = '' ) { 2945 if ( isset( $args['anyOf'] ) ) { 2946 $matching_schema = rest_find_any_matching_schema( $value, $args, $param ); 2947 if ( is_wp_error( $matching_schema ) ) { 2948 return $matching_schema; 2949 } 2950 2951 if ( ! isset( $args['type'] ) ) { 2952 $args['type'] = $matching_schema['type']; 2953 } 2954 2955 $value = rest_sanitize_value_from_schema( $value, $matching_schema, $param ); 2956 } 2957 2958 if ( isset( $args['oneOf'] ) ) { 2959 $matching_schema = rest_find_one_matching_schema( $value, $args, $param ); 2960 if ( is_wp_error( $matching_schema ) ) { 2961 return $matching_schema; 2962 } 2963 2964 if ( ! isset( $args['type'] ) ) { 2965 $args['type'] = $matching_schema['type']; 2966 } 2967 2968 $value = rest_sanitize_value_from_schema( $value, $matching_schema, $param ); 2969 } 2970 2971 $allowed_types = array( 'array', 'object', 'string', 'number', 'integer', 'boolean', 'null' ); 2972 2973 if ( ! isset( $args['type'] ) ) { 2974 /* translators: %s: Parameter. */ 2975 _doing_it_wrong( __FUNCTION__, sprintf( __( 'The "type" schema keyword for %s is required.' ), $param ), '5.5.0' ); 2976 } 2977 2978 if ( is_array( $args['type'] ) ) { 2979 $best_type = rest_handle_multi_type_schema( $value, $args, $param ); 2980 2981 if ( ! $best_type ) { 2982 return null; 2983 } 2984 2985 $args['type'] = $best_type; 2986 } 2987 2988 if ( ! in_array( $args['type'], $allowed_types, true ) ) { 2989 _doing_it_wrong( 2990 __FUNCTION__, 2991 /* translators: 1: Parameter, 2: The list of allowed types. */ 2992 wp_sprintf( __( 'The "type" schema keyword for %1$s can only be one of the built-in types: %2$l.' ), $param, $allowed_types ), 2993 '5.5.0' 2994 ); 2995 } 2996 2997 if ( 'array' === $args['type'] ) { 2998 $value = rest_sanitize_array( $value ); 2999 3000 if ( ! empty( $args['items'] ) ) { 3001 foreach ( $value as $index => $v ) { 3002 $value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' ); 3003 } 3004 } 3005 3006 if ( ! empty( $args['uniqueItems'] ) && ! rest_validate_array_contains_unique_items( $value ) ) { 3007 /* translators: %s: Parameter. */ 3008 return new WP_Error( 'rest_duplicate_items', sprintf( __( '%s has duplicate items.' ), $param ) ); 3009 } 3010 3011 return $value; 3012 } 3013 3014 if ( 'object' === $args['type'] ) { 3015 $value = rest_sanitize_object( $value ); 3016 3017 foreach ( $value as $property => $v ) { 3018 if ( isset( $args['properties'][ $property ] ) ) { 3019 $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' ); 3020 continue; 3021 } 3022 3023 $pattern_property_schema = rest_find_matching_pattern_property_schema( $property, $args ); 3024 if ( null !== $pattern_property_schema ) { 3025 $value[ $property ] = rest_sanitize_value_from_schema( $v, $pattern_property_schema, $param . '[' . $property . ']' ); 3026 continue; 3027 } 3028 3029 if ( isset( $args['additionalProperties'] ) ) { 3030 if ( false === $args['additionalProperties'] ) { 3031 unset( $value[ $property ] ); 3032 } elseif ( is_array( $args['additionalProperties'] ) ) { 3033 $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['additionalProperties'], $param . '[' . $property . ']' ); 3034 } 3035 } 3036 } 3037 3038 return $value; 3039 } 3040 3041 if ( 'null' === $args['type'] ) { 3042 return null; 3043 } 3044 3045 if ( 'integer' === $args['type'] ) { 3046 return (int) $value; 3047 } 3048 3049 if ( 'number' === $args['type'] ) { 3050 return (float) $value; 3051 } 3052 3053 if ( 'boolean' === $args['type'] ) { 3054 return rest_sanitize_boolean( $value ); 3055 } 3056 3057 // This behavior matches rest_validate_value_from_schema(). 3058 if ( isset( $args['format'] ) 3059 && ( ! isset( $args['type'] ) || 'string' === $args['type'] || ! in_array( $args['type'], $allowed_types, true ) ) 3060 ) { 3061 switch ( $args['format'] ) { 3062 case 'hex-color': 3063 return (string) sanitize_hex_color( $value ); 3064 3065 case 'date-time': 3066 return sanitize_text_field( $value ); 3067 3068 case 'email': 3069 // sanitize_email() validates, which would be unexpected. 3070 return sanitize_text_field( $value ); 3071 3072 case 'uri': 3073 return sanitize_url( $value ); 3074 3075 case 'ip': 3076 return sanitize_text_field( $value ); 3077 3078 case 'uuid': 3079 return sanitize_text_field( $value ); 3080 3081 case 'text-field': 3082 return sanitize_text_field( $value ); 3083 3084 case 'textarea-field': 3085 return sanitize_textarea_field( $value ); 3086 } 3087 } 3088 3089 if ( 'string' === $args['type'] ) { 3090 return (string) $value; 3091 } 3092 3093 return $value; 3094 } 3095 3096 /** 3097 * Append result of internal request to REST API for purpose of preloading data to be attached to a page. 3098 * Expected to be called in the context of `array_reduce`. 3099 * 3100 * @since 5.0.0 3101 * 3102 * @param array $memo Reduce accumulator. 3103 * @param string $path REST API path to preload. 3104 * @return array Modified reduce accumulator. 3105 */ 3106 function rest_preload_api_request( $memo, $path ) { 3107 /* 3108 * array_reduce() doesn't support passing an array in PHP 5.2, 3109 * so we need to make sure we start with one. 3110 */ 3111 if ( ! is_array( $memo ) ) { 3112 $memo = array(); 3113 } 3114 3115 if ( empty( $path ) ) { 3116 return $memo; 3117 } 3118 3119 $method = 'GET'; 3120 if ( is_array( $path ) && 2 === count( $path ) ) { 3121 $method = end( $path ); 3122 $path = reset( $path ); 3123 3124 if ( ! in_array( $method, array( 'GET', 'OPTIONS' ), true ) ) { 3125 $method = 'GET'; 3126 } 3127 } 3128 3129 // Remove trailing slashes at the end of the REST API path (query part). 3130 $path = untrailingslashit( $path ); 3131 if ( empty( $path ) ) { 3132 $path = '/'; 3133 } 3134 3135 $path_parts = parse_url( $path ); 3136 if ( false === $path_parts ) { 3137 return $memo; 3138 } 3139 3140 if ( isset( $path_parts['path'] ) && '/' !== $path_parts['path'] ) { 3141 // Remove trailing slashes from the "path" part of the REST API path. 3142 $path_parts['path'] = untrailingslashit( $path_parts['path'] ); 3143 $path = str_contains( $path, '?' ) ? 3144 $path_parts['path'] . '?' . ( $path_parts['query'] ?? '' ) : 3145 $path_parts['path']; 3146 } 3147 3148 $request = new WP_REST_Request( $method, $path_parts['path'] ); 3149 if ( ! empty( $path_parts['query'] ) ) { 3150 parse_str( $path_parts['query'], $query_params ); 3151 $request->set_query_params( $query_params ); 3152 } 3153 3154 $response = rest_do_request( $request ); 3155 if ( 200 === $response->status ) { 3156 $server = rest_get_server(); 3157 /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ 3158 $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $server, $request ); 3159 $embed = $request->has_param( '_embed' ) ? rest_parse_embed_param( $request['_embed'] ) : false; 3160 $data = $server->response_to_data( $response, $embed ); 3161 3162 if ( 'OPTIONS' === $method ) { 3163 $memo[ $method ][ $path ] = array( 3164 'body' => $data, 3165 'headers' => $response->headers, 3166 ); 3167 } else { 3168 $memo[ $path ] = array( 3169 'body' => $data, 3170 'headers' => $response->headers, 3171 ); 3172 } 3173 } 3174 3175 return $memo; 3176 } 3177 3178 /** 3179 * Parses the "_embed" parameter into the list of resources to embed. 3180 * 3181 * @since 5.4.0 3182 * 3183 * @param string|array $embed Raw "_embed" parameter value. 3184 * @return true|string[] Either true to embed all embeds, or a list of relations to embed. 3185 */ 3186 function rest_parse_embed_param( $embed ) { 3187 if ( ! $embed || 'true' === $embed || '1' === $embed ) { 3188 return true; 3189 } 3190 3191 $rels = wp_parse_list( $embed ); 3192 3193 if ( ! $rels ) { 3194 return true; 3195 } 3196 3197 return $rels; 3198 } 3199 3200 /** 3201 * Filters the response to remove any fields not available in the given context. 3202 * 3203 * @since 5.5.0 3204 * @since 5.6.0 Support the "patternProperties" keyword for objects. 3205 * Support the "anyOf" and "oneOf" keywords. 3206 * 3207 * @param array|object $response_data The response data to modify. 3208 * @param array $schema The schema for the endpoint used to filter the response. 3209 * @param string $context The requested context. 3210 * @return array|object The filtered response data. 3211 */ 3212 function rest_filter_response_by_context( $response_data, $schema, $context ) { 3213 if ( isset( $schema['anyOf'] ) ) { 3214 $matching_schema = rest_find_any_matching_schema( $response_data, $schema, '' ); 3215 if ( ! is_wp_error( $matching_schema ) ) { 3216 if ( ! isset( $schema['type'] ) ) { 3217 $schema['type'] = $matching_schema['type']; 3218 } 3219 3220 $response_data = rest_filter_response_by_context( $response_data, $matching_schema, $context ); 3221 } 3222 } 3223 3224 if ( isset( $schema['oneOf'] ) ) { 3225 $matching_schema = rest_find_one_matching_schema( $response_data, $schema, '', true ); 3226 if ( ! is_wp_error( $matching_schema ) ) { 3227 if ( ! isset( $schema['type'] ) ) { 3228 $schema['type'] = $matching_schema['type']; 3229 } 3230 3231 $response_data = rest_filter_response_by_context( $response_data, $matching_schema, $context ); 3232 } 3233 } 3234 3235 if ( ! is_array( $response_data ) && ! is_object( $response_data ) ) { 3236 return $response_data; 3237 } 3238 3239 if ( isset( $schema['type'] ) ) { 3240 $type = $schema['type']; 3241 } elseif ( isset( $schema['properties'] ) ) { 3242 $type = 'object'; // Back compat if a developer accidentally omitted the type. 3243 } else { 3244 return $response_data; 3245 } 3246 3247 $is_array_type = 'array' === $type || ( is_array( $type ) && in_array( 'array', $type, true ) ); 3248 $is_object_type = 'object' === $type || ( is_array( $type ) && in_array( 'object', $type, true ) ); 3249 3250 if ( $is_array_type && $is_object_type ) { 3251 if ( rest_is_array( $response_data ) ) { 3252 $is_object_type = false; 3253 } else { 3254 $is_array_type = false; 3255 } 3256 } 3257 3258 $has_additional_properties = $is_object_type && isset( $schema['additionalProperties'] ) && is_array( $schema['additionalProperties'] ); 3259 3260 foreach ( $response_data as $key => $value ) { 3261 $check = array(); 3262 3263 if ( $is_array_type ) { 3264 $check = $schema['items'] ?? array(); 3265 } elseif ( $is_object_type ) { 3266 if ( isset( $schema['properties'][ $key ] ) ) { 3267 $check = $schema['properties'][ $key ]; 3268 } else { 3269 $pattern_property_schema = rest_find_matching_pattern_property_schema( $key, $schema ); 3270 if ( null !== $pattern_property_schema ) { 3271 $check = $pattern_property_schema; 3272 } elseif ( $has_additional_properties ) { 3273 $check = $schema['additionalProperties']; 3274 } 3275 } 3276 } 3277 3278 if ( ! isset( $check['context'] ) ) { 3279 continue; 3280 } 3281 3282 if ( ! in_array( $context, $check['context'], true ) ) { 3283 if ( $is_array_type ) { 3284 // All array items share schema, so there's no need to check each one. 3285 $response_data = array(); 3286 break; 3287 } 3288 3289 if ( is_object( $response_data ) ) { 3290 unset( $response_data->$key ); 3291 } else { 3292 unset( $response_data[ $key ] ); 3293 } 3294 } elseif ( is_array( $value ) || is_object( $value ) ) { 3295 $new_value = rest_filter_response_by_context( $value, $check, $context ); 3296 3297 if ( is_object( $response_data ) ) { 3298 $response_data->$key = $new_value; 3299 } else { 3300 $response_data[ $key ] = $new_value; 3301 } 3302 } 3303 } 3304 3305 return $response_data; 3306 } 3307 3308 /** 3309 * Sets the "additionalProperties" to false by default for all object definitions in the schema. 3310 * 3311 * @since 5.5.0 3312 * @since 5.6.0 Support the "patternProperties" keyword. 3313 * 3314 * @param array $schema The schema to modify. 3315 * @return array The modified schema. 3316 */ 3317 function rest_default_additional_properties_to_false( $schema ) { 3318 $type = (array) $schema['type']; 3319 3320 if ( in_array( 'object', $type, true ) ) { 3321 if ( isset( $schema['properties'] ) ) { 3322 foreach ( $schema['properties'] as $key => $child_schema ) { 3323 $schema['properties'][ $key ] = rest_default_additional_properties_to_false( $child_schema ); 3324 } 3325 } 3326 3327 if ( isset( $schema['patternProperties'] ) ) { 3328 foreach ( $schema['patternProperties'] as $key => $child_schema ) { 3329 $schema['patternProperties'][ $key ] = rest_default_additional_properties_to_false( $child_schema ); 3330 } 3331 } 3332 3333 if ( ! isset( $schema['additionalProperties'] ) ) { 3334 $schema['additionalProperties'] = false; 3335 } 3336 } 3337 3338 if ( in_array( 'array', $type, true ) ) { 3339 if ( isset( $schema['items'] ) ) { 3340 $schema['items'] = rest_default_additional_properties_to_false( $schema['items'] ); 3341 } 3342 } 3343 3344 return $schema; 3345 } 3346 3347 /** 3348 * Gets the REST API route for a post. 3349 * 3350 * @since 5.5.0 3351 * 3352 * @param int|WP_Post $post Post ID or post object. 3353 * @return string The route path with a leading slash for the given post, 3354 * or an empty string if there is not a route. 3355 */ 3356 function rest_get_route_for_post( $post ) { 3357 $post = get_post( $post ); 3358 3359 if ( ! $post instanceof WP_Post ) { 3360 return ''; 3361 } 3362 3363 $post_type_route = rest_get_route_for_post_type_items( $post->post_type ); 3364 if ( ! $post_type_route ) { 3365 return ''; 3366 } 3367 3368 $route = sprintf( '%s/%d', $post_type_route, $post->ID ); 3369 3370 /** 3371 * Filters the REST API route for a post. 3372 * 3373 * @since 5.5.0 3374 * 3375 * @param string $route The route path. 3376 * @param WP_Post $post The post object. 3377 */ 3378 return apply_filters( 'rest_route_for_post', $route, $post ); 3379 } 3380 3381 /** 3382 * Gets the REST API route for a post type. 3383 * 3384 * @since 5.9.0 3385 * 3386 * @param string $post_type The name of a registered post type. 3387 * @return string The route path with a leading slash for the given post type, 3388 * or an empty string if there is not a route. 3389 */ 3390 function rest_get_route_for_post_type_items( $post_type ) { 3391 $post_type = get_post_type_object( $post_type ); 3392 if ( ! $post_type ) { 3393 return ''; 3394 } 3395 3396 if ( ! $post_type->show_in_rest ) { 3397 return ''; 3398 } 3399 3400 $namespace = ! empty( $post_type->rest_namespace ) ? $post_type->rest_namespace : 'wp/v2'; 3401 $rest_base = ! empty( $post_type->rest_base ) ? $post_type->rest_base : $post_type->name; 3402 $route = sprintf( '/%s/%s', $namespace, $rest_base ); 3403 3404 /** 3405 * Filters the REST API route for a post type. 3406 * 3407 * @since 5.9.0 3408 * 3409 * @param string $route The route path. 3410 * @param WP_Post_Type $post_type The post type object. 3411 */ 3412 return apply_filters( 'rest_route_for_post_type_items', $route, $post_type ); 3413 } 3414 3415 /** 3416 * Gets the REST API route for a term. 3417 * 3418 * @since 5.5.0 3419 * 3420 * @param int|WP_Term $term Term ID or term object. 3421 * @return string The route path with a leading slash for the given term, 3422 * or an empty string if there is not a route. 3423 */ 3424 function rest_get_route_for_term( $term ) { 3425 $term = get_term( $term ); 3426 3427 if ( ! $term instanceof WP_Term ) { 3428 return ''; 3429 } 3430 3431 $taxonomy_route = rest_get_route_for_taxonomy_items( $term->taxonomy ); 3432 if ( ! $taxonomy_route ) { 3433 return ''; 3434 } 3435 3436 $route = sprintf( '%s/%d', $taxonomy_route, $term->term_id ); 3437 3438 /** 3439 * Filters the REST API route for a term. 3440 * 3441 * @since 5.5.0 3442 * 3443 * @param string $route The route path. 3444 * @param WP_Term $term The term object. 3445 */ 3446 return apply_filters( 'rest_route_for_term', $route, $term ); 3447 } 3448 3449 /** 3450 * Gets the REST API route for a taxonomy. 3451 * 3452 * @since 5.9.0 3453 * 3454 * @param string $taxonomy Name of taxonomy. 3455 * @return string The route path with a leading slash for the given taxonomy. 3456 */ 3457 function rest_get_route_for_taxonomy_items( $taxonomy ) { 3458 $taxonomy = get_taxonomy( $taxonomy ); 3459 if ( ! $taxonomy ) { 3460 return ''; 3461 } 3462 3463 if ( ! $taxonomy->show_in_rest ) { 3464 return ''; 3465 } 3466 3467 $namespace = ! empty( $taxonomy->rest_namespace ) ? $taxonomy->rest_namespace : 'wp/v2'; 3468 $rest_base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; 3469 $route = sprintf( '/%s/%s', $namespace, $rest_base ); 3470 3471 /** 3472 * Filters the REST API route for a taxonomy. 3473 * 3474 * @since 5.9.0 3475 * 3476 * @param string $route The route path. 3477 * @param WP_Taxonomy $taxonomy The taxonomy object. 3478 */ 3479 return apply_filters( 'rest_route_for_taxonomy_items', $route, $taxonomy ); 3480 } 3481 3482 /** 3483 * Gets the REST route for the currently queried object. 3484 * 3485 * @since 5.5.0 3486 * 3487 * @return string The REST route of the resource, or an empty string if no resource identified. 3488 */ 3489 function rest_get_queried_resource_route() { 3490 if ( is_singular() ) { 3491 $route = rest_get_route_for_post( get_queried_object() ); 3492 } elseif ( is_category() || is_tag() || is_tax() ) { 3493 $route = rest_get_route_for_term( get_queried_object() ); 3494 } elseif ( is_author() ) { 3495 $route = '/wp/v2/users/' . get_queried_object_id(); 3496 } else { 3497 $route = ''; 3498 } 3499 3500 /** 3501 * Filters the REST route for the currently queried object. 3502 * 3503 * @since 5.5.0 3504 * 3505 * @param string $link The route with a leading slash, or an empty string. 3506 */ 3507 return apply_filters( 'rest_queried_resource_route', $route ); 3508 } 3509 3510 /** 3511 * Retrieves an array of endpoint arguments from the item schema and endpoint method. 3512 * 3513 * @since 5.6.0 3514 * 3515 * @param array $schema The full JSON schema for the endpoint. 3516 * @param string $method Optional. HTTP method of the endpoint. The arguments for `CREATABLE` endpoints are 3517 * checked for required values and may fall-back to a given default, this is not done 3518 * on `EDITABLE` endpoints. Default WP_REST_Server::CREATABLE. 3519 * @return array The endpoint arguments. 3520 */ 3521 function rest_get_endpoint_args_for_schema( $schema, $method = WP_REST_Server::CREATABLE ) { 3522 3523 $schema_properties = ! empty( $schema['properties'] ) ? $schema['properties'] : array(); 3524 $endpoint_args = array(); 3525 $valid_schema_properties = rest_get_allowed_schema_keywords(); 3526 $valid_schema_properties = array_diff( $valid_schema_properties, array( 'default', 'required' ) ); 3527 3528 foreach ( $schema_properties as $field_id => $params ) { 3529 3530 // Arguments specified as `readonly` are not allowed to be set. 3531 if ( ! empty( $params['readonly'] ) ) { 3532 continue; 3533 } 3534 3535 $endpoint_args[ $field_id ] = array( 3536 'validate_callback' => 'rest_validate_request_arg', 3537 'sanitize_callback' => 'rest_sanitize_request_arg', 3538 ); 3539 3540 if ( WP_REST_Server::CREATABLE === $method && isset( $params['default'] ) ) { 3541 $endpoint_args[ $field_id ]['default'] = $params['default']; 3542 } 3543 3544 if ( WP_REST_Server::CREATABLE === $method && ! empty( $params['required'] ) ) { 3545 $endpoint_args[ $field_id ]['required'] = true; 3546 } 3547 3548 foreach ( $valid_schema_properties as $schema_prop ) { 3549 if ( isset( $params[ $schema_prop ] ) ) { 3550 $endpoint_args[ $field_id ][ $schema_prop ] = $params[ $schema_prop ]; 3551 } 3552 } 3553 3554 // Merge in any options provided by the schema property. 3555 if ( isset( $params['arg_options'] ) ) { 3556 3557 // Only use required / default from arg_options on CREATABLE endpoints. 3558 if ( WP_REST_Server::CREATABLE !== $method ) { 3559 $params['arg_options'] = array_diff_key( 3560 $params['arg_options'], 3561 array( 3562 'required' => '', 3563 'default' => '', 3564 ) 3565 ); 3566 } 3567 3568 $endpoint_args[ $field_id ] = array_merge( $endpoint_args[ $field_id ], $params['arg_options'] ); 3569 } 3570 } 3571 3572 return $endpoint_args; 3573 } 3574 3575 /** 3576 * Prevents users without the `manage_privacy_options` capability from 3577 * changing the privacy policy page through the REST API. 3578 * 3579 * The settings endpoint only checks `manage_options`. On multisite the 3580 * `manage_privacy_options` capability maps to `manage_network`, so a site 3581 * administrator can read the setting but must not change it, matching the 3582 * Settings > Privacy screen. 3583 * 3584 * @since 7.2.0 3585 * 3586 * @param bool $updated Whether the setting update has already been handled. 3587 * @param string $name Setting name (as shown in REST API responses). 3588 * @return bool Whether to short-circuit the update. 3589 */ 3590 function rest_restrict_privacy_policy_page_setting_update( $updated, $name ) { 3591 if ( 'page_for_privacy_policy' === $name && ! current_user_can( 'manage_privacy_options' ) ) { 3592 return true; 3593 } 3594 return $updated; 3595 } 3596 3597 /** 3598 * Converts an error to a response object. 3599 * 3600 * This iterates over all error codes and messages to change it into a flat 3601 * array. This enables simpler client behavior, as it is represented as a 3602 * list in JSON rather than an object/map. 3603 * 3604 * @since 5.7.0 3605 * 3606 * @param WP_Error $error WP_Error instance. 3607 * @return WP_REST_Response List of associative arrays with code and message keys. 3608 */ 3609 function rest_convert_error_to_response( $error ) { 3610 $status = array_reduce( 3611 $error->get_all_error_data(), 3612 /** 3613 * @param int $status Status. 3614 * @param mixed $error_data Error data. 3615 */ 3616 static function ( int $status, $error_data ): int { 3617 if ( is_array( $error_data ) && isset( $error_data['status'] ) && is_numeric( $error_data['status'] ) ) { 3618 $status = (int) $error_data['status']; 3619 } 3620 return $status; 3621 }, 3622 500 3623 ); 3624 3625 $errors = array(); 3626 3627 foreach ( (array) $error->errors as $code => $messages ) { 3628 $all_data = $error->get_all_error_data( $code ); 3629 $last_data = array_pop( $all_data ); 3630 3631 foreach ( (array) $messages as $message ) { 3632 $formatted = array( 3633 'code' => $code, 3634 'message' => $message, 3635 'data' => $last_data, 3636 ); 3637 3638 if ( $all_data ) { 3639 $formatted['additional_data'] = $all_data; 3640 } 3641 3642 $errors[] = $formatted; 3643 } 3644 } 3645 3646 $data = $errors[0]; 3647 if ( count( $errors ) > 1 ) { 3648 // Remove the primary error. 3649 array_shift( $errors ); 3650 $data['additional_errors'] = $errors; 3651 } 3652 3653 return new WP_REST_Response( $data, $status ); 3654 } 3655 3656 /** 3657 * Checks whether a REST API endpoint request is currently being handled. 3658 * 3659 * This may be a standalone REST API request, or an internal request dispatched from within a regular page load. 3660 * 3661 * @since 6.5.0 3662 * 3663 * @global WP_REST_Server $wp_rest_server REST server instance. 3664 * 3665 * @return bool True if a REST endpoint request is currently being handled, false otherwise. 3666 */ 3667 function wp_is_rest_endpoint() { 3668 /* @var WP_REST_Server $wp_rest_server */ 3669 global $wp_rest_server; 3670 3671 // Check whether this is a standalone REST request. 3672 $is_rest_endpoint = wp_is_serving_rest_request(); 3673 if ( ! $is_rest_endpoint ) { 3674 // Otherwise, check whether an internal REST request is currently being handled. 3675 $is_rest_endpoint = isset( $wp_rest_server ) 3676 && $wp_rest_server->is_dispatching(); 3677 } 3678 3679 /** 3680 * Filters whether a REST endpoint request is currently being handled. 3681 * 3682 * This may be a standalone REST API request, or an internal request dispatched from within a regular page load. 3683 * 3684 * @since 6.5.0 3685 * 3686 * @param bool $is_request_endpoint Whether a REST endpoint request is currently being handled. 3687 */ 3688 return (bool) apply_filters( 'wp_is_rest_endpoint', $is_rest_endpoint ); 3689 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Wed Dec 2 08:20:02 2026 | Cross-referenced by PHPXref |