[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * REST API: WP_REST_Server class
   4   *
   5   * @package WordPress
   6   * @subpackage REST_API
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core class used to implement the WordPress REST API server.
  12   *
  13   * @since 4.4.0
  14   */
  15  class WP_REST_Server {
  16  
  17      /**
  18       * Alias for GET transport method.
  19       *
  20       * @since 4.4.0
  21       * @var string
  22       */
  23      const READABLE = 'GET';
  24  
  25      /**
  26       * Alias for POST transport method.
  27       *
  28       * @since 4.4.0
  29       * @var string
  30       */
  31      const CREATABLE = 'POST';
  32  
  33      /**
  34       * Alias for POST, PUT, PATCH transport methods together.
  35       *
  36       * @since 4.4.0
  37       * @var string
  38       */
  39      const EDITABLE = 'POST, PUT, PATCH';
  40  
  41      /**
  42       * Alias for DELETE transport method.
  43       *
  44       * @since 4.4.0
  45       * @var string
  46       */
  47      const DELETABLE = 'DELETE';
  48  
  49      /**
  50       * Alias for GET, POST, PUT, PATCH & DELETE transport methods together.
  51       *
  52       * @since 4.4.0
  53       * @var string
  54       */
  55      const ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE';
  56  
  57      /**
  58       * Namespaces registered to the server.
  59       *
  60       * @since 4.4.0
  61       * @var array
  62       */
  63      protected $namespaces = array();
  64  
  65      /**
  66       * Endpoints registered to the server.
  67       *
  68       * @since 4.4.0
  69       * @var array
  70       */
  71      protected $endpoints = array();
  72  
  73      /**
  74       * Options defined for the routes.
  75       *
  76       * @since 4.4.0
  77       * @var array
  78       */
  79      protected $route_options = array();
  80  
  81      /**
  82       * Caches embedded requests.
  83       *
  84       * @since 5.4.0
  85       * @var array
  86       */
  87      protected $embed_cache = array();
  88  
  89      /**
  90       * Instantiates the REST server.
  91       *
  92       * @since 4.4.0
  93       */
  94  	public function __construct() {
  95          $this->endpoints = array(
  96              // Meta endpoints.
  97              '/'         => array(
  98                  'callback' => array( $this, 'get_index' ),
  99                  'methods'  => 'GET',
 100                  'args'     => array(
 101                      'context' => array(
 102                          'default' => 'view',
 103                      ),
 104                  ),
 105              ),
 106              '/batch/v1' => array(
 107                  'callback' => array( $this, 'serve_batch_request_v1' ),
 108                  'methods'  => 'POST',
 109                  'args'     => array(
 110                      'validation' => array(
 111                          'type'    => 'string',
 112                          'enum'    => array( 'require-all-validate', 'normal' ),
 113                          'default' => 'normal',
 114                      ),
 115                      'requests'   => array(
 116                          'required' => true,
 117                          'type'     => 'array',
 118                          'maxItems' => $this->get_max_batch_size(),
 119                          'items'    => array(
 120                              'type'       => 'object',
 121                              'properties' => array(
 122                                  'method'  => array(
 123                                      'type'    => 'string',
 124                                      'enum'    => array( 'POST', 'PUT', 'PATCH', 'DELETE' ),
 125                                      'default' => 'POST',
 126                                  ),
 127                                  'path'    => array(
 128                                      'type'     => 'string',
 129                                      'required' => true,
 130                                  ),
 131                                  'body'    => array(
 132                                      'type'                 => 'object',
 133                                      'properties'           => array(),
 134                                      'additionalProperties' => true,
 135                                  ),
 136                                  'headers' => array(
 137                                      'type'                 => 'object',
 138                                      'properties'           => array(),
 139                                      'additionalProperties' => array(
 140                                          'type'  => array( 'string', 'array' ),
 141                                          'items' => array(
 142                                              'type' => 'string',
 143                                          ),
 144                                      ),
 145                                  ),
 146                              ),
 147                          ),
 148                      ),
 149                  ),
 150              ),
 151          );
 152      }
 153  
 154  
 155      /**
 156       * Checks the authentication headers if supplied.
 157       *
 158       * @since 4.4.0
 159       *
 160       * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful
 161       *                       or no authentication provided
 162       */
 163  	public function check_authentication() {
 164          /**
 165           * Filters REST authentication errors.
 166           *
 167           * This is used to pass a WP_Error from an authentication method back to
 168           * the API.
 169           *
 170           * Authentication methods should check first if they're being used, as
 171           * multiple authentication methods can be enabled on a site (cookies,
 172           * HTTP basic auth, OAuth). If the authentication method hooked in is
 173           * not actually being attempted, null should be returned to indicate
 174           * another authentication method should check instead. Similarly,
 175           * callbacks should ensure the value is `null` before checking for
 176           * errors.
 177           *
 178           * A WP_Error instance can be returned if an error occurs, and this should
 179           * match the format used by API methods internally (that is, the `status`
 180           * data should be used). A callback can return `true` to indicate that
 181           * the authentication method was used, and it succeeded.
 182           *
 183           * @since 4.4.0
 184           *
 185           * @param WP_Error|null|true $errors WP_Error if authentication error, null if authentication
 186           *                                   method wasn't used, true if authentication succeeded.
 187           */
 188          return apply_filters( 'rest_authentication_errors', null );
 189      }
 190  
 191      /**
 192       * Converts an error to a response object.
 193       *
 194       * This iterates over all error codes and messages to change it into a flat
 195       * array. This enables simpler client behaviour, as it is represented as a
 196       * list in JSON rather than an object/map.
 197       *
 198       * @since 4.4.0
 199       *
 200       * @param WP_Error $error WP_Error instance.
 201       * @return WP_REST_Response List of associative arrays with code and message keys.
 202       */
 203  	protected function error_to_response( $error ) {
 204          $error_data = $error->get_error_data();
 205  
 206          if ( is_array( $error_data ) && isset( $error_data['status'] ) ) {
 207              $status = $error_data['status'];
 208          } else {
 209              $status = 500;
 210          }
 211  
 212          $errors = array();
 213  
 214          foreach ( (array) $error->errors as $code => $messages ) {
 215              foreach ( (array) $messages as $message ) {
 216                  $errors[] = array(
 217                      'code'    => $code,
 218                      'message' => $message,
 219                      'data'    => $error->get_error_data( $code ),
 220                  );
 221              }
 222          }
 223  
 224          $data = $errors[0];
 225          if ( count( $errors ) > 1 ) {
 226              // Remove the primary error.
 227              array_shift( $errors );
 228              $data['additional_errors'] = $errors;
 229          }
 230  
 231          $response = new WP_REST_Response( $data, $status );
 232  
 233          return $response;
 234      }
 235  
 236      /**
 237       * Retrieves an appropriate error representation in JSON.
 238       *
 239       * Note: This should only be used in WP_REST_Server::serve_request(), as it
 240       * cannot handle WP_Error internally. All callbacks and other internal methods
 241       * should instead return a WP_Error with the data set to an array that includes
 242       * a 'status' key, with the value being the HTTP status to send.
 243       *
 244       * @since 4.4.0
 245       *
 246       * @param string $code    WP_Error-style code.
 247       * @param string $message Human-readable message.
 248       * @param int    $status  Optional. HTTP status code to send. Default null.
 249       * @return string JSON representation of the error
 250       */
 251  	protected function json_error( $code, $message, $status = null ) {
 252          if ( $status ) {
 253              $this->set_status( $status );
 254          }
 255  
 256          $error = compact( 'code', 'message' );
 257  
 258          return wp_json_encode( $error );
 259      }
 260  
 261      /**
 262       * Handles serving a REST API request.
 263       *
 264       * Matches the current server URI to a route and runs the first matching
 265       * callback then outputs a JSON representation of the returned value.
 266       *
 267       * @since 4.4.0
 268       *
 269       * @see WP_REST_Server::dispatch()
 270       *
 271       * @global WP_User $current_user The currently authenticated user.
 272       *
 273       * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
 274       *                     Default null.
 275       * @return null|false Null if not served and a HEAD request, false otherwise.
 276       */
 277  	public function serve_request( $path = null ) {
 278          /* @var WP_User|null $current_user */
 279          global $current_user;
 280  
 281          if ( $current_user instanceof WP_User && ! $current_user->exists() ) {
 282              /*
 283               * If there is no current user authenticated via other means, clear
 284               * the cached lack of user, so that an authenticate check can set it
 285               * properly.
 286               *
 287               * This is done because for authentications such as Application
 288               * Passwords, we don't want it to be accepted unless the current HTTP
 289               * request is a REST API request, which can't always be identified early
 290               * enough in evaluation.
 291               */
 292              $current_user = null;
 293          }
 294  
 295          $content_type = isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json';
 296          $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
 297          $this->send_header( 'X-Robots-Tag', 'noindex' );
 298  
 299          $api_root = get_rest_url();
 300          if ( ! empty( $api_root ) ) {
 301              $this->send_header( 'Link', '<' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"' );
 302          }
 303  
 304          /*
 305           * Mitigate possible JSONP Flash attacks.
 306           *
 307           * https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
 308           */
 309          $this->send_header( 'X-Content-Type-Options', 'nosniff' );
 310          $expose_headers = array( 'X-WP-Total', 'X-WP-TotalPages', 'Link' );
 311  
 312          /**
 313           * Filters the list of response headers that are exposed to CORS requests.
 314           *
 315           * @since 5.5.0
 316           *
 317           * @param string[] $expose_headers The list of headers to expose.
 318           */
 319          $expose_headers = apply_filters( 'rest_exposed_cors_headers', $expose_headers );
 320  
 321          $this->send_header( 'Access-Control-Expose-Headers', implode( ', ', $expose_headers ) );
 322  
 323          $allow_headers = array(
 324              'Authorization',
 325              'X-WP-Nonce',
 326              'Content-Disposition',
 327              'Content-MD5',
 328              'Content-Type',
 329          );
 330  
 331          /**
 332           * Filters the list of request headers that are allowed for CORS requests.
 333           *
 334           * The allowed headers are passed to the browser to specify which
 335           * headers can be passed to the REST API. By default, we allow the
 336           * Content-* headers needed to upload files to the media endpoints.
 337           * As well as the Authorization and Nonce headers for allowing authentication.
 338           *
 339           * @since 5.5.0
 340           *
 341           * @param string[] $allow_headers The list of headers to allow.
 342           */
 343          $allow_headers = apply_filters( 'rest_allowed_cors_headers', $allow_headers );
 344  
 345          $this->send_header( 'Access-Control-Allow-Headers', implode( ', ', $allow_headers ) );
 346  
 347          /**
 348           * Send nocache headers on authenticated requests.
 349           *
 350           * @since 4.4.0
 351           *
 352           * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
 353           */
 354          $send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
 355          if ( $send_no_cache_headers ) {
 356              foreach ( wp_get_nocache_headers() as $header => $header_value ) {
 357                  if ( empty( $header_value ) ) {
 358                      $this->remove_header( $header );
 359                  } else {
 360                      $this->send_header( $header, $header_value );
 361                  }
 362              }
 363          }
 364  
 365          /**
 366           * Filters whether the REST API is enabled.
 367           *
 368           * @since 4.4.0
 369           * @deprecated 4.7.0 Use the {@see 'rest_authentication_errors'} filter to
 370           *                   restrict access to the REST API.
 371           *
 372           * @param bool $rest_enabled Whether the REST API is enabled. Default true.
 373           */
 374          apply_filters_deprecated(
 375              'rest_enabled',
 376              array( true ),
 377              '4.7.0',
 378              'rest_authentication_errors',
 379              sprintf(
 380                  /* translators: %s: rest_authentication_errors */
 381                  __( 'The REST API can no longer be completely disabled, the %s filter can be used to restrict access to the API, instead.' ),
 382                  'rest_authentication_errors'
 383              )
 384          );
 385  
 386          /**
 387           * Filters whether jsonp is enabled.
 388           *
 389           * @since 4.4.0
 390           *
 391           * @param bool $jsonp_enabled Whether jsonp is enabled. Default true.
 392           */
 393          $jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
 394  
 395          $jsonp_callback = null;
 396  
 397          if ( isset( $_GET['_jsonp'] ) ) {
 398              if ( ! $jsonp_enabled ) {
 399                  echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
 400                  return false;
 401              }
 402  
 403              $jsonp_callback = $_GET['_jsonp'];
 404              if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
 405                  echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 );
 406                  return false;
 407              }
 408          }
 409  
 410          if ( empty( $path ) ) {
 411              if ( isset( $_SERVER['PATH_INFO'] ) ) {
 412                  $path = $_SERVER['PATH_INFO'];
 413              } else {
 414                  $path = '/';
 415              }
 416          }
 417  
 418          $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
 419  
 420          $request->set_query_params( wp_unslash( $_GET ) );
 421          $request->set_body_params( wp_unslash( $_POST ) );
 422          $request->set_file_params( $_FILES );
 423          $request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) );
 424          $request->set_body( self::get_raw_data() );
 425  
 426          /*
 427           * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
 428           * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
 429           * header.
 430           */
 431          if ( isset( $_GET['_method'] ) ) {
 432              $request->set_method( $_GET['_method'] );
 433          } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
 434              $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
 435          }
 436  
 437          $result = $this->check_authentication();
 438  
 439          if ( ! is_wp_error( $result ) ) {
 440              $result = $this->dispatch( $request );
 441          }
 442  
 443          // Normalize to either WP_Error or WP_REST_Response...
 444          $result = rest_ensure_response( $result );
 445  
 446          // ...then convert WP_Error across.
 447          if ( is_wp_error( $result ) ) {
 448              $result = $this->error_to_response( $result );
 449          }
 450  
 451          /**
 452           * Filters the REST API response.
 453           *
 454           * Allows modification of the response before returning.
 455           *
 456           * @since 4.4.0
 457           * @since 4.5.0 Applied to embedded responses.
 458           *
 459           * @param WP_HTTP_Response $result  Result to send to the client. Usually a `WP_REST_Response`.
 460           * @param WP_REST_Server   $this    Server instance.
 461           * @param WP_REST_Request  $request Request used to generate the response.
 462           */
 463          $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
 464  
 465          // Wrap the response in an envelope if asked for.
 466          if ( isset( $_GET['_envelope'] ) ) {
 467              $result = $this->envelope_response( $result, isset( $_GET['_embed'] ) );
 468          }
 469  
 470          // Send extra data from response objects.
 471          $headers = $result->get_headers();
 472          $this->send_headers( $headers );
 473  
 474          $code = $result->get_status();
 475          $this->set_status( $code );
 476  
 477          /**
 478           * Filters whether the REST API request has already been served.
 479           *
 480           * Allow sending the request manually - by returning true, the API result
 481           * will not be sent to the client.
 482           *
 483           * @since 4.4.0
 484           *
 485           * @param bool             $served  Whether the request has already been served.
 486           *                                           Default false.
 487           * @param WP_HTTP_Response $result  Result to send to the client. Usually a `WP_REST_Response`.
 488           * @param WP_REST_Request  $request Request used to generate the response.
 489           * @param WP_REST_Server   $this    Server instance.
 490           */
 491          $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
 492  
 493          if ( ! $served ) {
 494              if ( 'HEAD' === $request->get_method() ) {
 495                  return null;
 496              }
 497  
 498              // Embed links inside the request.
 499              $embed  = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
 500              $result = $this->response_to_data( $result, $embed );
 501  
 502              /**
 503               * Filters the REST API response.
 504               *
 505               * Allows modification of the response data after inserting
 506               * embedded data (if any) and before echoing the response data.
 507               *
 508               * @since 4.8.1
 509               *
 510               * @param array            $result  Response data to send to the client.
 511               * @param WP_REST_Server   $this    Server instance.
 512               * @param WP_REST_Request  $request Request used to generate the response.
 513               */
 514              $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
 515  
 516              // The 204 response shouldn't have a body.
 517              if ( 204 === $code || null === $result ) {
 518                  return null;
 519              }
 520  
 521              $result = wp_json_encode( $result );
 522  
 523              $json_error_message = $this->get_json_last_error();
 524  
 525              if ( $json_error_message ) {
 526                  $json_error_obj = new WP_Error(
 527                      'rest_encode_error',
 528                      $json_error_message,
 529                      array( 'status' => 500 )
 530                  );
 531  
 532                  $result = $this->error_to_response( $json_error_obj );
 533                  $result = wp_json_encode( $result->data[0] );
 534              }
 535  
 536              if ( $jsonp_callback ) {
 537                  // Prepend '/**/' to mitigate possible JSONP Flash attacks.
 538                  // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
 539                  echo '/**/' . $jsonp_callback . '(' . $result . ')';
 540              } else {
 541                  echo $result;
 542              }
 543          }
 544  
 545          return null;
 546      }
 547  
 548      /**
 549       * Converts a response to data to send.
 550       *
 551       * @since 4.4.0
 552       * @since 5.4.0 The $embed parameter can now contain a list of link relations to include.
 553       *
 554       * @param WP_REST_Response $response Response object.
 555       * @param bool|string[]    $embed    Whether to embed all links, a filtered list of link relations, or no links.
 556       * @return array {
 557       *     Data with sub-requests embedded.
 558       *
 559       *     @type array $_links    Links.
 560       *     @type array $_embedded Embedded objects.
 561       * }
 562       */
 563  	public function response_to_data( $response, $embed ) {
 564          $data  = $response->get_data();
 565          $links = self::get_compact_response_links( $response );
 566  
 567          if ( ! empty( $links ) ) {
 568              // Convert links to part of the data.
 569              $data['_links'] = $links;
 570          }
 571  
 572          if ( $embed ) {
 573              $this->embed_cache = array();
 574              // Determine if this is a numeric array.
 575              if ( wp_is_numeric_array( $data ) ) {
 576                  foreach ( $data as $key => $item ) {
 577                      $data[ $key ] = $this->embed_links( $item, $embed );
 578                  }
 579              } else {
 580                  $data = $this->embed_links( $data, $embed );
 581              }
 582              $this->embed_cache = array();
 583          }
 584  
 585          return $data;
 586      }
 587  
 588      /**
 589       * Retrieves links from a response.
 590       *
 591       * Extracts the links from a response into a structured hash, suitable for
 592       * direct output.
 593       *
 594       * @since 4.4.0
 595       *
 596       * @param WP_REST_Response $response Response to extract links from.
 597       * @return array Map of link relation to list of link hashes.
 598       */
 599  	public static function get_response_links( $response ) {
 600          $links = $response->get_links();
 601  
 602          if ( empty( $links ) ) {
 603              return array();
 604          }
 605  
 606          // Convert links to part of the data.
 607          $data = array();
 608          foreach ( $links as $rel => $items ) {
 609              $data[ $rel ] = array();
 610  
 611              foreach ( $items as $item ) {
 612                  $attributes         = $item['attributes'];
 613                  $attributes['href'] = $item['href'];
 614                  $data[ $rel ][]     = $attributes;
 615              }
 616          }
 617  
 618          return $data;
 619      }
 620  
 621      /**
 622       * Retrieves the CURIEs (compact URIs) used for relations.
 623       *
 624       * Extracts the links from a response into a structured hash, suitable for
 625       * direct output.
 626       *
 627       * @since 4.5.0
 628       *
 629       * @param WP_REST_Response $response Response to extract links from.
 630       * @return array Map of link relation to list of link hashes.
 631       */
 632  	public static function get_compact_response_links( $response ) {
 633          $links = self::get_response_links( $response );
 634  
 635          if ( empty( $links ) ) {
 636              return array();
 637          }
 638  
 639          $curies      = $response->get_curies();
 640          $used_curies = array();
 641  
 642          foreach ( $links as $rel => $items ) {
 643  
 644              // Convert $rel URIs to their compact versions if they exist.
 645              foreach ( $curies as $curie ) {
 646                  $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
 647                  if ( strpos( $rel, $href_prefix ) !== 0 ) {
 648                      continue;
 649                  }
 650  
 651                  // Relation now changes from '$uri' to '$curie:$relation'.
 652                  $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
 653                  preg_match( '!' . $rel_regex . '!', $rel, $matches );
 654                  if ( $matches ) {
 655                      $new_rel                       = $curie['name'] . ':' . $matches[1];
 656                      $used_curies[ $curie['name'] ] = $curie;
 657                      $links[ $new_rel ]             = $items;
 658                      unset( $links[ $rel ] );
 659                      break;
 660                  }
 661              }
 662          }
 663  
 664          // Push the curies onto the start of the links array.
 665          if ( $used_curies ) {
 666              $links['curies'] = array_values( $used_curies );
 667          }
 668  
 669          return $links;
 670      }
 671  
 672      /**
 673       * Embeds the links from the data into the request.
 674       *
 675       * @since 4.4.0
 676       * @since 5.4.0 The $embed parameter can now contain a list of link relations to include.
 677       *
 678       * @param array         $data  Data from the request.
 679       * @param bool|string[] $embed Whether to embed all links or a filtered list of link relations.
 680       * @return array {
 681       *     Data with sub-requests embedded.
 682       *
 683       *     @type array $_links    Links.
 684       *     @type array $_embedded Embedded objects.
 685       * }
 686       */
 687  	protected function embed_links( $data, $embed = true ) {
 688          if ( empty( $data['_links'] ) ) {
 689              return $data;
 690          }
 691  
 692          $embedded = array();
 693  
 694          foreach ( $data['_links'] as $rel => $links ) {
 695              // If a list of relations was specified, and the link relation
 696              // is not in the list of allowed relations, don't process the link.
 697              if ( is_array( $embed ) && ! in_array( $rel, $embed, true ) ) {
 698                  continue;
 699              }
 700  
 701              $embeds = array();
 702  
 703              foreach ( $links as $item ) {
 704                  // Determine if the link is embeddable.
 705                  if ( empty( $item['embeddable'] ) ) {
 706                      // Ensure we keep the same order.
 707                      $embeds[] = array();
 708                      continue;
 709                  }
 710  
 711                  if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) {
 712                      // Run through our internal routing and serve.
 713                      $request = WP_REST_Request::from_url( $item['href'] );
 714                      if ( ! $request ) {
 715                          $embeds[] = array();
 716                          continue;
 717                      }
 718  
 719                      // Embedded resources get passed context=embed.
 720                      if ( empty( $request['context'] ) ) {
 721                          $request['context'] = 'embed';
 722                      }
 723  
 724                      $response = $this->dispatch( $request );
 725  
 726                      /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
 727                      $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
 728  
 729                      $this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false );
 730                  }
 731  
 732                  $embeds[] = $this->embed_cache[ $item['href'] ];
 733              }
 734  
 735              // Determine if any real links were found.
 736              $has_links = count( array_filter( $embeds ) );
 737  
 738              if ( $has_links ) {
 739                  $embedded[ $rel ] = $embeds;
 740              }
 741          }
 742  
 743          if ( ! empty( $embedded ) ) {
 744              $data['_embedded'] = $embedded;
 745          }
 746  
 747          return $data;
 748      }
 749  
 750      /**
 751       * Wraps the response in an envelope.
 752       *
 753       * The enveloping technique is used to work around browser/client
 754       * compatibility issues. Essentially, it converts the full HTTP response to
 755       * data instead.
 756       *
 757       * @since 4.4.0
 758       *
 759       * @param WP_REST_Response $response Response object.
 760       * @param bool             $embed    Whether links should be embedded.
 761       * @return WP_REST_Response New response with wrapped data
 762       */
 763  	public function envelope_response( $response, $embed ) {
 764          $envelope = array(
 765              'body'    => $this->response_to_data( $response, $embed ),
 766              'status'  => $response->get_status(),
 767              'headers' => $response->get_headers(),
 768          );
 769  
 770          /**
 771           * Filters the enveloped form of a response.
 772           *
 773           * @since 4.4.0
 774           *
 775           * @param array            $envelope Envelope data.
 776           * @param WP_REST_Response $response Original response data.
 777           */
 778          $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
 779  
 780          // Ensure it's still a response and return.
 781          return rest_ensure_response( $envelope );
 782      }
 783  
 784      /**
 785       * Registers a route to the server.
 786       *
 787       * @since 4.4.0
 788       *
 789       * @param string $namespace  Namespace.
 790       * @param string $route      The REST route.
 791       * @param array  $route_args Route arguments.
 792       * @param bool   $override   Optional. Whether the route should be overridden if it already exists.
 793       *                           Default false.
 794       */
 795  	public function register_route( $namespace, $route, $route_args, $override = false ) {
 796          if ( ! isset( $this->namespaces[ $namespace ] ) ) {
 797              $this->namespaces[ $namespace ] = array();
 798  
 799              $this->register_route(
 800                  $namespace,
 801                  '/' . $namespace,
 802                  array(
 803                      array(
 804                          'methods'  => self::READABLE,
 805                          'callback' => array( $this, 'get_namespace_index' ),
 806                          'args'     => array(
 807                              'namespace' => array(
 808                                  'default' => $namespace,
 809                              ),
 810                              'context'   => array(
 811                                  'default' => 'view',
 812                              ),
 813                          ),
 814                      ),
 815                  )
 816              );
 817          }
 818  
 819          // Associative to avoid double-registration.
 820          $this->namespaces[ $namespace ][ $route ] = true;
 821          $route_args['namespace']                  = $namespace;
 822  
 823          if ( $override || empty( $this->endpoints[ $route ] ) ) {
 824              $this->endpoints[ $route ] = $route_args;
 825          } else {
 826              $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
 827          }
 828      }
 829  
 830      /**
 831       * Retrieves the route map.
 832       *
 833       * The route map is an associative array with path regexes as the keys. The
 834       * value is an indexed array with the callback function/method as the first
 835       * item, and a bitmask of HTTP methods as the second item (see the class
 836       * constants).
 837       *
 838       * Each route can be mapped to more than one callback by using an array of
 839       * the indexed arrays. This allows mapping e.g. GET requests to one callback
 840       * and POST requests to another.
 841       *
 842       * Note that the path regexes (array keys) must have @ escaped, as this is
 843       * used as the delimiter with preg_match()
 844       *
 845       * @since 4.4.0
 846       * @since 5.4.0 Add $namespace parameter.
 847       *
 848       * @param string $namespace Optionally, only return routes in the given namespace.
 849       * @return array `'/path/regex' => array( $callback, $bitmask )` or
 850       *               `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
 851       */
 852  	public function get_routes( $namespace = '' ) {
 853          $endpoints = $this->endpoints;
 854  
 855          if ( $namespace ) {
 856              $endpoints = wp_list_filter( $endpoints, array( 'namespace' => $namespace ) );
 857          }
 858  
 859          /**
 860           * Filters the array of available endpoints.
 861           *
 862           * @since 4.4.0
 863           *
 864           * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
 865           *                         to an array of callbacks for the endpoint. These take the format
 866           *                         `'/path/regex' => array( $callback, $bitmask )` or
 867           *                         `'/path/regex' => array( array( $callback, $bitmask ).
 868           */
 869          $endpoints = apply_filters( 'rest_endpoints', $endpoints );
 870  
 871          // Normalise the endpoints.
 872          $defaults = array(
 873              'methods'       => '',
 874              'accept_json'   => false,
 875              'accept_raw'    => false,
 876              'show_in_index' => true,
 877              'args'          => array(),
 878          );
 879  
 880          foreach ( $endpoints as $route => &$handlers ) {
 881  
 882              if ( isset( $handlers['callback'] ) ) {
 883                  // Single endpoint, add one deeper.
 884                  $handlers = array( $handlers );
 885              }
 886  
 887              if ( ! isset( $this->route_options[ $route ] ) ) {
 888                  $this->route_options[ $route ] = array();
 889              }
 890  
 891              foreach ( $handlers as $key => &$handler ) {
 892  
 893                  if ( ! is_numeric( $key ) ) {
 894                      // Route option, move it to the options.
 895                      $this->route_options[ $route ][ $key ] = $handler;
 896                      unset( $handlers[ $key ] );
 897                      continue;
 898                  }
 899  
 900                  $handler = wp_parse_args( $handler, $defaults );
 901  
 902                  // Allow comma-separated HTTP methods.
 903                  if ( is_string( $handler['methods'] ) ) {
 904                      $methods = explode( ',', $handler['methods'] );
 905                  } elseif ( is_array( $handler['methods'] ) ) {
 906                      $methods = $handler['methods'];
 907                  } else {
 908                      $methods = array();
 909                  }
 910  
 911                  $handler['methods'] = array();
 912  
 913                  foreach ( $methods as $method ) {
 914                      $method                        = strtoupper( trim( $method ) );
 915                      $handler['methods'][ $method ] = true;
 916                  }
 917              }
 918          }
 919  
 920          return $endpoints;
 921      }
 922  
 923      /**
 924       * Retrieves namespaces registered on the server.
 925       *
 926       * @since 4.4.0
 927       *
 928       * @return string[] List of registered namespaces.
 929       */
 930  	public function get_namespaces() {
 931          return array_keys( $this->namespaces );
 932      }
 933  
 934      /**
 935       * Retrieves specified options for a route.
 936       *
 937       * @since 4.4.0
 938       *
 939       * @param string $route Route pattern to fetch options for.
 940       * @return array|null Data as an associative array if found, or null if not found.
 941       */
 942  	public function get_route_options( $route ) {
 943          if ( ! isset( $this->route_options[ $route ] ) ) {
 944              return null;
 945          }
 946  
 947          return $this->route_options[ $route ];
 948      }
 949  
 950      /**
 951       * Matches the request to a callback and call it.
 952       *
 953       * @since 4.4.0
 954       *
 955       * @param WP_REST_Request $request Request to attempt dispatching.
 956       * @return WP_REST_Response Response returned by the callback.
 957       */
 958  	public function dispatch( $request ) {
 959          /**
 960           * Filters the pre-calculated result of a REST dispatch request.
 961           *
 962           * Allow hijacking the request before dispatching by returning a non-empty. The returned value
 963           * will be used to serve the request instead.
 964           *
 965           * @since 4.4.0
 966           *
 967           * @param mixed           $result  Response to replace the requested version with. Can be anything
 968           *                                 a normal endpoint can return, or null to not hijack the request.
 969           * @param WP_REST_Server  $this    Server instance.
 970           * @param WP_REST_Request $request Request used to generate the response.
 971           */
 972          $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
 973  
 974          if ( ! empty( $result ) ) {
 975              return $result;
 976          }
 977  
 978          $error   = null;
 979          $matched = $this->match_request_to_handler( $request );
 980  
 981          if ( is_wp_error( $matched ) ) {
 982              return $this->error_to_response( $matched );
 983          }
 984  
 985          list( $route, $handler ) = $matched;
 986  
 987          if ( ! is_callable( $handler['callback'] ) ) {
 988              $error = new WP_Error(
 989                  'rest_invalid_handler',
 990                  __( 'The handler for the route is invalid.' ),
 991                  array( 'status' => 500 )
 992              );
 993          }
 994  
 995          if ( ! is_wp_error( $error ) ) {
 996              $check_required = $request->has_valid_params();
 997              if ( is_wp_error( $check_required ) ) {
 998                  $error = $check_required;
 999              } else {
1000                  $check_sanitized = $request->sanitize_params();
1001                  if ( is_wp_error( $check_sanitized ) ) {
1002                      $error = $check_sanitized;
1003                  }
1004              }
1005          }
1006  
1007          return $this->respond_to_request( $request, $route, $handler, $error );
1008      }
1009  
1010      /**
1011       * Matches a request object to it's handler.
1012       *
1013       * @access private
1014       * @since 5.6.0
1015       *
1016       * @param WP_REST_Request $request The request object.
1017       * @return array|WP_Error The route and request handler on success or a WP_Error instance if no handler was found.
1018       */
1019  	protected function match_request_to_handler( $request ) {
1020          $method = $request->get_method();
1021          $path   = $request->get_route();
1022  
1023          $with_namespace = array();
1024  
1025          foreach ( $this->get_namespaces() as $namespace ) {
1026              if ( 0 === strpos( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) {
1027                  $with_namespace[] = $this->get_routes( $namespace );
1028              }
1029          }
1030  
1031          if ( $with_namespace ) {
1032              $routes = array_merge( ...$with_namespace );
1033          } else {
1034              $routes = $this->get_routes();
1035          }
1036  
1037          foreach ( $routes as $route => $handlers ) {
1038              $match = preg_match( '@^' . $route . '$@i', $path, $matches );
1039  
1040              if ( ! $match ) {
1041                  continue;
1042              }
1043  
1044              $args = array();
1045  
1046              foreach ( $matches as $param => $value ) {
1047                  if ( ! is_int( $param ) ) {
1048                      $args[ $param ] = $value;
1049                  }
1050              }
1051  
1052              foreach ( $handlers as $handler ) {
1053                  $callback = $handler['callback'];
1054                  $response = null;
1055  
1056                  // Fallback to GET method if no HEAD method is registered.
1057                  $checked_method = $method;
1058                  if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
1059                      $checked_method = 'GET';
1060                  }
1061                  if ( empty( $handler['methods'][ $checked_method ] ) ) {
1062                      continue;
1063                  }
1064  
1065                  if ( ! is_callable( $callback ) ) {
1066                      return array( $route, $handler );
1067                  }
1068  
1069                  $request->set_url_params( $args );
1070                  $request->set_attributes( $handler );
1071  
1072                  $defaults = array();
1073  
1074                  foreach ( $handler['args'] as $arg => $options ) {
1075                      if ( isset( $options['default'] ) ) {
1076                          $defaults[ $arg ] = $options['default'];
1077                      }
1078                  }
1079  
1080                  $request->set_default_params( $defaults );
1081  
1082                  return array( $route, $handler );
1083              }
1084          }
1085  
1086          return new WP_Error(
1087              'rest_no_route',
1088              __( 'No route was found matching the URL and request method.' ),
1089              array( 'status' => 404 )
1090          );
1091      }
1092  
1093      /**
1094       * Dispatches the request to the callback handler.
1095       *
1096       * @access private
1097       * @since 5.6.0
1098       *
1099       * @param WP_REST_Request $request  The request object.
1100       * @param array           $handler  The matched route handler.
1101       * @param string          $route    The matched route regex.
1102       * @param WP_Error|null   $response The current error object if any.
1103       *
1104       * @return WP_REST_Response
1105       */
1106  	protected function respond_to_request( $request, $route, $handler, $response ) {
1107          /**
1108           * Filters the response before executing any REST API callbacks.
1109           *
1110           * Allows plugins to perform additional validation after a
1111           * request is initialized and matched to a registered route,
1112           * but before it is executed.
1113           *
1114           * Note that this filter will not be called for requests that
1115           * fail to authenticate or match to a registered route.
1116           *
1117           * @since 4.7.0
1118           *
1119           * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. Usually a WP_REST_Response or WP_Error.
1120           * @param array                                            $handler  Route handler used for the request.
1121           * @param WP_REST_Request                                  $request  Request used to generate the response.
1122           */
1123          $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
1124  
1125          // Check permission specified on the route.
1126          if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) {
1127              $permission = call_user_func( $handler['permission_callback'], $request );
1128  
1129              if ( is_wp_error( $permission ) ) {
1130                  $response = $permission;
1131              } elseif ( false === $permission || null === $permission ) {
1132                  $response = new WP_Error(
1133                      'rest_forbidden',
1134                      __( 'Sorry, you are not allowed to do that.' ),
1135                      array( 'status' => rest_authorization_required_code() )
1136                  );
1137              }
1138          }
1139  
1140          if ( ! is_wp_error( $response ) ) {
1141              /**
1142               * Filters the REST dispatch request result.
1143               *
1144               * Allow plugins to override dispatching the request.
1145               *
1146               * @since 4.4.0
1147               * @since 4.5.0 Added `$route` and `$handler` parameters.
1148               *
1149               * @param mixed           $dispatch_result Dispatch result, will be used if not empty.
1150               * @param WP_REST_Request $request         Request used to generate the response.
1151               * @param string          $route           Route matched for the request.
1152               * @param array           $handler         Route handler used for the request.
1153               */
1154              $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
1155  
1156              // Allow plugins to halt the request via this filter.
1157              if ( null !== $dispatch_result ) {
1158                  $response = $dispatch_result;
1159              } else {
1160                  $response = call_user_func( $handler['callback'], $request );
1161              }
1162          }
1163  
1164          /**
1165           * Filters the response immediately after executing any REST API
1166           * callbacks.
1167           *
1168           * Allows plugins to perform any needed cleanup, for example,
1169           * to undo changes made during the {@see 'rest_request_before_callbacks'}
1170           * filter.
1171           *
1172           * Note that this filter will not be called for requests that
1173           * fail to authenticate or match to a registered route.
1174           *
1175           * Note that an endpoint's `permission_callback` can still be
1176           * called after this filter - see `rest_send_allow_header()`.
1177           *
1178           * @since 4.7.0
1179           *
1180           * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. Usually a WP_REST_Response or WP_Error.
1181           * @param array                                            $handler  Route handler used for the request.
1182           * @param WP_REST_Request                                  $request  Request used to generate the response.
1183           */
1184          $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
1185  
1186          if ( is_wp_error( $response ) ) {
1187              $response = $this->error_to_response( $response );
1188          } else {
1189              $response = rest_ensure_response( $response );
1190          }
1191  
1192          $response->set_matched_route( $route );
1193          $response->set_matched_handler( $handler );
1194  
1195          return $response;
1196      }
1197  
1198      /**
1199       * Returns if an error occurred during most recent JSON encode/decode.
1200       *
1201       * Strings to be translated will be in format like
1202       * "Encoding error: Maximum stack depth exceeded".
1203       *
1204       * @since 4.4.0
1205       *
1206       * @return bool|string Boolean false or string error message.
1207       */
1208  	protected function get_json_last_error() {
1209          $last_error_code = json_last_error();
1210  
1211          if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) {
1212              return false;
1213          }
1214  
1215          return json_last_error_msg();
1216      }
1217  
1218      /**
1219       * Retrieves the site index.
1220       *
1221       * This endpoint describes the capabilities of the site.
1222       *
1223       * @since 4.4.0
1224       *
1225       * @param array $request {
1226       *     Request.
1227       *
1228       *     @type string $context Context.
1229       * }
1230       * @return WP_REST_Response The API root index data.
1231       */
1232  	public function get_index( $request ) {
1233          // General site data.
1234          $available = array(
1235              'name'            => get_option( 'blogname' ),
1236              'description'     => get_option( 'blogdescription' ),
1237              'url'             => get_option( 'siteurl' ),
1238              'home'            => home_url(),
1239              'gmt_offset'      => get_option( 'gmt_offset' ),
1240              'timezone_string' => get_option( 'timezone_string' ),
1241              'namespaces'      => array_keys( $this->namespaces ),
1242              'authentication'  => array(),
1243              'routes'          => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
1244          );
1245  
1246          $response = new WP_REST_Response( $available );
1247  
1248          $response->add_link( 'help', 'http://v2.wp-api.org/' );
1249  
1250          /**
1251           * Filters the REST API root index data.
1252           *
1253           * This contains the data describing the API. This includes information
1254           * about supported authentication schemes, supported namespaces, routes
1255           * available on the API, and a small amount of data about the site.
1256           *
1257           * @since 4.4.0
1258           *
1259           * @param WP_REST_Response $response Response data.
1260           */
1261          return apply_filters( 'rest_index', $response );
1262      }
1263  
1264      /**
1265       * Retrieves the index for a namespace.
1266       *
1267       * @since 4.4.0
1268       *
1269       * @param WP_REST_Request $request REST request instance.
1270       * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
1271       *                                   WP_Error if the namespace isn't set.
1272       */
1273  	public function get_namespace_index( $request ) {
1274          $namespace = $request['namespace'];
1275  
1276          if ( ! isset( $this->namespaces[ $namespace ] ) ) {
1277              return new WP_Error(
1278                  'rest_invalid_namespace',
1279                  __( 'The specified namespace could not be found.' ),
1280                  array( 'status' => 404 )
1281              );
1282          }
1283  
1284          $routes    = $this->namespaces[ $namespace ];
1285          $endpoints = array_intersect_key( $this->get_routes(), $routes );
1286  
1287          $data     = array(
1288              'namespace' => $namespace,
1289              'routes'    => $this->get_data_for_routes( $endpoints, $request['context'] ),
1290          );
1291          $response = rest_ensure_response( $data );
1292  
1293          // Link to the root index.
1294          $response->add_link( 'up', rest_url( '/' ) );
1295  
1296          /**
1297           * Filters the namespace index data.
1298           *
1299           * This typically is just the route data for the namespace, but you can
1300           * add any data you'd like here.
1301           *
1302           * @since 4.4.0
1303           *
1304           * @param WP_REST_Response $response Response data.
1305           * @param WP_REST_Request  $request  Request data. The namespace is passed as the 'namespace' parameter.
1306           */
1307          return apply_filters( 'rest_namespace_index', $response, $request );
1308      }
1309  
1310      /**
1311       * Retrieves the publicly-visible data for routes.
1312       *
1313       * @since 4.4.0
1314       *
1315       * @param array  $routes  Routes to get data for.
1316       * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
1317       * @return array[] Route data to expose in indexes, keyed by route.
1318       */
1319  	public function get_data_for_routes( $routes, $context = 'view' ) {
1320          $available = array();
1321  
1322          // Find the available routes.
1323          foreach ( $routes as $route => $callbacks ) {
1324              $data = $this->get_data_for_route( $route, $callbacks, $context );
1325              if ( empty( $data ) ) {
1326                  continue;
1327              }
1328  
1329              /**
1330               * Filters the REST endpoint data.
1331               *
1332               * @since 4.4.0
1333               *
1334               * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
1335               */
1336              $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
1337          }
1338  
1339          /**
1340           * Filters the publicly-visible data for routes.
1341           *
1342           * This data is exposed on indexes and can be used by clients or
1343           * developers to investigate the site and find out how to use it. It
1344           * acts as a form of self-documentation.
1345           *
1346           * @since 4.4.0
1347           *
1348           * @param array[] $available Route data to expose in indexes, keyed by route.
1349           * @param array   $routes    Internal route data as an associative array.
1350           */
1351          return apply_filters( 'rest_route_data', $available, $routes );
1352      }
1353  
1354      /**
1355       * Retrieves publicly-visible data for the route.
1356       *
1357       * @since 4.4.0
1358       *
1359       * @param string $route     Route to get data for.
1360       * @param array  $callbacks Callbacks to convert to data.
1361       * @param string $context   Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
1362       * @return array|null Data for the route, or null if no publicly-visible data.
1363       */
1364  	public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
1365          $data = array(
1366              'namespace' => '',
1367              'methods'   => array(),
1368              'endpoints' => array(),
1369          );
1370  
1371          if ( isset( $this->route_options[ $route ] ) ) {
1372              $options = $this->route_options[ $route ];
1373  
1374              if ( isset( $options['namespace'] ) ) {
1375                  $data['namespace'] = $options['namespace'];
1376              }
1377  
1378              if ( isset( $options['schema'] ) && 'help' === $context ) {
1379                  $data['schema'] = call_user_func( $options['schema'] );
1380              }
1381          }
1382  
1383          $allowed_schema_keywords = array_flip( rest_get_allowed_schema_keywords() );
1384  
1385          $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
1386  
1387          foreach ( $callbacks as $callback ) {
1388              // Skip to the next route if any callback is hidden.
1389              if ( empty( $callback['show_in_index'] ) ) {
1390                  continue;
1391              }
1392  
1393              $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
1394              $endpoint_data   = array(
1395                  'methods' => array_keys( $callback['methods'] ),
1396              );
1397  
1398              if ( isset( $callback['args'] ) ) {
1399                  $endpoint_data['args'] = array();
1400  
1401                  foreach ( $callback['args'] as $key => $opts ) {
1402                      $arg_data             = array_intersect_key( $opts, $allowed_schema_keywords );
1403                      $arg_data['required'] = ! empty( $opts['required'] );
1404  
1405                      $endpoint_data['args'][ $key ] = $arg_data;
1406                  }
1407              }
1408  
1409              $data['endpoints'][] = $endpoint_data;
1410  
1411              // For non-variable routes, generate links.
1412              if ( strpos( $route, '{' ) === false ) {
1413                  $data['_links'] = array(
1414                      'self' => array(
1415                          array(
1416                              'href' => rest_url( $route ),
1417                          ),
1418                      ),
1419                  );
1420              }
1421          }
1422  
1423          if ( empty( $data['methods'] ) ) {
1424              // No methods supported, hide the route.
1425              return null;
1426          }
1427  
1428          return $data;
1429      }
1430  
1431      /**
1432       * Gets the maximum number of requests that can be included in a batch.
1433       *
1434       * @since 5.6.0
1435       *
1436       * @return int The maximum requests.
1437       */
1438  	protected function get_max_batch_size() {
1439          /**
1440           * Filters the maximum number of requests that can be included in a batch.
1441           *
1442           * @param int $max_size The maximum size.
1443           */
1444          return apply_filters( 'rest_get_max_batch_size', 25 );
1445      }
1446  
1447      /**
1448       * Serves the batch/v1 request.
1449       *
1450       * @since 5.6.0
1451       *
1452       * @param WP_REST_Request $batch_request The batch request object.
1453       * @return WP_REST_Response The generated response object.
1454       */
1455  	public function serve_batch_request_v1( WP_REST_Request $batch_request ) {
1456          $requests = array();
1457  
1458          foreach ( $batch_request['requests'] as $args ) {
1459              $parsed_url = wp_parse_url( $args['path'] );
1460  
1461              if ( false === $parsed_url ) {
1462                  $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) );
1463  
1464                  continue;
1465              }
1466  
1467              $single_request = new WP_REST_Request( isset( $args['method'] ) ? $args['method'] : 'POST', $parsed_url['path'] );
1468  
1469              if ( ! empty( $parsed_url['query'] ) ) {
1470                  $query_args = null; // Satisfy linter.
1471                  wp_parse_str( $parsed_url['query'], $query_args );
1472                  $single_request->set_query_params( $query_args );
1473              }
1474  
1475              if ( ! empty( $args['body'] ) ) {
1476                  $single_request->set_body_params( $args['body'] );
1477              }
1478  
1479              if ( ! empty( $args['headers'] ) ) {
1480                  $single_request->set_headers( $args['headers'] );
1481              }
1482  
1483              $requests[] = $single_request;
1484          }
1485  
1486          $matches    = array();
1487          $validation = array();
1488          $has_error  = false;
1489  
1490          foreach ( $requests as $single_request ) {
1491              $match     = $this->match_request_to_handler( $single_request );
1492              $matches[] = $match;
1493              $error     = null;
1494  
1495              if ( is_wp_error( $match ) ) {
1496                  $error = $match;
1497              }
1498  
1499              if ( ! $error ) {
1500                  list( $route, $handler ) = $match;
1501  
1502                  if ( isset( $handler['allow_batch'] ) ) {
1503                      $allow_batch = $handler['allow_batch'];
1504                  } else {
1505                      $route_options = $this->get_route_options( $route );
1506                      $allow_batch   = isset( $route_options['allow_batch'] ) ? $route_options['allow_batch'] : false;
1507                  }
1508  
1509                  if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) {
1510                      $error = new WP_Error(
1511                          'rest_batch_not_allowed',
1512                          __( 'The requested route does not support batch requests.' ),
1513                          array( 'status' => 400 )
1514                      );
1515                  }
1516              }
1517  
1518              if ( ! $error ) {
1519                  $check_required = $single_request->has_valid_params();
1520                  if ( is_wp_error( $check_required ) ) {
1521                      $error = $check_required;
1522                  }
1523              }
1524  
1525              if ( ! $error ) {
1526                  $check_sanitized = $single_request->sanitize_params();
1527                  if ( is_wp_error( $check_sanitized ) ) {
1528                      $error = $check_sanitized;
1529                  }
1530              }
1531  
1532              if ( $error ) {
1533                  $has_error    = true;
1534                  $validation[] = $error;
1535              } else {
1536                  $validation[] = true;
1537              }
1538          }
1539  
1540          $responses = array();
1541  
1542          if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) {
1543              foreach ( $validation as $valid ) {
1544                  if ( is_wp_error( $valid ) ) {
1545                      $responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data();
1546                  } else {
1547                      $responses[] = null;
1548                  }
1549              }
1550  
1551              return new WP_REST_Response(
1552                  array(
1553                      'failed'    => 'validation',
1554                      'responses' => $responses,
1555                  ),
1556                  WP_Http::MULTI_STATUS
1557              );
1558          }
1559  
1560          foreach ( $requests as $i => $single_request ) {
1561              $clean_request = clone $single_request;
1562              $clean_request->set_url_params( array() );
1563              $clean_request->set_attributes( array() );
1564              $clean_request->set_default_params( array() );
1565  
1566              /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1567              $result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );
1568  
1569              if ( empty( $result ) ) {
1570                  $match = $matches[ $i ];
1571                  $error = null;
1572  
1573                  if ( is_wp_error( $validation[ $i ] ) ) {
1574                      $error = $validation[ $i ];
1575                  }
1576  
1577                  if ( is_wp_error( $match ) ) {
1578                      $result = $this->error_to_response( $match );
1579                  } else {
1580                      list( $route, $handler ) = $match;
1581  
1582                      if ( ! $error && ! is_callable( $handler['callback'] ) ) {
1583                          $error = new WP_Error(
1584                              'rest_invalid_handler',
1585                              __( 'The handler for the route is invalid' ),
1586                              array( 'status' => 500 )
1587                          );
1588                      }
1589  
1590                      $result = $this->respond_to_request( $single_request, $route, $handler, $error );
1591                  }
1592              }
1593  
1594              /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1595              $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request );
1596  
1597              $responses[] = $this->envelope_response( $result, false )->get_data();
1598          }
1599  
1600          return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS );
1601      }
1602  
1603      /**
1604       * Sends an HTTP status code.
1605       *
1606       * @since 4.4.0
1607       *
1608       * @param int $code HTTP status.
1609       */
1610  	protected function set_status( $code ) {
1611          status_header( $code );
1612      }
1613  
1614      /**
1615       * Sends an HTTP header.
1616       *
1617       * @since 4.4.0
1618       *
1619       * @param string $key Header key.
1620       * @param string $value Header value.
1621       */
1622  	public function send_header( $key, $value ) {
1623          /*
1624           * Sanitize as per RFC2616 (Section 4.2):
1625           *
1626           * Any LWS that occurs between field-content MAY be replaced with a
1627           * single SP before interpreting the field value or forwarding the
1628           * message downstream.
1629           */
1630          $value = preg_replace( '/\s+/', ' ', $value );
1631          header( sprintf( '%s: %s', $key, $value ) );
1632      }
1633  
1634      /**
1635       * Sends multiple HTTP headers.
1636       *
1637       * @since 4.4.0
1638       *
1639       * @param array $headers Map of header name to header value.
1640       */
1641  	public function send_headers( $headers ) {
1642          foreach ( $headers as $key => $value ) {
1643              $this->send_header( $key, $value );
1644          }
1645      }
1646  
1647      /**
1648       * Removes an HTTP header from the current response.
1649       *
1650       * @since 4.8.0
1651       *
1652       * @param string $key Header key.
1653       */
1654  	public function remove_header( $key ) {
1655          header_remove( $key );
1656      }
1657  
1658      /**
1659       * Retrieves the raw request entity (body).
1660       *
1661       * @since 4.4.0
1662       *
1663       * @global string $HTTP_RAW_POST_DATA Raw post data.
1664       *
1665       * @return string Raw request data.
1666       */
1667  	public static function get_raw_data() {
1668          // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
1669          global $HTTP_RAW_POST_DATA;
1670  
1671          // $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0.
1672          if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
1673              $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
1674          }
1675  
1676          return $HTTP_RAW_POST_DATA;
1677          // phpcs:enable
1678      }
1679  
1680      /**
1681       * Extracts headers from a PHP-style $_SERVER array.
1682       *
1683       * @since 4.4.0
1684       *
1685       * @param array $server Associative array similar to `$_SERVER`.
1686       * @return array Headers extracted from the input.
1687       */
1688  	public function get_headers( $server ) {
1689          $headers = array();
1690  
1691          // CONTENT_* headers are not prefixed with HTTP_.
1692          $additional = array(
1693              'CONTENT_LENGTH' => true,
1694              'CONTENT_MD5'    => true,
1695              'CONTENT_TYPE'   => true,
1696          );
1697  
1698          foreach ( $server as $key => $value ) {
1699              if ( strpos( $key, 'HTTP_' ) === 0 ) {
1700                  $headers[ substr( $key, 5 ) ] = $value;
1701              } elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) {
1702                  /*
1703                   * In some server configurations, the authorization header is passed in this alternate location.
1704                   * Since it would not be passed in in both places we do not check for both headers and resolve.
1705                   */
1706                  $headers['AUTHORIZATION'] = $value;
1707              } elseif ( isset( $additional[ $key ] ) ) {
1708                  $headers[ $key ] = $value;
1709              }
1710          }
1711  
1712          return $headers;
1713      }
1714  }


Generated : Sat Nov 28 08:20:01 2020 Cross-referenced by PHPXref