[ Index ]

WordPress 5.4.1

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

title

Body

[close]

/wp-includes/ -> rest-api.php (source)

   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   * @var string
  14   */
  15  define( 'REST_API_VERSION', '2.0' );
  16  
  17  /**
  18   * Registers a REST API route.
  19   *
  20   * Note: Do not use before the {@see 'rest_api_init'} hook.
  21   *
  22   * @since 4.4.0
  23   * @since 5.1.0 Added a _doing_it_wrong() notice when not called on or after the rest_api_init hook.
  24   *
  25   * @param string $namespace The first URL segment after core prefix. Should be unique to your package/plugin.
  26   * @param string $route     The base URL for route you are adding.
  27   * @param array  $args      Optional. Either an array of options for the endpoint, or an array of arrays for
  28   *                          multiple methods. Default empty array.
  29   * @param bool   $override  Optional. If the route already exists, should we override it? True overrides,
  30   *                          false merges (with newer overriding if duplicate keys exist). Default false.
  31   * @return bool True on success, false on error.
  32   */
  33  function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
  34      if ( empty( $namespace ) ) {
  35          /*
  36           * Non-namespaced routes are not allowed, with the exception of the main
  37           * and namespace indexes. If you really need to register a
  38           * non-namespaced route, call `WP_REST_Server::register_route` directly.
  39           */
  40          _doing_it_wrong( 'register_rest_route', __( 'Routes must be namespaced with plugin or theme name and version.' ), '4.4.0' );
  41          return false;
  42      } elseif ( empty( $route ) ) {
  43          _doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
  44          return false;
  45      }
  46  
  47      if ( ! did_action( 'rest_api_init' ) ) {
  48          _doing_it_wrong(
  49              'register_rest_route',
  50              sprintf(
  51                  /* translators: %s: rest_api_init */
  52                  __( 'REST API routes must be registered on the %s action.' ),
  53                  '<code>rest_api_init</code>'
  54              ),
  55              '5.1.0'
  56          );
  57      }
  58  
  59      if ( isset( $args['args'] ) ) {
  60          $common_args = $args['args'];
  61          unset( $args['args'] );
  62      } else {
  63          $common_args = array();
  64      }
  65  
  66      if ( isset( $args['callback'] ) ) {
  67          // Upgrade a single set to multiple.
  68          $args = array( $args );
  69      }
  70  
  71      $defaults = array(
  72          'methods'  => 'GET',
  73          'callback' => null,
  74          'args'     => array(),
  75      );
  76  
  77      foreach ( $args as $key => &$arg_group ) {
  78          if ( ! is_numeric( $key ) ) {
  79              // Route option, skip here.
  80              continue;
  81          }
  82  
  83          $arg_group         = array_merge( $defaults, $arg_group );
  84          $arg_group['args'] = array_merge( $common_args, $arg_group['args'] );
  85      }
  86  
  87      $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
  88      rest_get_server()->register_route( $namespace, $full_route, $args, $override );
  89      return true;
  90  }
  91  
  92  /**
  93   * Registers a new field on an existing WordPress object type.
  94   *
  95   * @since 4.7.0
  96   *
  97   * @global array $wp_rest_additional_fields Holds registered fields, organized
  98   *                                          by object type.
  99   *
 100   * @param string|array $object_type Object(s) the field is being registered
 101   *                                  to, "post"|"term"|"comment" etc.
 102   * @param string $attribute         The attribute name.
 103   * @param array  $args {
 104   *     Optional. An array of arguments used to handle the registered field.
 105   *
 106   *     @type callable|null $get_callback    Optional. The callback function used to retrieve the field value. Default is
 107   *                                          'null', the field will not be returned in the response. The function will
 108   *                                          be passed the prepared object data.
 109   *     @type callable|null $update_callback Optional. The callback function used to set and update the field value. Default
 110   *                                          is 'null', the value cannot be set or updated. The function will be passed
 111   *                                          the model object, like WP_Post.
 112   *     @type array|null $schema             Optional. The callback function used to create the schema for this field.
 113   *                                          Default is 'null', no schema entry will be returned.
 114   * }
 115   */
 116  function register_rest_field( $object_type, $attribute, $args = array() ) {
 117      $defaults = array(
 118          'get_callback'    => null,
 119          'update_callback' => null,
 120          'schema'          => null,
 121      );
 122  
 123      $args = wp_parse_args( $args, $defaults );
 124  
 125      global $wp_rest_additional_fields;
 126  
 127      $object_types = (array) $object_type;
 128  
 129      foreach ( $object_types as $object_type ) {
 130          $wp_rest_additional_fields[ $object_type ][ $attribute ] = $args;
 131      }
 132  }
 133  
 134  /**
 135   * Registers rewrite rules for the API.
 136   *
 137   * @since 4.4.0
 138   *
 139   * @see rest_api_register_rewrites()
 140   * @global WP $wp Current WordPress environment instance.
 141   */
 142  function rest_api_init() {
 143      rest_api_register_rewrites();
 144  
 145      global $wp;
 146      $wp->add_query_var( 'rest_route' );
 147  }
 148  
 149  /**
 150   * Adds REST rewrite rules.
 151   *
 152   * @since 4.4.0
 153   *
 154   * @see add_rewrite_rule()
 155   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 156   */
 157  function rest_api_register_rewrites() {
 158      global $wp_rewrite;
 159  
 160      add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' );
 161      add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' );
 162      add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' );
 163      add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' );
 164  }
 165  
 166  /**
 167   * Registers the default REST API filters.
 168   *
 169   * Attached to the {@see 'rest_api_init'} action
 170   * to make testing and disabling these filters easier.
 171   *
 172   * @since 4.4.0
 173   */
 174  function rest_api_default_filters() {
 175      // Deprecated reporting.
 176      add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 );
 177      add_filter( 'deprecated_function_trigger_error', '__return_false' );
 178      add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 );
 179      add_filter( 'deprecated_argument_trigger_error', '__return_false' );
 180  
 181      // Default serving.
 182      add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
 183      add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
 184      add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
 185  
 186      add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );
 187  }
 188  
 189  /**
 190   * Registers default REST API routes.
 191   *
 192   * @since 4.7.0
 193   */
 194  function create_initial_rest_routes() {
 195      foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
 196          $controller = $post_type->get_rest_controller();
 197  
 198          if ( ! $controller ) {
 199              continue;
 200          }
 201  
 202          $controller->register_routes();
 203  
 204          if ( post_type_supports( $post_type->name, 'revisions' ) ) {
 205              $revisions_controller = new WP_REST_Revisions_Controller( $post_type->name );
 206              $revisions_controller->register_routes();
 207          }
 208  
 209          if ( 'attachment' !== $post_type->name ) {
 210              $autosaves_controller = new WP_REST_Autosaves_Controller( $post_type->name );
 211              $autosaves_controller->register_routes();
 212          }
 213      }
 214  
 215      // Post types.
 216      $controller = new WP_REST_Post_Types_Controller;
 217      $controller->register_routes();
 218  
 219      // Post statuses.
 220      $controller = new WP_REST_Post_Statuses_Controller;
 221      $controller->register_routes();
 222  
 223      // Taxonomies.
 224      $controller = new WP_REST_Taxonomies_Controller;
 225      $controller->register_routes();
 226  
 227      // Terms.
 228      foreach ( get_taxonomies( array( 'show_in_rest' => true ), 'object' ) as $taxonomy ) {
 229          $class = ! empty( $taxonomy->rest_controller_class ) ? $taxonomy->rest_controller_class : 'WP_REST_Terms_Controller';
 230  
 231          if ( ! class_exists( $class ) ) {
 232              continue;
 233          }
 234          $controller = new $class( $taxonomy->name );
 235          if ( ! is_subclass_of( $controller, 'WP_REST_Controller' ) ) {
 236              continue;
 237          }
 238  
 239          $controller->register_routes();
 240      }
 241  
 242      // Users.
 243      $controller = new WP_REST_Users_Controller;
 244      $controller->register_routes();
 245  
 246      // Comments.
 247      $controller = new WP_REST_Comments_Controller;
 248      $controller->register_routes();
 249  
 250      /**
 251       * Filters the search handlers to use in the REST search controller.
 252       *
 253       * @since 5.0.0
 254       *
 255       * @param array $search_handlers List of search handlers to use in the controller. Each search
 256       *                               handler instance must extend the `WP_REST_Search_Handler` class.
 257       *                               Default is only a handler for posts.
 258       */
 259      $search_handlers = apply_filters( 'wp_rest_search_handlers', array( new WP_REST_Post_Search_Handler() ) );
 260  
 261      $controller = new WP_REST_Search_Controller( $search_handlers );
 262      $controller->register_routes();
 263  
 264      // Block Renderer.
 265      $controller = new WP_REST_Block_Renderer_Controller;
 266      $controller->register_routes();
 267  
 268      // Settings.
 269      $controller = new WP_REST_Settings_Controller;
 270      $controller->register_routes();
 271  
 272      // Themes.
 273      $controller = new WP_REST_Themes_Controller;
 274      $controller->register_routes();
 275  
 276  }
 277  
 278  /**
 279   * Loads the REST API.
 280   *
 281   * @since 4.4.0
 282   *
 283   * @global WP $wp Current WordPress environment instance.
 284   */
 285  function rest_api_loaded() {
 286      if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
 287          return;
 288      }
 289  
 290      /**
 291       * Whether this is a REST Request.
 292       *
 293       * @since 4.4.0
 294       * @var bool
 295       */
 296      define( 'REST_REQUEST', true );
 297  
 298      // Initialize the server.
 299      $server = rest_get_server();
 300  
 301      // Fire off the request.
 302      $route = untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] );
 303      if ( empty( $route ) ) {
 304          $route = '/';
 305      }
 306      $server->serve_request( $route );
 307  
 308      // We're done.
 309      die();
 310  }
 311  
 312  /**
 313   * Retrieves the URL prefix for any API resource.
 314   *
 315   * @since 4.4.0
 316   *
 317   * @return string Prefix.
 318   */
 319  function rest_get_url_prefix() {
 320      /**
 321       * Filters the REST URL prefix.
 322       *
 323       * @since 4.4.0
 324       *
 325       * @param string $prefix URL prefix. Default 'wp-json'.
 326       */
 327      return apply_filters( 'rest_url_prefix', 'wp-json' );
 328  }
 329  
 330  /**
 331   * Retrieves the URL to a REST endpoint on a site.
 332   *
 333   * Note: The returned URL is NOT escaped.
 334   *
 335   * @since 4.4.0
 336   *
 337   * @todo Check if this is even necessary
 338   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 339   *
 340   * @param int    $blog_id Optional. Blog ID. Default of null returns URL for current blog.
 341   * @param string $path    Optional. REST route. Default '/'.
 342   * @param string $scheme  Optional. Sanitization scheme. Default 'rest'.
 343   * @return string Full URL to the endpoint.
 344   */
 345  function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
 346      if ( empty( $path ) ) {
 347          $path = '/';
 348      }
 349  
 350      $path = '/' . ltrim( $path, '/' );
 351  
 352      if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
 353          global $wp_rewrite;
 354  
 355          if ( $wp_rewrite->using_index_permalinks() ) {
 356              $url = get_home_url( $blog_id, $wp_rewrite->index . '/' . rest_get_url_prefix(), $scheme );
 357          } else {
 358              $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
 359          }
 360  
 361          $url .= $path;
 362      } else {
 363          $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
 364          // nginx only allows HTTP/1.0 methods when redirecting from / to /index.php.
 365          // To work around this, we manually add index.php to the URL, avoiding the redirect.
 366          if ( 'index.php' !== substr( $url, 9 ) ) {
 367              $url .= 'index.php';
 368          }
 369  
 370          $url = add_query_arg( 'rest_route', $path, $url );
 371      }
 372  
 373      if ( is_ssl() && isset( $_SERVER['SERVER_NAME'] ) ) {
 374          // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
 375          if ( parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) === $_SERVER['SERVER_NAME'] ) {
 376              $url = set_url_scheme( $url, 'https' );
 377          }
 378      }
 379  
 380      if ( is_admin() && force_ssl_admin() ) {
 381          /*
 382           * In this situation the home URL may be http:, and `is_ssl()` may be false,
 383           * but the admin is served over https: (one way or another), so REST API usage
 384           * will be blocked by browsers unless it is also served over HTTPS.
 385           */
 386          $url = set_url_scheme( $url, 'https' );
 387      }
 388  
 389      /**
 390       * Filters the REST URL.
 391       *
 392       * Use this filter to adjust the url returned by the get_rest_url() function.
 393       *
 394       * @since 4.4.0
 395       *
 396       * @param string $url     REST URL.
 397       * @param string $path    REST route.
 398       * @param int    $blog_id Blog ID.
 399       * @param string $scheme  Sanitization scheme.
 400       */
 401      return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
 402  }
 403  
 404  /**
 405   * Retrieves the URL to a REST endpoint.
 406   *
 407   * Note: The returned URL is NOT escaped.
 408   *
 409   * @since 4.4.0
 410   *
 411   * @param string $path   Optional. REST route. Default empty.
 412   * @param string $scheme Optional. Sanitization scheme. Default 'rest'.
 413   * @return string Full URL to the endpoint.
 414   */
 415  function rest_url( $path = '', $scheme = 'rest' ) {
 416      return get_rest_url( null, $path, $scheme );
 417  }
 418  
 419  /**
 420   * Do a REST request.
 421   *
 422   * Used primarily to route internal requests through WP_REST_Server.
 423   *
 424   * @since 4.4.0
 425   *
 426   * @param WP_REST_Request|string $request Request.
 427   * @return WP_REST_Response REST response.
 428   */
 429  function rest_do_request( $request ) {
 430      $request = rest_ensure_request( $request );
 431      return rest_get_server()->dispatch( $request );
 432  }
 433  
 434  /**
 435   * Retrieves the current REST server instance.
 436   *
 437   * Instantiates a new instance if none exists already.
 438   *
 439   * @since 4.5.0
 440   *
 441   * @global WP_REST_Server $wp_rest_server REST server instance.
 442   *
 443   * @return WP_REST_Server REST server instance.
 444   */
 445  function rest_get_server() {
 446      /* @var WP_REST_Server $wp_rest_server */
 447      global $wp_rest_server;
 448  
 449      if ( empty( $wp_rest_server ) ) {
 450          /**
 451           * Filters the REST Server Class.
 452           *
 453           * This filter allows you to adjust the server class used by the API, using a
 454           * different class to handle requests.
 455           *
 456           * @since 4.4.0
 457           *
 458           * @param string $class_name The name of the server class. Default 'WP_REST_Server'.
 459           */
 460          $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
 461          $wp_rest_server       = new $wp_rest_server_class;
 462  
 463          /**
 464           * Fires when preparing to serve an API request.
 465           *
 466           * Endpoint objects should be created and register their hooks on this action rather
 467           * than another action to ensure they're only loaded when needed.
 468           *
 469           * @since 4.4.0
 470           *
 471           * @param WP_REST_Server $wp_rest_server Server object.
 472           */
 473          do_action( 'rest_api_init', $wp_rest_server );
 474      }
 475  
 476      return $wp_rest_server;
 477  }
 478  
 479  /**
 480   * Ensures request arguments are a request object (for consistency).
 481   *
 482   * @since 4.4.0
 483   * @since 5.3.0 Accept string argument for the request path.
 484   *
 485   * @param array|string|WP_REST_Request $request Request to check.
 486   * @return WP_REST_Request REST request instance.
 487   */
 488  function rest_ensure_request( $request ) {
 489      if ( $request instanceof WP_REST_Request ) {
 490          return $request;
 491      }
 492  
 493      if ( is_string( $request ) ) {
 494          return new WP_REST_Request( 'GET', $request );
 495      }
 496  
 497      return new WP_REST_Request( 'GET', '', $request );
 498  }
 499  
 500  /**
 501   * Ensures a REST response is a response object (for consistency).
 502   *
 503   * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
 504   * without needing to double-check the object. Will also allow WP_Error to indicate error
 505   * responses, so users should immediately check for this value.
 506   *
 507   * @since 4.4.0
 508   *
 509   * @param WP_HTTP_Response|WP_Error|mixed $response Response to check.
 510   * @return WP_REST_Response|mixed If response generated an error, WP_Error, if response
 511   *                                is already an instance, WP_HTTP_Response, otherwise
 512   *                                returns a new WP_REST_Response instance.
 513   */
 514  function rest_ensure_response( $response ) {
 515      if ( is_wp_error( $response ) ) {
 516          return $response;
 517      }
 518  
 519      if ( $response instanceof WP_HTTP_Response ) {
 520          return $response;
 521      }
 522  
 523      return new WP_REST_Response( $response );
 524  }
 525  
 526  /**
 527   * Handles _deprecated_function() errors.
 528   *
 529   * @since 4.4.0
 530   *
 531   * @param string $function    The function that was called.
 532   * @param string $replacement The function that should have been called.
 533   * @param string $version     Version.
 534   */
 535  function rest_handle_deprecated_function( $function, $replacement, $version ) {
 536      if ( ! WP_DEBUG || headers_sent() ) {
 537          return;
 538      }
 539      if ( ! empty( $replacement ) ) {
 540          /* translators: 1: Function name, 2: WordPress version number, 3: New function name. */
 541          $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
 542      } else {
 543          /* translators: 1: Function name, 2: WordPress version number. */
 544          $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
 545      }
 546  
 547      header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
 548  }
 549  
 550  /**
 551   * Handles _deprecated_argument() errors.
 552   *
 553   * @since 4.4.0
 554   *
 555   * @param string $function    The function that was called.
 556   * @param string $message     A message regarding the change.
 557   * @param string $version     Version.
 558   */
 559  function rest_handle_deprecated_argument( $function, $message, $version ) {
 560      if ( ! WP_DEBUG || headers_sent() ) {
 561          return;
 562      }
 563      if ( ! empty( $message ) ) {
 564          /* translators: 1: Function name, 2: WordPress version number, 3: Error message. */
 565          $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $message );
 566      } else {
 567          /* translators: 1: Function name, 2: WordPress version number. */
 568          $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
 569      }
 570  
 571      header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
 572  }
 573  
 574  /**
 575   * Sends Cross-Origin Resource Sharing headers with API requests.
 576   *
 577   * @since 4.4.0
 578   *
 579   * @param mixed $value Response data.
 580   * @return mixed Response data.
 581   */
 582  function rest_send_cors_headers( $value ) {
 583      $origin = get_http_origin();
 584  
 585      if ( $origin ) {
 586          // Requests from file:// and data: URLs send "Origin: null".
 587          if ( 'null' !== $origin ) {
 588              $origin = esc_url_raw( $origin );
 589          }
 590          header( 'Access-Control-Allow-Origin: ' . $origin );
 591          header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
 592          header( 'Access-Control-Allow-Credentials: true' );
 593          header( 'Vary: Origin', false );
 594      } elseif ( ! headers_sent() && 'GET' === $_SERVER['REQUEST_METHOD'] && ! is_user_logged_in() ) {
 595          header( 'Vary: Origin', false );
 596      }
 597  
 598      return $value;
 599  }
 600  
 601  /**
 602   * Handles OPTIONS requests for the server.
 603   *
 604   * This is handled outside of the server code, as it doesn't obey normal route
 605   * mapping.
 606   *
 607   * @since 4.4.0
 608   *
 609   * @param mixed           $response Current response, either response or `null` to indicate pass-through.
 610   * @param WP_REST_Server  $handler  ResponseHandler instance (usually WP_REST_Server).
 611   * @param WP_REST_Request $request  The request that was used to make current response.
 612   * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
 613   */
 614  function rest_handle_options_request( $response, $handler, $request ) {
 615      if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
 616          return $response;
 617      }
 618  
 619      $response = new WP_REST_Response();
 620      $data     = array();
 621  
 622      foreach ( $handler->get_routes() as $route => $endpoints ) {
 623          $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $matches );
 624  
 625          if ( ! $match ) {
 626              continue;
 627          }
 628  
 629          $args = array();
 630          foreach ( $matches as $param => $value ) {
 631              if ( ! is_int( $param ) ) {
 632                  $args[ $param ] = $value;
 633              }
 634          }
 635  
 636          foreach ( $endpoints as $endpoint ) {
 637              // Remove the redundant preg_match() argument.
 638              unset( $args[0] );
 639  
 640              $request->set_url_params( $args );
 641              $request->set_attributes( $endpoint );
 642          }
 643  
 644          $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
 645          $response->set_matched_route( $route );
 646          break;
 647      }
 648  
 649      $response->set_data( $data );
 650      return $response;
 651  }
 652  
 653  /**
 654   * Sends the "Allow" header to state all methods that can be sent to the current route.
 655   *
 656   * @since 4.4.0
 657   *
 658   * @param WP_REST_Response $response Current response being served.
 659   * @param WP_REST_Server   $server   ResponseHandler instance (usually WP_REST_Server).
 660   * @param WP_REST_Request  $request  The request that was used to make current response.
 661   * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
 662   */
 663  function rest_send_allow_header( $response, $server, $request ) {
 664      $matched_route = $response->get_matched_route();
 665  
 666      if ( ! $matched_route ) {
 667          return $response;
 668      }
 669  
 670      $routes = $server->get_routes();
 671  
 672      $allowed_methods = array();
 673  
 674      // Get the allowed methods across the routes.
 675      foreach ( $routes[ $matched_route ] as $_handler ) {
 676          foreach ( $_handler['methods'] as $handler_method => $value ) {
 677  
 678              if ( ! empty( $_handler['permission_callback'] ) ) {
 679  
 680                  $permission = call_user_func( $_handler['permission_callback'], $request );
 681  
 682                  $allowed_methods[ $handler_method ] = true === $permission;
 683              } else {
 684                  $allowed_methods[ $handler_method ] = true;
 685              }
 686          }
 687      }
 688  
 689      // Strip out all the methods that are not allowed (false values).
 690      $allowed_methods = array_filter( $allowed_methods );
 691  
 692      if ( $allowed_methods ) {
 693          $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
 694      }
 695  
 696      return $response;
 697  }
 698  
 699  /**
 700   * Recursively computes the intersection of arrays using keys for comparison.
 701   *
 702   * @param  array $array1 The array with master keys to check.
 703   * @param  array $array2 An array to compare keys against.
 704   *
 705   * @return array An associative array containing all the entries of array1 which have keys that are present in all arguments.
 706   */
 707  function _rest_array_intersect_key_recursive( $array1, $array2 ) {
 708      $array1 = array_intersect_key( $array1, $array2 );
 709      foreach ( $array1 as $key => $value ) {
 710          if ( is_array( $value ) && is_array( $array2[ $key ] ) ) {
 711              $array1[ $key ] = _rest_array_intersect_key_recursive( $value, $array2[ $key ] );
 712          }
 713      }
 714      return $array1;
 715  }
 716  
 717  /**
 718   * Filter the API response to include only a white-listed set of response object fields.
 719   *
 720   * @since 4.8.0
 721   *
 722   * @param WP_REST_Response $response Current response being served.
 723   * @param WP_REST_Server   $server   ResponseHandler instance (usually WP_REST_Server).
 724   * @param WP_REST_Request  $request  The request that was used to make current response.
 725   *
 726   * @return WP_REST_Response Response to be served, trimmed down to contain a subset of fields.
 727   */
 728  function rest_filter_response_fields( $response, $server, $request ) {
 729      if ( ! isset( $request['_fields'] ) || $response->is_error() ) {
 730          return $response;
 731      }
 732  
 733      $data = $response->get_data();
 734  
 735      $fields = wp_parse_list( $request['_fields'] );
 736  
 737      if ( 0 === count( $fields ) ) {
 738          return $response;
 739      }
 740  
 741      // Trim off outside whitespace from the comma delimited list.
 742      $fields = array_map( 'trim', $fields );
 743  
 744      // Create nested array of accepted field hierarchy.
 745      $fields_as_keyed = array();
 746      foreach ( $fields as $field ) {
 747          $parts = explode( '.', $field );
 748          $ref   = &$fields_as_keyed;
 749          while ( count( $parts ) > 1 ) {
 750              $next = array_shift( $parts );
 751              if ( isset( $ref[ $next ] ) && true === $ref[ $next ] ) {
 752                  // Skip any sub-properties if their parent prop is already marked for inclusion.
 753                  break 2;
 754              }
 755              $ref[ $next ] = isset( $ref[ $next ] ) ? $ref[ $next ] : array();
 756              $ref          = &$ref[ $next ];
 757          }
 758          $last         = array_shift( $parts );
 759          $ref[ $last ] = true;
 760      }
 761  
 762      if ( wp_is_numeric_array( $data ) ) {
 763          $new_data = array();
 764          foreach ( $data as $item ) {
 765              $new_data[] = _rest_array_intersect_key_recursive( $item, $fields_as_keyed );
 766          }
 767      } else {
 768          $new_data = _rest_array_intersect_key_recursive( $data, $fields_as_keyed );
 769      }
 770  
 771      $response->set_data( $new_data );
 772  
 773      return $response;
 774  }
 775  
 776  /**
 777   * Given an array of fields to include in a response, some of which may be
 778   * `nested.fields`, determine whether the provided field should be included
 779   * in the response body.
 780   *
 781   * If a parent field is passed in, the presence of any nested field within
 782   * that parent will cause the method to return `true`. For example "title"
 783   * will return true if any of `title`, `title.raw` or `title.rendered` is
 784   * provided.
 785   *
 786   * @since 5.3.0
 787   *
 788   * @param string $field  A field to test for inclusion in the response body.
 789   * @param array  $fields An array of string fields supported by the endpoint.
 790   * @return bool Whether to include the field or not.
 791   */
 792  function rest_is_field_included( $field, $fields ) {
 793      if ( in_array( $field, $fields, true ) ) {
 794          return true;
 795      }
 796  
 797      foreach ( $fields as $accepted_field ) {
 798          // Check to see if $field is the parent of any item in $fields.
 799          // A field "parent" should be accepted if "parent.child" is accepted.
 800          if ( strpos( $accepted_field, "$field." ) === 0 ) {
 801              return true;
 802          }
 803          // Conversely, if "parent" is accepted, all "parent.child" fields
 804          // should also be accepted.
 805          if ( strpos( $field, "$accepted_field." ) === 0 ) {
 806              return true;
 807          }
 808      }
 809  
 810      return false;
 811  }
 812  
 813  /**
 814   * Adds the REST API URL to the WP RSD endpoint.
 815   *
 816   * @since 4.4.0
 817   *
 818   * @see get_rest_url()
 819   */
 820  function rest_output_rsd() {
 821      $api_root = get_rest_url();
 822  
 823      if ( empty( $api_root ) ) {
 824          return;
 825      }
 826      ?>
 827      <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
 828      <?php
 829  }
 830  
 831  /**
 832   * Outputs the REST API link tag into page header.
 833   *
 834   * @since 4.4.0
 835   *
 836   * @see get_rest_url()
 837   */
 838  function rest_output_link_wp_head() {
 839      $api_root = get_rest_url();
 840  
 841      if ( empty( $api_root ) ) {
 842          return;
 843      }
 844  
 845      echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
 846  }
 847  
 848  /**
 849   * Sends a Link header for the REST API.
 850   *
 851   * @since 4.4.0
 852   */
 853  function rest_output_link_header() {
 854      if ( headers_sent() ) {
 855          return;
 856      }
 857  
 858      $api_root = get_rest_url();
 859  
 860      if ( empty( $api_root ) ) {
 861          return;
 862      }
 863  
 864      header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
 865  }
 866  
 867  /**
 868   * Checks for errors when using cookie-based authentication.
 869   *
 870   * WordPress' built-in cookie authentication is always active
 871   * for logged in users. However, the API has to check nonces
 872   * for each request to ensure users are not vulnerable to CSRF.
 873   *
 874   * @since 4.4.0
 875   *
 876   * @global mixed          $wp_rest_auth_cookie
 877   *
 878   * @param WP_Error|mixed $result Error from another authentication handler,
 879   *                               null if we should handle it, or another value if not.
 880   * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
 881   */
 882  function rest_cookie_check_errors( $result ) {
 883      if ( ! empty( $result ) ) {
 884          return $result;
 885      }
 886  
 887      global $wp_rest_auth_cookie;
 888  
 889      /*
 890       * Is cookie authentication being used? (If we get an auth
 891       * error, but we're still logged in, another authentication
 892       * must have been used).
 893       */
 894      if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
 895          return $result;
 896      }
 897  
 898      // Determine if there is a nonce.
 899      $nonce = null;
 900  
 901      if ( isset( $_REQUEST['_wpnonce'] ) ) {
 902          $nonce = $_REQUEST['_wpnonce'];
 903      } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
 904          $nonce = $_SERVER['HTTP_X_WP_NONCE'];
 905      }
 906  
 907      if ( null === $nonce ) {
 908          // No nonce at all, so act as if it's an unauthenticated request.
 909          wp_set_current_user( 0 );
 910          return true;
 911      }
 912  
 913      // Check the nonce.
 914      $result = wp_verify_nonce( $nonce, 'wp_rest' );
 915  
 916      if ( ! $result ) {
 917          return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
 918      }
 919  
 920      // Send a refreshed nonce in header.
 921      rest_get_server()->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) );
 922  
 923      return true;
 924  }
 925  
 926  /**
 927   * Collects cookie authentication status.
 928   *
 929   * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
 930   *
 931   * @since 4.4.0
 932   *
 933   * @see current_action()
 934   * @global mixed $wp_rest_auth_cookie
 935   */
 936  function rest_cookie_collect_status() {
 937      global $wp_rest_auth_cookie;
 938  
 939      $status_type = current_action();
 940  
 941      if ( 'auth_cookie_valid' !== $status_type ) {
 942          $wp_rest_auth_cookie = substr( $status_type, 12 );
 943          return;
 944      }
 945  
 946      $wp_rest_auth_cookie = true;
 947  }
 948  
 949  /**
 950   * Parses an RFC3339 time into a Unix timestamp.
 951   *
 952   * @since 4.4.0
 953   *
 954   * @param string $date      RFC3339 timestamp.
 955   * @param bool   $force_utc Optional. Whether to force UTC timezone instead of using
 956   *                          the timestamp's timezone. Default false.
 957   * @return int Unix timestamp.
 958   */
 959  function rest_parse_date( $date, $force_utc = false ) {
 960      if ( $force_utc ) {
 961          $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
 962      }
 963  
 964      $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
 965  
 966      if ( ! preg_match( $regex, $date, $matches ) ) {
 967          return false;
 968      }
 969  
 970      return strtotime( $date );
 971  }
 972  
 973  /**
 974   * Parses a date into both its local and UTC equivalent, in MySQL datetime format.
 975   *
 976   * @since 4.4.0
 977   *
 978   * @see rest_parse_date()
 979   *
 980   * @param string $date   RFC3339 timestamp.
 981   * @param bool   $is_utc Whether the provided date should be interpreted as UTC. Default false.
 982   * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
 983   *                    null on failure.
 984   */
 985  function rest_get_date_with_gmt( $date, $is_utc = false ) {
 986      /*
 987       * Whether or not the original date actually has a timezone string
 988       * changes the way we need to do timezone conversion.
 989       * Store this info before parsing the date, and use it later.
 990       */
 991      $has_timezone = preg_match( '#(Z|[+-]\d{2}(:\d{2})?)$#', $date );
 992  
 993      $date = rest_parse_date( $date );
 994  
 995      if ( empty( $date ) ) {
 996          return null;
 997      }
 998  
 999      /*
1000       * At this point $date could either be a local date (if we were passed
1001       * a *local* date without a timezone offset) or a UTC date (otherwise).
1002       * Timezone conversion needs to be handled differently between these two cases.
1003       */
1004      if ( ! $is_utc && ! $has_timezone ) {
1005          $local = gmdate( 'Y-m-d H:i:s', $date );
1006          $utc   = get_gmt_from_date( $local );
1007      } else {
1008          $utc   = gmdate( 'Y-m-d H:i:s', $date );
1009          $local = get_date_from_gmt( $utc );
1010      }
1011  
1012      return array( $local, $utc );
1013  }
1014  
1015  /**
1016   * Returns a contextual HTTP error code for authorization failure.
1017   *
1018   * @since 4.7.0
1019   *
1020   * @return integer 401 if the user is not logged in, 403 if the user is logged in.
1021   */
1022  function rest_authorization_required_code() {
1023      return is_user_logged_in() ? 403 : 401;
1024  }
1025  
1026  /**
1027   * Validate a request argument based on details registered to the route.
1028   *
1029   * @since 4.7.0
1030   *
1031   * @param  mixed            $value
1032   * @param  WP_REST_Request  $request
1033   * @param  string           $param
1034   * @return true|WP_Error
1035   */
1036  function rest_validate_request_arg( $value, $request, $param ) {
1037      $attributes = $request->get_attributes();
1038      if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
1039          return true;
1040      }
1041      $args = $attributes['args'][ $param ];
1042  
1043      return rest_validate_value_from_schema( $value, $args, $param );
1044  }
1045  
1046  /**
1047   * Sanitize a request argument based on details registered to the route.
1048   *
1049   * @since 4.7.0
1050   *
1051   * @param  mixed            $value
1052   * @param  WP_REST_Request  $request
1053   * @param  string           $param
1054   * @return mixed
1055   */
1056  function rest_sanitize_request_arg( $value, $request, $param ) {
1057      $attributes = $request->get_attributes();
1058      if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
1059          return $value;
1060      }
1061      $args = $attributes['args'][ $param ];
1062  
1063      return rest_sanitize_value_from_schema( $value, $args );
1064  }
1065  
1066  /**
1067   * Parse a request argument based on details registered to the route.
1068   *
1069   * Runs a validation check and sanitizes the value, primarily to be used via
1070   * the `sanitize_callback` arguments in the endpoint args registration.
1071   *
1072   * @since 4.7.0
1073   *
1074   * @param  mixed            $value
1075   * @param  WP_REST_Request  $request
1076   * @param  string           $param
1077   * @return mixed
1078   */
1079  function rest_parse_request_arg( $value, $request, $param ) {
1080      $is_valid = rest_validate_request_arg( $value, $request, $param );
1081  
1082      if ( is_wp_error( $is_valid ) ) {
1083          return $is_valid;
1084      }
1085  
1086      $value = rest_sanitize_request_arg( $value, $request, $param );
1087  
1088      return $value;
1089  }
1090  
1091  /**
1092   * Determines if an IP address is valid.
1093   *
1094   * Handles both IPv4 and IPv6 addresses.
1095   *
1096   * @since 4.7.0
1097   *
1098   * @param  string $ip IP address.
1099   * @return string|false The valid IP address, otherwise false.
1100   */
1101  function rest_is_ip_address( $ip ) {
1102      $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]?)$/';
1103  
1104      if ( ! preg_match( $ipv4_pattern, $ip ) && ! Requests_IPv6::check_ipv6( $ip ) ) {
1105          return false;
1106      }
1107  
1108      return $ip;
1109  }
1110  
1111  /**
1112   * Changes a boolean-like value into the proper boolean value.
1113   *
1114   * @since 4.7.0
1115   *
1116   * @param bool|string|int $value The value being evaluated.
1117   * @return boolean Returns the proper associated boolean value.
1118   */
1119  function rest_sanitize_boolean( $value ) {
1120      // String values are translated to `true`; make sure 'false' is false.
1121      if ( is_string( $value ) ) {
1122          $value = strtolower( $value );
1123          if ( in_array( $value, array( 'false', '0' ), true ) ) {
1124              $value = false;
1125          }
1126      }
1127  
1128      // Everything else will map nicely to boolean.
1129      return (bool) $value;
1130  }
1131  
1132  /**
1133   * Determines if a given value is boolean-like.
1134   *
1135   * @since 4.7.0
1136   *
1137   * @param bool|string $maybe_bool The value being evaluated.
1138   * @return boolean True if a boolean, otherwise false.
1139   */
1140  function rest_is_boolean( $maybe_bool ) {
1141      if ( is_bool( $maybe_bool ) ) {
1142          return true;
1143      }
1144  
1145      if ( is_string( $maybe_bool ) ) {
1146          $maybe_bool = strtolower( $maybe_bool );
1147  
1148          $valid_boolean_values = array(
1149              'false',
1150              'true',
1151              '0',
1152              '1',
1153          );
1154  
1155          return in_array( $maybe_bool, $valid_boolean_values, true );
1156      }
1157  
1158      if ( is_int( $maybe_bool ) ) {
1159          return in_array( $maybe_bool, array( 0, 1 ), true );
1160      }
1161  
1162      return false;
1163  }
1164  
1165  /**
1166   * Retrieves the avatar urls in various sizes.
1167   *
1168   * @since 4.7.0
1169   *
1170   * @see get_avatar_url()
1171   *
1172   * @param mixed $id_or_email The Gravatar to retrieve a URL for. Accepts a user_id, gravatar md5 hash,
1173   *                           user email, WP_User object, WP_Post object, or WP_Comment object.
1174   * @return array Avatar URLs keyed by size. Each value can be a URL string or boolean false.
1175   */
1176  function rest_get_avatar_urls( $id_or_email ) {
1177      $avatar_sizes = rest_get_avatar_sizes();
1178  
1179      $urls = array();
1180      foreach ( $avatar_sizes as $size ) {
1181          $urls[ $size ] = get_avatar_url( $id_or_email, array( 'size' => $size ) );
1182      }
1183  
1184      return $urls;
1185  }
1186  
1187  /**
1188   * Retrieves the pixel sizes for avatars.
1189   *
1190   * @since 4.7.0
1191   *
1192   * @return int[] List of pixel sizes for avatars. Default `[ 24, 48, 96 ]`.
1193   */
1194  function rest_get_avatar_sizes() {
1195      /**
1196       * Filters the REST avatar sizes.
1197       *
1198       * Use this filter to adjust the array of sizes returned by the
1199       * `rest_get_avatar_sizes` function.
1200       *
1201       * @since 4.4.0
1202       *
1203       * @param int[] $sizes An array of int values that are the pixel sizes for avatars.
1204       *                     Default `[ 24, 48, 96 ]`.
1205       */
1206      return apply_filters( 'rest_avatar_sizes', array( 24, 48, 96 ) );
1207  }
1208  
1209  /**
1210   * Validate a value based on a schema.
1211   *
1212   * @since 4.7.0
1213   *
1214   * @param mixed  $value The value to validate.
1215   * @param array  $args  Schema array to use for validation.
1216   * @param string $param The parameter name, used in error messages.
1217   * @return true|WP_Error
1218   */
1219  function rest_validate_value_from_schema( $value, $args, $param = '' ) {
1220      if ( is_array( $args['type'] ) ) {
1221          foreach ( $args['type'] as $type ) {
1222              $type_args         = $args;
1223              $type_args['type'] = $type;
1224  
1225              if ( true === rest_validate_value_from_schema( $value, $type_args, $param ) ) {
1226                  return true;
1227              }
1228          }
1229  
1230          /* translators: 1: Parameter, 2: List of types. */
1231          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, implode( ',', $args['type'] ) ) );
1232      }
1233  
1234      if ( 'array' === $args['type'] ) {
1235          if ( ! is_null( $value ) ) {
1236              $value = wp_parse_list( $value );
1237          }
1238  
1239          if ( ! wp_is_numeric_array( $value ) ) {
1240              /* translators: 1: Parameter, 2: Type name. */
1241              return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'array' ) );
1242          }
1243  
1244          foreach ( $value as $index => $v ) {
1245              $is_valid = rest_validate_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' );
1246              if ( is_wp_error( $is_valid ) ) {
1247                  return $is_valid;
1248              }
1249          }
1250      }
1251  
1252      if ( 'object' === $args['type'] ) {
1253          if ( '' === $value ) {
1254              $value = array();
1255          }
1256  
1257          if ( $value instanceof stdClass ) {
1258              $value = (array) $value;
1259          }
1260  
1261          if ( $value instanceof JsonSerializable ) {
1262              $value = $value->jsonSerialize();
1263          }
1264  
1265          if ( ! is_array( $value ) ) {
1266              /* translators: 1: Parameter, 2: Type name. */
1267              return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'object' ) );
1268          }
1269  
1270          foreach ( $value as $property => $v ) {
1271              if ( isset( $args['properties'][ $property ] ) ) {
1272                  $is_valid = rest_validate_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' );
1273                  if ( is_wp_error( $is_valid ) ) {
1274                      return $is_valid;
1275                  }
1276              } elseif ( isset( $args['additionalProperties'] ) ) {
1277                  if ( false === $args['additionalProperties'] ) {
1278                      /* translators: %s: Property of an object. */
1279                      return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not a valid property of Object.' ), $property ) );
1280                  }
1281  
1282                  if ( is_array( $args['additionalProperties'] ) ) {
1283                      $is_valid = rest_validate_value_from_schema( $v, $args['additionalProperties'], $param . '[' . $property . ']' );
1284                      if ( is_wp_error( $is_valid ) ) {
1285                          return $is_valid;
1286                      }
1287                  }
1288              }
1289          }
1290      }
1291  
1292      if ( 'null' === $args['type'] ) {
1293          if ( null !== $value ) {
1294              /* translators: 1: Parameter, 2: Type name. */
1295              return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'null' ) );
1296          }
1297  
1298          return true;
1299      }
1300  
1301      if ( ! empty( $args['enum'] ) ) {
1302          if ( ! in_array( $value, $args['enum'], true ) ) {
1303              /* translators: 1: Parameter, 2: List of valid values. */
1304              return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not one of %2$s.' ), $param, implode( ', ', $args['enum'] ) ) );
1305          }
1306      }
1307  
1308      if ( in_array( $args['type'], array( 'integer', 'number' ) ) && ! is_numeric( $value ) ) {
1309          /* translators: 1: Parameter, 2: Type name. */
1310          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, $args['type'] ) );
1311      }
1312  
1313      if ( 'integer' === $args['type'] && round( floatval( $value ) ) !== floatval( $value ) ) {
1314          /* translators: 1: Parameter, 2: Type name. */
1315          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'integer' ) );
1316      }
1317  
1318      if ( 'boolean' === $args['type'] && ! rest_is_boolean( $value ) ) {
1319          /* translators: 1: Parameter, 2: Type name. */
1320          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'boolean' ) );
1321      }
1322  
1323      if ( 'string' === $args['type'] && ! is_string( $value ) ) {
1324          /* translators: 1: Parameter, 2: Type name. */
1325          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
1326      }
1327  
1328      if ( isset( $args['format'] ) ) {
1329          switch ( $args['format'] ) {
1330              case 'date-time':
1331                  if ( ! rest_parse_date( $value ) ) {
1332                      return new WP_Error( 'rest_invalid_date', __( 'Invalid date.' ) );
1333                  }
1334                  break;
1335  
1336              case 'email':
1337                  if ( ! is_email( $value ) ) {
1338                      return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ) );
1339                  }
1340                  break;
1341              case 'ip':
1342                  if ( ! rest_is_ip_address( $value ) ) {
1343                      /* translators: %s: IP address. */
1344                      return new WP_Error( 'rest_invalid_param', sprintf( __( '%s is not a valid IP address.' ), $param ) );
1345                  }
1346                  break;
1347          }
1348      }
1349  
1350      if ( in_array( $args['type'], array( 'number', 'integer' ), true ) && ( isset( $args['minimum'] ) || isset( $args['maximum'] ) ) ) {
1351          if ( isset( $args['minimum'] ) && ! isset( $args['maximum'] ) ) {
1352              if ( ! empty( $args['exclusiveMinimum'] ) && $value <= $args['minimum'] ) {
1353                  /* translators: 1: Parameter, 2: Minimum number. */
1354                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d' ), $param, $args['minimum'] ) );
1355              } elseif ( empty( $args['exclusiveMinimum'] ) && $value < $args['minimum'] ) {
1356                  /* translators: 1: Parameter, 2: Minimum number. */
1357                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than or equal to %2$d' ), $param, $args['minimum'] ) );
1358              }
1359          } elseif ( isset( $args['maximum'] ) && ! isset( $args['minimum'] ) ) {
1360              if ( ! empty( $args['exclusiveMaximum'] ) && $value >= $args['maximum'] ) {
1361                  /* translators: 1: Parameter, 2: Maximum number. */
1362                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d' ), $param, $args['maximum'] ) );
1363              } elseif ( empty( $args['exclusiveMaximum'] ) && $value > $args['maximum'] ) {
1364                  /* translators: 1: Parameter, 2: Maximum number. */
1365                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than or equal to %2$d' ), $param, $args['maximum'] ) );
1366              }
1367          } elseif ( isset( $args['maximum'] ) && isset( $args['minimum'] ) ) {
1368              if ( ! empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
1369                  if ( $value >= $args['maximum'] || $value <= $args['minimum'] ) {
1370                      /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
1371                      return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (exclusive) and %3$d (exclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1372                  }
1373              } elseif ( empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
1374                  if ( $value >= $args['maximum'] || $value < $args['minimum'] ) {
1375                      /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
1376                      return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (inclusive) and %3$d (exclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1377                  }
1378              } elseif ( ! empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
1379                  if ( $value > $args['maximum'] || $value <= $args['minimum'] ) {
1380                      /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
1381                      return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (exclusive) and %3$d (inclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1382                  }
1383              } elseif ( empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
1384                  if ( $value > $args['maximum'] || $value < $args['minimum'] ) {
1385                      /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
1386                      return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (inclusive) and %3$d (inclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1387                  }
1388              }
1389          }
1390      }
1391  
1392      return true;
1393  }
1394  
1395  /**
1396   * Sanitize a value based on a schema.
1397   *
1398   * @since 4.7.0
1399   *
1400   * @param mixed $value The value to sanitize.
1401   * @param array $args  Schema array to use for sanitization.
1402   * @return true|WP_Error
1403   */
1404  function rest_sanitize_value_from_schema( $value, $args ) {
1405      if ( is_array( $args['type'] ) ) {
1406          // Determine which type the value was validated against,
1407          // and use that type when performing sanitization.
1408          $validated_type = '';
1409  
1410          foreach ( $args['type'] as $type ) {
1411              $type_args         = $args;
1412              $type_args['type'] = $type;
1413  
1414              if ( ! is_wp_error( rest_validate_value_from_schema( $value, $type_args ) ) ) {
1415                  $validated_type = $type;
1416                  break;
1417              }
1418          }
1419  
1420          if ( ! $validated_type ) {
1421              return null;
1422          }
1423  
1424          $args['type'] = $validated_type;
1425      }
1426  
1427      if ( 'array' === $args['type'] ) {
1428          if ( empty( $args['items'] ) ) {
1429              return (array) $value;
1430          }
1431  
1432          $value = wp_parse_list( $value );
1433          foreach ( $value as $index => $v ) {
1434              $value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'] );
1435          }
1436  
1437          // Normalize to numeric array so nothing unexpected is in the keys.
1438          $value = array_values( $value );
1439          return $value;
1440      }
1441  
1442      if ( 'object' === $args['type'] ) {
1443          if ( $value instanceof stdClass ) {
1444              $value = (array) $value;
1445          }
1446  
1447          if ( $value instanceof JsonSerializable ) {
1448              $value = $value->jsonSerialize();
1449          }
1450  
1451          if ( ! is_array( $value ) ) {
1452              return array();
1453          }
1454  
1455          foreach ( $value as $property => $v ) {
1456              if ( isset( $args['properties'][ $property ] ) ) {
1457                  $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['properties'][ $property ] );
1458              } elseif ( isset( $args['additionalProperties'] ) ) {
1459                  if ( false === $args['additionalProperties'] ) {
1460                      unset( $value[ $property ] );
1461                  } elseif ( is_array( $args['additionalProperties'] ) ) {
1462                      $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['additionalProperties'] );
1463                  }
1464              }
1465          }
1466  
1467          return $value;
1468      }
1469  
1470      if ( 'null' === $args['type'] ) {
1471          return null;
1472      }
1473  
1474      if ( 'integer' === $args['type'] ) {
1475          return (int) $value;
1476      }
1477  
1478      if ( 'number' === $args['type'] ) {
1479          return (float) $value;
1480      }
1481  
1482      if ( 'boolean' === $args['type'] ) {
1483          return rest_sanitize_boolean( $value );
1484      }
1485  
1486      if ( isset( $args['format'] ) ) {
1487          switch ( $args['format'] ) {
1488              case 'date-time':
1489                  return sanitize_text_field( $value );
1490  
1491              case 'email':
1492                  // sanitize_email() validates, which would be unexpected.
1493                  return sanitize_text_field( $value );
1494  
1495              case 'uri':
1496                  return esc_url_raw( $value );
1497  
1498              case 'ip':
1499                  return sanitize_text_field( $value );
1500          }
1501      }
1502  
1503      if ( 'string' === $args['type'] ) {
1504          return strval( $value );
1505      }
1506  
1507      return $value;
1508  }
1509  
1510  /**
1511   * Append result of internal request to REST API for purpose of preloading data to be attached to a page.
1512   * Expected to be called in the context of `array_reduce`.
1513   *
1514   * @since 5.0.0
1515   *
1516   * @param  array  $memo Reduce accumulator.
1517   * @param  string $path REST API path to preload.
1518   * @return array        Modified reduce accumulator.
1519   */
1520  function rest_preload_api_request( $memo, $path ) {
1521      // array_reduce() doesn't support passing an array in PHP 5.2,
1522      // so we need to make sure we start with one.
1523      if ( ! is_array( $memo ) ) {
1524          $memo = array();
1525      }
1526  
1527      if ( empty( $path ) ) {
1528          return $memo;
1529      }
1530  
1531      $method = 'GET';
1532      if ( is_array( $path ) && 2 === count( $path ) ) {
1533          $method = end( $path );
1534          $path   = reset( $path );
1535  
1536          if ( ! in_array( $method, array( 'GET', 'OPTIONS' ), true ) ) {
1537              $method = 'GET';
1538          }
1539      }
1540  
1541      $path_parts = parse_url( $path );
1542      if ( false === $path_parts ) {
1543          return $memo;
1544      }
1545  
1546      $request = new WP_REST_Request( $method, $path_parts['path'] );
1547      if ( ! empty( $path_parts['query'] ) ) {
1548          parse_str( $path_parts['query'], $query_params );
1549          $request->set_query_params( $query_params );
1550      }
1551  
1552      $response = rest_do_request( $request );
1553      if ( 200 === $response->status ) {
1554          $server = rest_get_server();
1555          $data   = (array) $response->get_data();
1556          $links  = $server::get_compact_response_links( $response );
1557          if ( ! empty( $links ) ) {
1558              $data['_links'] = $links;
1559          }
1560  
1561          if ( 'OPTIONS' === $method ) {
1562              $response = rest_send_allow_header( $response, $server, $request );
1563  
1564              $memo[ $method ][ $path ] = array(
1565                  'body'    => $data,
1566                  'headers' => $response->headers,
1567              );
1568          } else {
1569              $memo[ $path ] = array(
1570                  'body'    => $data,
1571                  'headers' => $response->headers,
1572              );
1573          }
1574      }
1575  
1576      return $memo;
1577  }
1578  
1579  /**
1580   * Parses the "_embed" parameter into the list of resources to embed.
1581   *
1582   * @since 5.4.0
1583   *
1584   * @param string|array $embed Raw "_embed" parameter value.
1585   * @return true|string[] Either true to embed all embeds, or a list of relations to embed.
1586   */
1587  function rest_parse_embed_param( $embed ) {
1588      if ( ! $embed || 'true' === $embed || '1' === $embed ) {
1589          return true;
1590      }
1591  
1592      $rels = wp_parse_list( $embed );
1593  
1594      if ( ! $rels ) {
1595          return true;
1596      }
1597  
1598      return $rels;
1599  }


Generated: Tue May 19 15:51:04 2020 Cross-referenced by PHPXref 0.7.1