[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7