[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sat Sep 21 01:00:03 2019 Cross-referenced by PHPXref 0.7.1