[ 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 string|array|null $get_callback    Optional. The callback function used to retrieve the field
 106   *                                              value. Default is 'null', the field will not be returned in
 107   *                                              the response.
 108   *     @type string|array|null $update_callback Optional. The callback function used to set and update the
 109   *                                              field value. Default is 'null', the value cannot be set or
 110   *                                              updated.
 111   *     @type string|array|null $schema          Optional. The callback function used to create the schema for
 112   *                                              this field. 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
 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
 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() ) {
 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   *
 486   * @param array|WP_REST_Request $request Request to check.
 487   * @return WP_REST_Request REST request instance.
 488   */
 489  function rest_ensure_request( $request ) {
 490      if ( $request instanceof WP_REST_Request ) {
 491          return $request;
 492      }
 493  
 494      return new WP_REST_Request( 'GET', '', $request );
 495  }
 496  
 497  /**
 498   * Ensures a REST response is a response object (for consistency).
 499   *
 500   * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
 501   * without needing to double-check the object. Will also allow WP_Error to indicate error
 502   * responses, so users should immediately check for this value.
 503   *
 504   * @since 4.4.0
 505   *
 506   * @param WP_Error|WP_HTTP_Response|mixed $response Response to check.
 507   * @return WP_REST_Response|mixed If response generated an error, WP_Error, if response
 508   *                                is already an instance, WP_HTTP_Response, otherwise
 509   *                                returns a new WP_REST_Response instance.
 510   */
 511  function rest_ensure_response( $response ) {
 512      if ( is_wp_error( $response ) ) {
 513          return $response;
 514      }
 515  
 516      if ( $response instanceof WP_HTTP_Response ) {
 517          return $response;
 518      }
 519  
 520      return new WP_REST_Response( $response );
 521  }
 522  
 523  /**
 524   * Handles _deprecated_function() errors.
 525   *
 526   * @since 4.4.0
 527   *
 528   * @param string $function    The function that was called.
 529   * @param string $replacement The function that should have been called.
 530   * @param string $version     Version.
 531   */
 532  function rest_handle_deprecated_function( $function, $replacement, $version ) {
 533      if ( ! WP_DEBUG || headers_sent() ) {
 534          return;
 535      }
 536      if ( ! empty( $replacement ) ) {
 537          /* translators: 1: function name, 2: WordPress version number, 3: new function name */
 538          $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
 539      } else {
 540          /* translators: 1: function name, 2: WordPress version number */
 541          $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
 542      }
 543  
 544      header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
 545  }
 546  
 547  /**
 548   * Handles _deprecated_argument() errors.
 549   *
 550   * @since 4.4.0
 551   *
 552   * @param string $function    The function that was called.
 553   * @param string $message     A message regarding the change.
 554   * @param string $version     Version.
 555   */
 556  function rest_handle_deprecated_argument( $function, $message, $version ) {
 557      if ( ! WP_DEBUG || headers_sent() ) {
 558          return;
 559      }
 560      if ( ! empty( $message ) ) {
 561          /* translators: 1: function name, 2: WordPress version number, 3: error message */
 562          $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $message );
 563      } else {
 564          /* translators: 1: function name, 2: WordPress version number */
 565          $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
 566      }
 567  
 568      header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
 569  }
 570  
 571  /**
 572   * Sends Cross-Origin Resource Sharing headers with API requests.
 573   *
 574   * @since 4.4.0
 575   *
 576   * @param mixed $value Response data.
 577   * @return mixed Response data.
 578   */
 579  function rest_send_cors_headers( $value ) {
 580      $origin = get_http_origin();
 581  
 582      if ( $origin ) {
 583          // Requests from file:// and data: URLs send "Origin: null"
 584          if ( 'null' !== $origin ) {
 585              $origin = esc_url_raw( $origin );
 586          }
 587          header( 'Access-Control-Allow-Origin: ' . $origin );
 588          header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
 589          header( 'Access-Control-Allow-Credentials: true' );
 590          header( 'Vary: Origin' );
 591      }
 592  
 593      return $value;
 594  }
 595  
 596  /**
 597   * Handles OPTIONS requests for the server.
 598   *
 599   * This is handled outside of the server code, as it doesn't obey normal route
 600   * mapping.
 601   *
 602   * @since 4.4.0
 603   *
 604   * @param mixed           $response Current response, either response or `null` to indicate pass-through.
 605   * @param WP_REST_Server  $handler  ResponseHandler instance (usually WP_REST_Server).
 606   * @param WP_REST_Request $request  The request that was used to make current response.
 607   * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
 608   */
 609  function rest_handle_options_request( $response, $handler, $request ) {
 610      if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
 611          return $response;
 612      }
 613  
 614      $response = new WP_REST_Response();
 615      $data     = array();
 616  
 617      foreach ( $handler->get_routes() as $route => $endpoints ) {
 618          $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $matches );
 619  
 620          if ( ! $match ) {
 621              continue;
 622          }
 623  
 624          $args = array();
 625          foreach ( $matches as $param => $value ) {
 626              if ( ! is_int( $param ) ) {
 627                  $args[ $param ] = $value;
 628              }
 629          }
 630  
 631          foreach ( $endpoints as $endpoint ) {
 632              // Remove the redundant preg_match argument.
 633              unset( $args[0] );
 634  
 635              $request->set_url_params( $args );
 636              $request->set_attributes( $endpoint );
 637          }
 638  
 639          $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
 640          $response->set_matched_route( $route );
 641          break;
 642      }
 643  
 644      $response->set_data( $data );
 645      return $response;
 646  }
 647  
 648  /**
 649   * Sends the "Allow" header to state all methods that can be sent to the current route.
 650   *
 651   * @since 4.4.0
 652   *
 653   * @param WP_REST_Response $response Current response being served.
 654   * @param WP_REST_Server   $server   ResponseHandler instance (usually WP_REST_Server).
 655   * @param WP_REST_Request  $request  The request that was used to make current response.
 656   * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
 657   */
 658  function rest_send_allow_header( $response, $server, $request ) {
 659      $matched_route = $response->get_matched_route();
 660  
 661      if ( ! $matched_route ) {
 662          return $response;
 663      }
 664  
 665      $routes = $server->get_routes();
 666  
 667      $allowed_methods = array();
 668  
 669      // Get the allowed methods across the routes.
 670      foreach ( $routes[ $matched_route ] as $_handler ) {
 671          foreach ( $_handler['methods'] as $handler_method => $value ) {
 672  
 673              if ( ! empty( $_handler['permission_callback'] ) ) {
 674  
 675                  $permission = call_user_func( $_handler['permission_callback'], $request );
 676  
 677                  $allowed_methods[ $handler_method ] = true === $permission;
 678              } else {
 679                  $allowed_methods[ $handler_method ] = true;
 680              }
 681          }
 682      }
 683  
 684      // Strip out all the methods that are not allowed (false values).
 685      $allowed_methods = array_filter( $allowed_methods );
 686  
 687      if ( $allowed_methods ) {
 688          $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
 689      }
 690  
 691      return $response;
 692  }
 693  
 694  /**
 695   * Filter the API response to include only a white-listed set of response object fields.
 696   *
 697   * @since 4.8.0
 698   *
 699   * @param WP_REST_Response $response Current response being served.
 700   * @param WP_REST_Server   $server   ResponseHandler instance (usually WP_REST_Server).
 701   * @param WP_REST_Request  $request  The request that was used to make current response.
 702   *
 703   * @return WP_REST_Response Response to be served, trimmed down to contain a subset of fields.
 704   */
 705  function rest_filter_response_fields( $response, $server, $request ) {
 706      if ( ! isset( $request['_fields'] ) || $response->is_error() ) {
 707          return $response;
 708      }
 709  
 710      $data = $response->get_data();
 711  
 712      $fields = wp_parse_list( $request['_fields'] );
 713  
 714      if ( 0 === count( $fields ) ) {
 715          return $response;
 716      }
 717  
 718      // Trim off outside whitespace from the comma delimited list.
 719      $fields = array_map( 'trim', $fields );
 720  
 721      $fields_as_keyed = array_combine( $fields, array_fill( 0, count( $fields ), true ) );
 722  
 723      if ( wp_is_numeric_array( $data ) ) {
 724          $new_data = array();
 725          foreach ( $data as $item ) {
 726              $new_data[] = array_intersect_key( $item, $fields_as_keyed );
 727          }
 728      } else {
 729          $new_data = array_intersect_key( $data, $fields_as_keyed );
 730      }
 731  
 732      $response->set_data( $new_data );
 733  
 734      return $response;
 735  }
 736  
 737  /**
 738   * Adds the REST API URL to the WP RSD endpoint.
 739   *
 740   * @since 4.4.0
 741   *
 742   * @see get_rest_url()
 743   */
 744  function rest_output_rsd() {
 745      $api_root = get_rest_url();
 746  
 747      if ( empty( $api_root ) ) {
 748          return;
 749      }
 750      ?>
 751      <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
 752      <?php
 753  }
 754  
 755  /**
 756   * Outputs the REST API link tag into page header.
 757   *
 758   * @since 4.4.0
 759   *
 760   * @see get_rest_url()
 761   */
 762  function rest_output_link_wp_head() {
 763      $api_root = get_rest_url();
 764  
 765      if ( empty( $api_root ) ) {
 766          return;
 767      }
 768  
 769      echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
 770  }
 771  
 772  /**
 773   * Sends a Link header for the REST API.
 774   *
 775   * @since 4.4.0
 776   */
 777  function rest_output_link_header() {
 778      if ( headers_sent() ) {
 779          return;
 780      }
 781  
 782      $api_root = get_rest_url();
 783  
 784      if ( empty( $api_root ) ) {
 785          return;
 786      }
 787  
 788      header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
 789  }
 790  
 791  /**
 792   * Checks for errors when using cookie-based authentication.
 793   *
 794   * WordPress' built-in cookie authentication is always active
 795   * for logged in users. However, the API has to check nonces
 796   * for each request to ensure users are not vulnerable to CSRF.
 797   *
 798   * @since 4.4.0
 799   *
 800   * @global mixed          $wp_rest_auth_cookie
 801   *
 802   * @param WP_Error|mixed $result Error from another authentication handler,
 803   *                               null if we should handle it, or another value
 804   *                               if not.
 805   * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
 806   */
 807  function rest_cookie_check_errors( $result ) {
 808      if ( ! empty( $result ) ) {
 809          return $result;
 810      }
 811  
 812      global $wp_rest_auth_cookie;
 813  
 814      /*
 815       * Is cookie authentication being used? (If we get an auth
 816       * error, but we're still logged in, another authentication
 817       * must have been used).
 818       */
 819      if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
 820          return $result;
 821      }
 822  
 823      // Determine if there is a nonce.
 824      $nonce = null;
 825  
 826      if ( isset( $_REQUEST['_wpnonce'] ) ) {
 827          $nonce = $_REQUEST['_wpnonce'];
 828      } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
 829          $nonce = $_SERVER['HTTP_X_WP_NONCE'];
 830      }
 831  
 832      if ( null === $nonce ) {
 833          // No nonce at all, so act as if it's an unauthenticated request.
 834          wp_set_current_user( 0 );
 835          return true;
 836      }
 837  
 838      // Check the nonce.
 839      $result = wp_verify_nonce( $nonce, 'wp_rest' );
 840  
 841      if ( ! $result ) {
 842          return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
 843      }
 844  
 845      // Send a refreshed nonce in header.
 846      rest_get_server()->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) );
 847  
 848      return true;
 849  }
 850  
 851  /**
 852   * Collects cookie authentication status.
 853   *
 854   * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
 855   *
 856   * @since 4.4.0
 857   *
 858   * @see current_action()
 859   * @global mixed $wp_rest_auth_cookie
 860   */
 861  function rest_cookie_collect_status() {
 862      global $wp_rest_auth_cookie;
 863  
 864      $status_type = current_action();
 865  
 866      if ( 'auth_cookie_valid' !== $status_type ) {
 867          $wp_rest_auth_cookie = substr( $status_type, 12 );
 868          return;
 869      }
 870  
 871      $wp_rest_auth_cookie = true;
 872  }
 873  
 874  /**
 875   * Parses an RFC3339 time into a Unix timestamp.
 876   *
 877   * @since 4.4.0
 878   *
 879   * @param string $date      RFC3339 timestamp.
 880   * @param bool   $force_utc Optional. Whether to force UTC timezone instead of using
 881   *                          the timestamp's timezone. Default false.
 882   * @return int Unix timestamp.
 883   */
 884  function rest_parse_date( $date, $force_utc = false ) {
 885      if ( $force_utc ) {
 886          $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
 887      }
 888  
 889      $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
 890  
 891      if ( ! preg_match( $regex, $date, $matches ) ) {
 892          return false;
 893      }
 894  
 895      return strtotime( $date );
 896  }
 897  
 898  /**
 899   * Parses a date into both its local and UTC equivalent, in MySQL datetime format.
 900   *
 901   * @since 4.4.0
 902   *
 903   * @see rest_parse_date()
 904   *
 905   * @param string $date   RFC3339 timestamp.
 906   * @param bool   $is_utc Whether the provided date should be interpreted as UTC. Default false.
 907   * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
 908   *                    null on failure.
 909   */
 910  function rest_get_date_with_gmt( $date, $is_utc = false ) {
 911      // Whether or not the original date actually has a timezone string
 912      // changes the way we need to do timezone conversion.  Store this info
 913      // before parsing the date, and use it later.
 914      $has_timezone = preg_match( '#(Z|[+-]\d{2}(:\d{2})?)$#', $date );
 915  
 916      $date = rest_parse_date( $date );
 917  
 918      if ( empty( $date ) ) {
 919          return null;
 920      }
 921  
 922      // At this point $date could either be a local date (if we were passed a
 923      // *local* date without a timezone offset) or a UTC date (otherwise).
 924      // Timezone conversion needs to be handled differently between these two
 925      // cases.
 926      if ( ! $is_utc && ! $has_timezone ) {
 927          $local = gmdate( 'Y-m-d H:i:s', $date );
 928          $utc   = get_gmt_from_date( $local );
 929      } else {
 930          $utc   = gmdate( 'Y-m-d H:i:s', $date );
 931          $local = get_date_from_gmt( $utc );
 932      }
 933  
 934      return array( $local, $utc );
 935  }
 936  
 937  /**
 938   * Returns a contextual HTTP error code for authorization failure.
 939   *
 940   * @since 4.7.0
 941   *
 942   * @return integer 401 if the user is not logged in, 403 if the user is logged in.
 943   */
 944  function rest_authorization_required_code() {
 945      return is_user_logged_in() ? 403 : 401;
 946  }
 947  
 948  /**
 949   * Validate a request argument based on details registered to the route.
 950   *
 951   * @since 4.7.0
 952   *
 953   * @param  mixed            $value
 954   * @param  WP_REST_Request  $request
 955   * @param  string           $param
 956   * @return WP_Error|boolean
 957   */
 958  function rest_validate_request_arg( $value, $request, $param ) {
 959      $attributes = $request->get_attributes();
 960      if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
 961          return true;
 962      }
 963      $args = $attributes['args'][ $param ];
 964  
 965      return rest_validate_value_from_schema( $value, $args, $param );
 966  }
 967  
 968  /**
 969   * Sanitize a request argument based on details registered to the route.
 970   *
 971   * @since 4.7.0
 972   *
 973   * @param  mixed            $value
 974   * @param  WP_REST_Request  $request
 975   * @param  string           $param
 976   * @return mixed
 977   */
 978  function rest_sanitize_request_arg( $value, $request, $param ) {
 979      $attributes = $request->get_attributes();
 980      if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
 981          return $value;
 982      }
 983      $args = $attributes['args'][ $param ];
 984  
 985      return rest_sanitize_value_from_schema( $value, $args );
 986  }
 987  
 988  /**
 989   * Parse a request argument based on details registered to the route.
 990   *
 991   * Runs a validation check and sanitizes the value, primarily to be used via
 992   * the `sanitize_callback` arguments in the endpoint args registration.
 993   *
 994   * @since 4.7.0
 995   *
 996   * @param  mixed            $value
 997   * @param  WP_REST_Request  $request
 998   * @param  string           $param
 999   * @return mixed
1000   */
1001  function rest_parse_request_arg( $value, $request, $param ) {
1002      $is_valid = rest_validate_request_arg( $value, $request, $param );
1003  
1004      if ( is_wp_error( $is_valid ) ) {
1005          return $is_valid;
1006      }
1007  
1008      $value = rest_sanitize_request_arg( $value, $request, $param );
1009  
1010      return $value;
1011  }
1012  
1013  /**
1014   * Determines if an IP address is valid.
1015   *
1016   * Handles both IPv4 and IPv6 addresses.
1017   *
1018   * @since 4.7.0
1019   *
1020   * @param  string $ip IP address.
1021   * @return string|false The valid IP address, otherwise false.
1022   */
1023  function rest_is_ip_address( $ip ) {
1024      $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]?)$/';
1025  
1026      if ( ! preg_match( $ipv4_pattern, $ip ) && ! Requests_IPv6::check_ipv6( $ip ) ) {
1027          return false;
1028      }
1029  
1030      return $ip;
1031  }
1032  
1033  /**
1034   * Changes a boolean-like value into the proper boolean value.
1035   *
1036   * @since 4.7.0
1037   *
1038   * @param bool|string|int $value The value being evaluated.
1039   * @return boolean Returns the proper associated boolean value.
1040   */
1041  function rest_sanitize_boolean( $value ) {
1042      // String values are translated to `true`; make sure 'false' is false.
1043      if ( is_string( $value ) ) {
1044          $value = strtolower( $value );
1045          if ( in_array( $value, array( 'false', '0' ), true ) ) {
1046              $value = false;
1047          }
1048      }
1049  
1050      // Everything else will map nicely to boolean.
1051      return (bool) $value;
1052  }
1053  
1054  /**
1055   * Determines if a given value is boolean-like.
1056   *
1057   * @since 4.7.0
1058   *
1059   * @param bool|string $maybe_bool The value being evaluated.
1060   * @return boolean True if a boolean, otherwise false.
1061   */
1062  function rest_is_boolean( $maybe_bool ) {
1063      if ( is_bool( $maybe_bool ) ) {
1064          return true;
1065      }
1066  
1067      if ( is_string( $maybe_bool ) ) {
1068          $maybe_bool = strtolower( $maybe_bool );
1069  
1070          $valid_boolean_values = array(
1071              'false',
1072              'true',
1073              '0',
1074              '1',
1075          );
1076  
1077          return in_array( $maybe_bool, $valid_boolean_values, true );
1078      }
1079  
1080      if ( is_int( $maybe_bool ) ) {
1081          return in_array( $maybe_bool, array( 0, 1 ), true );
1082      }
1083  
1084      return false;
1085  }
1086  
1087  /**
1088   * Retrieves the avatar urls in various sizes.
1089   *
1090   * @since 4.7.0
1091   *
1092   * @see get_avatar_url()
1093   *
1094   * @param mixed $id_or_email The Gravatar to retrieve a URL for. Accepts a user_id, gravatar md5 hash,
1095   *                           user email, WP_User object, WP_Post object, or WP_Comment object.
1096   * @return array $urls Gravatar url for each size.
1097   */
1098  function rest_get_avatar_urls( $id_or_email ) {
1099      $avatar_sizes = rest_get_avatar_sizes();
1100  
1101      $urls = array();
1102      foreach ( $avatar_sizes as $size ) {
1103          $urls[ $size ] = get_avatar_url( $id_or_email, array( 'size' => $size ) );
1104      }
1105  
1106      return $urls;
1107  }
1108  
1109  /**
1110   * Retrieves the pixel sizes for avatars.
1111   *
1112   * @since 4.7.0
1113   *
1114   * @return array List of pixel sizes for avatars. Default `[ 24, 48, 96 ]`.
1115   */
1116  function rest_get_avatar_sizes() {
1117      /**
1118       * Filters the REST avatar sizes.
1119       *
1120       * Use this filter to adjust the array of sizes returned by the
1121       * `rest_get_avatar_sizes` function.
1122       *
1123       * @since 4.4.0
1124       *
1125       * @param array $sizes An array of int values that are the pixel sizes for avatars.
1126       *                     Default `[ 24, 48, 96 ]`.
1127       */
1128      return apply_filters( 'rest_avatar_sizes', array( 24, 48, 96 ) );
1129  }
1130  
1131  /**
1132   * Validate a value based on a schema.
1133   *
1134   * @since 4.7.0
1135   *
1136   * @param mixed  $value The value to validate.
1137   * @param array  $args  Schema array to use for validation.
1138   * @param string $param The parameter name, used in error messages.
1139   * @return true|WP_Error
1140   */
1141  function rest_validate_value_from_schema( $value, $args, $param = '' ) {
1142      if ( 'array' === $args['type'] ) {
1143          if ( ! is_null( $value ) ) {
1144              $value = wp_parse_list( $value );
1145          }
1146          if ( ! wp_is_numeric_array( $value ) ) {
1147              /* translators: 1: parameter, 2: type name */
1148              return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'array' ) );
1149          }
1150          foreach ( $value as $index => $v ) {
1151              $is_valid = rest_validate_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' );
1152              if ( is_wp_error( $is_valid ) ) {
1153                  return $is_valid;
1154              }
1155          }
1156      }
1157  
1158      if ( 'object' === $args['type'] ) {
1159          if ( $value instanceof stdClass ) {
1160              $value = (array) $value;
1161          }
1162          if ( ! is_array( $value ) ) {
1163              /* translators: 1: parameter, 2: type name */
1164              return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'object' ) );
1165          }
1166  
1167          foreach ( $value as $property => $v ) {
1168              if ( isset( $args['properties'][ $property ] ) ) {
1169                  $is_valid = rest_validate_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' );
1170                  if ( is_wp_error( $is_valid ) ) {
1171                      return $is_valid;
1172                  }
1173              } elseif ( isset( $args['additionalProperties'] ) && false === $args['additionalProperties'] ) {
1174                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not a valid property of Object.' ), $property ) );
1175              }
1176          }
1177      }
1178  
1179      if ( ! empty( $args['enum'] ) ) {
1180          if ( ! in_array( $value, $args['enum'], true ) ) {
1181              /* translators: 1: parameter, 2: list of valid values */
1182              return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not one of %2$s.' ), $param, implode( ', ', $args['enum'] ) ) );
1183          }
1184      }
1185  
1186      if ( in_array( $args['type'], array( 'integer', 'number' ) ) && ! is_numeric( $value ) ) {
1187          /* translators: 1: parameter, 2: type name */
1188          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, $args['type'] ) );
1189      }
1190  
1191      if ( 'integer' === $args['type'] && round( floatval( $value ) ) !== floatval( $value ) ) {
1192          /* translators: 1: parameter, 2: type name */
1193          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'integer' ) );
1194      }
1195  
1196      if ( 'boolean' === $args['type'] && ! rest_is_boolean( $value ) ) {
1197          /* translators: 1: parameter, 2: type name */
1198          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $value, 'boolean' ) );
1199      }
1200  
1201      if ( 'string' === $args['type'] && ! is_string( $value ) ) {
1202          /* translators: 1: parameter, 2: type name */
1203          return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
1204      }
1205  
1206      if ( isset( $args['format'] ) ) {
1207          switch ( $args['format'] ) {
1208              case 'date-time':
1209                  if ( ! rest_parse_date( $value ) ) {
1210                      return new WP_Error( 'rest_invalid_date', __( 'Invalid date.' ) );
1211                  }
1212                  break;
1213  
1214              case 'email':
1215                  if ( ! is_email( $value ) ) {
1216                      return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ) );
1217                  }
1218                  break;
1219              case 'ip':
1220                  if ( ! rest_is_ip_address( $value ) ) {
1221                      /* translators: %s: IP address */
1222                      return new WP_Error( 'rest_invalid_param', sprintf( __( '%s is not a valid IP address.' ), $value ) );
1223                  }
1224                  break;
1225          }
1226      }
1227  
1228      if ( in_array( $args['type'], array( 'number', 'integer' ), true ) && ( isset( $args['minimum'] ) || isset( $args['maximum'] ) ) ) {
1229          if ( isset( $args['minimum'] ) && ! isset( $args['maximum'] ) ) {
1230              if ( ! empty( $args['exclusiveMinimum'] ) && $value <= $args['minimum'] ) {
1231                  /* translators: 1: parameter, 2: minimum number */
1232                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d' ), $param, $args['minimum'] ) );
1233              } elseif ( empty( $args['exclusiveMinimum'] ) && $value < $args['minimum'] ) {
1234                  /* translators: 1: parameter, 2: minimum number */
1235                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than or equal to %2$d' ), $param, $args['minimum'] ) );
1236              }
1237          } elseif ( isset( $args['maximum'] ) && ! isset( $args['minimum'] ) ) {
1238              if ( ! empty( $args['exclusiveMaximum'] ) && $value >= $args['maximum'] ) {
1239                  /* translators: 1: parameter, 2: maximum number */
1240                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d' ), $param, $args['maximum'] ) );
1241              } elseif ( empty( $args['exclusiveMaximum'] ) && $value > $args['maximum'] ) {
1242                  /* translators: 1: parameter, 2: maximum number */
1243                  return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than or equal to %2$d' ), $param, $args['maximum'] ) );
1244              }
1245          } elseif ( isset( $args['maximum'] ) && isset( $args['minimum'] ) ) {
1246              if ( ! empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
1247                  if ( $value >= $args['maximum'] || $value <= $args['minimum'] ) {
1248                      /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1249                      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'] ) );
1250                  }
1251              } elseif ( empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
1252                  if ( $value >= $args['maximum'] || $value < $args['minimum'] ) {
1253                      /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1254                      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'] ) );
1255                  }
1256              } elseif ( ! empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
1257                  if ( $value > $args['maximum'] || $value <= $args['minimum'] ) {
1258                      /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1259                      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'] ) );
1260                  }
1261              } elseif ( empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
1262                  if ( $value > $args['maximum'] || $value < $args['minimum'] ) {
1263                      /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1264                      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'] ) );
1265                  }
1266              }
1267          }
1268      }
1269  
1270      return true;
1271  }
1272  
1273  /**
1274   * Sanitize a value based on a schema.
1275   *
1276   * @since 4.7.0
1277   *
1278   * @param mixed $value The value to sanitize.
1279   * @param array $args  Schema array to use for sanitization.
1280   * @return true|WP_Error
1281   */
1282  function rest_sanitize_value_from_schema( $value, $args ) {
1283      if ( 'array' === $args['type'] ) {
1284          if ( empty( $args['items'] ) ) {
1285              return (array) $value;
1286          }
1287          $value = wp_parse_list( $value );
1288          foreach ( $value as $index => $v ) {
1289              $value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'] );
1290          }
1291          // Normalize to numeric array so nothing unexpected
1292          // is in the keys.
1293          $value = array_values( $value );
1294          return $value;
1295      }
1296  
1297      if ( 'object' === $args['type'] ) {
1298          if ( $value instanceof stdClass ) {
1299              $value = (array) $value;
1300          }
1301          if ( ! is_array( $value ) ) {
1302              return array();
1303          }
1304  
1305          foreach ( $value as $property => $v ) {
1306              if ( isset( $args['properties'][ $property ] ) ) {
1307                  $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['properties'][ $property ] );
1308              } elseif ( isset( $args['additionalProperties'] ) && false === $args['additionalProperties'] ) {
1309                  unset( $value[ $property ] );
1310              }
1311          }
1312  
1313          return $value;
1314      }
1315  
1316      if ( 'integer' === $args['type'] ) {
1317          return (int) $value;
1318      }
1319  
1320      if ( 'number' === $args['type'] ) {
1321          return (float) $value;
1322      }
1323  
1324      if ( 'boolean' === $args['type'] ) {
1325          return rest_sanitize_boolean( $value );
1326      }
1327  
1328      if ( isset( $args['format'] ) ) {
1329          switch ( $args['format'] ) {
1330              case 'date-time':
1331                  return sanitize_text_field( $value );
1332  
1333              case 'email':
1334                  /*
1335                   * sanitize_email() validates, which would be unexpected.
1336                   */
1337                  return sanitize_text_field( $value );
1338  
1339              case 'uri':
1340                  return esc_url_raw( $value );
1341  
1342              case 'ip':
1343                  return sanitize_text_field( $value );
1344          }
1345      }
1346  
1347      if ( 'string' === $args['type'] ) {
1348          return strval( $value );
1349      }
1350  
1351      return $value;
1352  }
1353  
1354  /**
1355   * Append result of internal request to REST API for purpose of preloading data to be attached to a page.
1356   * Expected to be called in the context of `array_reduce`.
1357   *
1358   * @since 5.0.0
1359   *
1360   * @param  array  $memo Reduce accumulator.
1361   * @param  string $path REST API path to preload.
1362   * @return array        Modified reduce accumulator.
1363   */
1364  function rest_preload_api_request( $memo, $path ) {
1365      // array_reduce() doesn't support passing an array in PHP 5.2, so we need to make sure we start with one.
1366      if ( ! is_array( $memo ) ) {
1367          $memo = array();
1368      }
1369  
1370      if ( empty( $path ) ) {
1371          return $memo;
1372      }
1373  
1374      $method = 'GET';
1375      if ( is_array( $path ) && 2 === count( $path ) ) {
1376          $method = end( $path );
1377          $path   = reset( $path );
1378  
1379          if ( ! in_array( $method, array( 'GET', 'OPTIONS' ), true ) ) {
1380              $method = 'GET';
1381          }
1382      }
1383  
1384      $path_parts = parse_url( $path );
1385      if ( false === $path_parts ) {
1386          return $memo;
1387      }
1388  
1389      $request = new WP_REST_Request( $method, $path_parts['path'] );
1390      if ( ! empty( $path_parts['query'] ) ) {
1391          parse_str( $path_parts['query'], $query_params );
1392          $request->set_query_params( $query_params );
1393      }
1394  
1395      $response = rest_do_request( $request );
1396      if ( 200 === $response->status ) {
1397          $server = rest_get_server();
1398          $data   = (array) $response->get_data();
1399          $links  = $server::get_compact_response_links( $response );
1400          if ( ! empty( $links ) ) {
1401              $data['_links'] = $links;
1402          }
1403  
1404          if ( 'OPTIONS' === $method ) {
1405              $response = rest_send_allow_header( $response, $server, $request );
1406  
1407              $memo[ $method ][ $path ] = array(
1408                  'body'    => $data,
1409                  'headers' => $response->headers,
1410              );
1411          } else {
1412              $memo[ $path ] = array(
1413                  'body'    => $data,
1414                  'headers' => $response->headers,
1415              );
1416          }
1417      }
1418  
1419      return $memo;
1420  }


Generated: Fri Jul 19 01:00:04 2019 Cross-referenced by PHPXref 0.7.1