[ Index ]

PHP Cross Reference of WordPress

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       * Instantiates the REST server.
  83       *
  84       * @since 4.4.0
  85       */
  86  	public function __construct() {
  87          $this->endpoints = array(
  88              // Meta endpoints.
  89              '/' => array(
  90                  'callback' => array( $this, 'get_index' ),
  91                  'methods'  => 'GET',
  92                  'args'     => array(
  93                      'context' => array(
  94                          'default' => 'view',
  95                      ),
  96                  ),
  97              ),
  98          );
  99      }
 100  
 101  
 102      /**
 103       * Checks the authentication headers if supplied.
 104       *
 105       * @since 4.4.0
 106       *
 107       * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful
 108       *                       or no authentication provided
 109       */
 110  	public function check_authentication() {
 111          /**
 112           * Filters REST authentication errors.
 113           *
 114           * This is used to pass a WP_Error from an authentication method back to
 115           * the API.
 116           *
 117           * Authentication methods should check first if they're being used, as
 118           * multiple authentication methods can be enabled on a site (cookies,
 119           * HTTP basic auth, OAuth). If the authentication method hooked in is
 120           * not actually being attempted, null should be returned to indicate
 121           * another authentication method should check instead. Similarly,
 122           * callbacks should ensure the value is `null` before checking for
 123           * errors.
 124           *
 125           * A WP_Error instance can be returned if an error occurs, and this should
 126           * match the format used by API methods internally (that is, the `status`
 127           * data should be used). A callback can return `true` to indicate that
 128           * the authentication method was used, and it succeeded.
 129           *
 130           * @since 4.4.0
 131           *
 132           * @param WP_Error|null|bool WP_Error if authentication error, null if authentication
 133           *                              method wasn't used, true if authentication succeeded.
 134           */
 135          return apply_filters( 'rest_authentication_errors', null );
 136      }
 137  
 138      /**
 139       * Converts an error to a response object.
 140       *
 141       * This iterates over all error codes and messages to change it into a flat
 142       * array. This enables simpler client behaviour, as it is represented as a
 143       * list in JSON rather than an object/map.
 144       *
 145       * @since 4.4.0
 146       *
 147       * @param WP_Error $error WP_Error instance.
 148       * @return WP_REST_Response List of associative arrays with code and message keys.
 149       */
 150  	protected function error_to_response( $error ) {
 151          $error_data = $error->get_error_data();
 152  
 153          if ( is_array( $error_data ) && isset( $error_data['status'] ) ) {
 154              $status = $error_data['status'];
 155          } else {
 156              $status = 500;
 157          }
 158  
 159          $errors = array();
 160  
 161          foreach ( (array) $error->errors as $code => $messages ) {
 162              foreach ( (array) $messages as $message ) {
 163                  $errors[] = array(
 164                      'code'    => $code,
 165                      'message' => $message,
 166                      'data'    => $error->get_error_data( $code ),
 167                  );
 168              }
 169          }
 170  
 171          $data = $errors[0];
 172          if ( count( $errors ) > 1 ) {
 173              // Remove the primary error.
 174              array_shift( $errors );
 175              $data['additional_errors'] = $errors;
 176          }
 177  
 178          $response = new WP_REST_Response( $data, $status );
 179  
 180          return $response;
 181      }
 182  
 183      /**
 184       * Retrieves an appropriate error representation in JSON.
 185       *
 186       * Note: This should only be used in WP_REST_Server::serve_request(), as it
 187       * cannot handle WP_Error internally. All callbacks and other internal methods
 188       * should instead return a WP_Error with the data set to an array that includes
 189       * a 'status' key, with the value being the HTTP status to send.
 190       *
 191       * @since 4.4.0
 192       *
 193       * @param string $code    WP_Error-style code.
 194       * @param string $message Human-readable message.
 195       * @param int    $status  Optional. HTTP status code to send. Default null.
 196       * @return string JSON representation of the error
 197       */
 198  	protected function json_error( $code, $message, $status = null ) {
 199          if ( $status ) {
 200              $this->set_status( $status );
 201          }
 202  
 203          $error = compact( 'code', 'message' );
 204  
 205          return wp_json_encode( $error );
 206      }
 207  
 208      /**
 209       * Handles serving an API request.
 210       *
 211       * Matches the current server URI to a route and runs the first matching
 212       * callback then outputs a JSON representation of the returned value.
 213       *
 214       * @since 4.4.0
 215       *
 216       * @see WP_REST_Server::dispatch()
 217       *
 218       * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
 219       *                     Default null.
 220       * @return false|null Null if not served and a HEAD request, false otherwise.
 221       */
 222  	public function serve_request( $path = null ) {
 223          $content_type = isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json';
 224          $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
 225          $this->send_header( 'X-Robots-Tag', 'noindex' );
 226  
 227          $api_root = get_rest_url();
 228          if ( ! empty( $api_root ) ) {
 229              $this->send_header( 'Link', '<' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"' );
 230          }
 231  
 232          /*
 233           * Mitigate possible JSONP Flash attacks.
 234           *
 235           * https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
 236           */
 237          $this->send_header( 'X-Content-Type-Options', 'nosniff' );
 238          $this->send_header( 'Access-Control-Expose-Headers', 'X-WP-Total, X-WP-TotalPages' );
 239          $this->send_header( 'Access-Control-Allow-Headers', 'Authorization, Content-Type' );
 240  
 241          /**
 242           * Send nocache headers on authenticated requests.
 243           *
 244           * @since 4.4.0
 245           *
 246           * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
 247           */
 248          $send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
 249          if ( $send_no_cache_headers ) {
 250              foreach ( wp_get_nocache_headers() as $header => $header_value ) {
 251                  if ( empty( $header_value ) ) {
 252                      $this->remove_header( $header );
 253                  } else {
 254                      $this->send_header( $header, $header_value );
 255                  }
 256              }
 257          }
 258  
 259          /**
 260           * Filters whether the REST API is enabled.
 261           *
 262           * @since 4.4.0
 263           * @deprecated 4.7.0 Use the rest_authentication_errors filter to restrict access to the API
 264           *
 265           * @param bool $rest_enabled Whether the REST API is enabled. Default true.
 266           */
 267          apply_filters_deprecated(
 268              'rest_enabled',
 269              array( true ),
 270              '4.7.0',
 271              'rest_authentication_errors',
 272              __( 'The REST API can no longer be completely disabled, the rest_authentication_errors filter can be used to restrict access to the API, instead.' )
 273          );
 274  
 275          /**
 276           * Filters whether jsonp is enabled.
 277           *
 278           * @since 4.4.0
 279           *
 280           * @param bool $jsonp_enabled Whether jsonp is enabled. Default true.
 281           */
 282          $jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
 283  
 284          $jsonp_callback = null;
 285  
 286          if ( isset( $_GET['_jsonp'] ) ) {
 287              if ( ! $jsonp_enabled ) {
 288                  echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
 289                  return false;
 290              }
 291  
 292              $jsonp_callback = $_GET['_jsonp'];
 293              if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
 294                  echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 );
 295                  return false;
 296              }
 297          }
 298  
 299          if ( empty( $path ) ) {
 300              if ( isset( $_SERVER['PATH_INFO'] ) ) {
 301                  $path = $_SERVER['PATH_INFO'];
 302              } else {
 303                  $path = '/';
 304              }
 305          }
 306  
 307          $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
 308  
 309          $request->set_query_params( wp_unslash( $_GET ) );
 310          $request->set_body_params( wp_unslash( $_POST ) );
 311          $request->set_file_params( $_FILES );
 312          $request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) );
 313          $request->set_body( self::get_raw_data() );
 314  
 315          /*
 316           * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
 317           * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
 318           * header.
 319           */
 320          if ( isset( $_GET['_method'] ) ) {
 321              $request->set_method( $_GET['_method'] );
 322          } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
 323              $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
 324          }
 325  
 326          $result = $this->check_authentication();
 327  
 328          if ( ! is_wp_error( $result ) ) {
 329              $result = $this->dispatch( $request );
 330          }
 331  
 332          // Normalize to either WP_Error or WP_REST_Response...
 333          $result = rest_ensure_response( $result );
 334  
 335          // ...then convert WP_Error across.
 336          if ( is_wp_error( $result ) ) {
 337              $result = $this->error_to_response( $result );
 338          }
 339  
 340          /**
 341           * Filters the API response.
 342           *
 343           * Allows modification of the response before returning.
 344           *
 345           * @since 4.4.0
 346           * @since 4.5.0 Applied to embedded responses.
 347           *
 348           * @param WP_HTTP_Response $result  Result to send to the client. Usually a WP_REST_Response.
 349           * @param WP_REST_Server   $this    Server instance.
 350           * @param WP_REST_Request  $request Request used to generate the response.
 351           */
 352          $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
 353  
 354          // Wrap the response in an envelope if asked for.
 355          if ( isset( $_GET['_envelope'] ) ) {
 356              $result = $this->envelope_response( $result, isset( $_GET['_embed'] ) );
 357          }
 358  
 359          // Send extra data from response objects.
 360          $headers = $result->get_headers();
 361          $this->send_headers( $headers );
 362  
 363          $code = $result->get_status();
 364          $this->set_status( $code );
 365  
 366          /**
 367           * Filters whether the request has already been served.
 368           *
 369           * Allow sending the request manually - by returning true, the API result
 370           * will not be sent to the client.
 371           *
 372           * @since 4.4.0
 373           *
 374           * @param bool             $served  Whether the request has already been served.
 375           *                                           Default false.
 376           * @param WP_HTTP_Response $result  Result to send to the client. Usually a WP_REST_Response.
 377           * @param WP_REST_Request  $request Request used to generate the response.
 378           * @param WP_REST_Server   $this    Server instance.
 379           */
 380          $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
 381  
 382          if ( ! $served ) {
 383              if ( 'HEAD' === $request->get_method() ) {
 384                  return null;
 385              }
 386  
 387              // Embed links inside the request.
 388              $result = $this->response_to_data( $result, isset( $_GET['_embed'] ) );
 389  
 390              /**
 391               * Filters the API response.
 392               *
 393               * Allows modification of the response data after inserting
 394               * embedded data (if any) and before echoing the response data.
 395               *
 396               * @since 4.8.1
 397               *
 398               * @param array            $result  Response data to send to the client.
 399               * @param WP_REST_Server   $this    Server instance.
 400               * @param WP_REST_Request  $request Request used to generate the response.
 401               */
 402              $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
 403  
 404              // The 204 response shouldn't have a body.
 405              if ( 204 === $code || null === $result ) {
 406                  return null;
 407              }
 408  
 409              $result = wp_json_encode( $result );
 410  
 411              $json_error_message = $this->get_json_last_error();
 412              if ( $json_error_message ) {
 413                  $json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, array( 'status' => 500 ) );
 414                  $result         = $this->error_to_response( $json_error_obj );
 415                  $result         = wp_json_encode( $result->data[0] );
 416              }
 417  
 418              if ( $jsonp_callback ) {
 419                  // Prepend '/**/' to mitigate possible JSONP Flash attacks.
 420                  // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
 421                  echo '/**/' . $jsonp_callback . '(' . $result . ')';
 422              } else {
 423                  echo $result;
 424              }
 425          }
 426          return null;
 427      }
 428  
 429      /**
 430       * Converts a response to data to send.
 431       *
 432       * @since 4.4.0
 433       *
 434       * @param WP_REST_Response $response Response object.
 435       * @param bool             $embed    Whether links should be embedded.
 436       * @return array {
 437       *     Data with sub-requests embedded.
 438       *
 439       *     @type array [$_links]    Links.
 440       *     @type array [$_embedded] Embeddeds.
 441       * }
 442       */
 443  	public function response_to_data( $response, $embed ) {
 444          $data  = $response->get_data();
 445          $links = self::get_compact_response_links( $response );
 446  
 447          if ( ! empty( $links ) ) {
 448              // Convert links to part of the data.
 449              $data['_links'] = $links;
 450          }
 451          if ( $embed ) {
 452              // Determine if this is a numeric array.
 453              if ( wp_is_numeric_array( $data ) ) {
 454                  $data = array_map( array( $this, 'embed_links' ), $data );
 455              } else {
 456                  $data = $this->embed_links( $data );
 457              }
 458          }
 459  
 460          return $data;
 461      }
 462  
 463      /**
 464       * Retrieves links from a response.
 465       *
 466       * Extracts the links from a response into a structured hash, suitable for
 467       * direct output.
 468       *
 469       * @since 4.4.0
 470       *
 471       * @param WP_REST_Response $response Response to extract links from.
 472       * @return array Map of link relation to list of link hashes.
 473       */
 474  	public static function get_response_links( $response ) {
 475          $links = $response->get_links();
 476          if ( empty( $links ) ) {
 477              return array();
 478          }
 479  
 480          // Convert links to part of the data.
 481          $data = array();
 482          foreach ( $links as $rel => $items ) {
 483              $data[ $rel ] = array();
 484  
 485              foreach ( $items as $item ) {
 486                  $attributes         = $item['attributes'];
 487                  $attributes['href'] = $item['href'];
 488                  $data[ $rel ][]     = $attributes;
 489              }
 490          }
 491  
 492          return $data;
 493      }
 494  
 495      /**
 496       * Retrieves the CURIEs (compact URIs) used for relations.
 497       *
 498       * Extracts the links from a response into a structured hash, suitable for
 499       * direct output.
 500       *
 501       * @since 4.5.0
 502       *
 503       * @param WP_REST_Response $response Response to extract links from.
 504       * @return array Map of link relation to list of link hashes.
 505       */
 506  	public static function get_compact_response_links( $response ) {
 507          $links = self::get_response_links( $response );
 508  
 509          if ( empty( $links ) ) {
 510              return array();
 511          }
 512  
 513          $curies      = $response->get_curies();
 514          $used_curies = array();
 515  
 516          foreach ( $links as $rel => $items ) {
 517  
 518              // Convert $rel URIs to their compact versions if they exist.
 519              foreach ( $curies as $curie ) {
 520                  $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
 521                  if ( strpos( $rel, $href_prefix ) !== 0 ) {
 522                      continue;
 523                  }
 524  
 525                  // Relation now changes from '$uri' to '$curie:$relation'.
 526                  $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
 527                  preg_match( '!' . $rel_regex . '!', $rel, $matches );
 528                  if ( $matches ) {
 529                      $new_rel                       = $curie['name'] . ':' . $matches[1];
 530                      $used_curies[ $curie['name'] ] = $curie;
 531                      $links[ $new_rel ]             = $items;
 532                      unset( $links[ $rel ] );
 533                      break;
 534                  }
 535              }
 536          }
 537  
 538          // Push the curies onto the start of the links array.
 539          if ( $used_curies ) {
 540              $links['curies'] = array_values( $used_curies );
 541          }
 542  
 543          return $links;
 544      }
 545  
 546      /**
 547       * Embeds the links from the data into the request.
 548       *
 549       * @since 4.4.0
 550       *
 551       * @param array $data Data from the request.
 552       * @return array {
 553       *     Data with sub-requests embedded.
 554       *
 555       *     @type array [$_links]    Links.
 556       *     @type array [$_embedded] Embeddeds.
 557       * }
 558       */
 559  	protected function embed_links( $data ) {
 560          if ( empty( $data['_links'] ) ) {
 561              return $data;
 562          }
 563  
 564          $embedded = array();
 565  
 566          foreach ( $data['_links'] as $rel => $links ) {
 567              // Ignore links to self, for obvious reasons.
 568              if ( 'self' === $rel ) {
 569                  continue;
 570              }
 571  
 572              $embeds = array();
 573  
 574              foreach ( $links as $item ) {
 575                  // Determine if the link is embeddable.
 576                  if ( empty( $item['embeddable'] ) ) {
 577                      // Ensure we keep the same order.
 578                      $embeds[] = array();
 579                      continue;
 580                  }
 581  
 582                  // Run through our internal routing and serve.
 583                  $request = WP_REST_Request::from_url( $item['href'] );
 584                  if ( ! $request ) {
 585                      $embeds[] = array();
 586                      continue;
 587                  }
 588  
 589                  // Embedded resources get passed context=embed.
 590                  if ( empty( $request['context'] ) ) {
 591                      $request['context'] = 'embed';
 592                  }
 593  
 594                  $response = $this->dispatch( $request );
 595  
 596                  /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
 597                  $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
 598  
 599                  $embeds[] = $this->response_to_data( $response, false );
 600              }
 601  
 602              // Determine if any real links were found.
 603              $has_links = count( array_filter( $embeds ) );
 604  
 605              if ( $has_links ) {
 606                  $embedded[ $rel ] = $embeds;
 607              }
 608          }
 609  
 610          if ( ! empty( $embedded ) ) {
 611              $data['_embedded'] = $embedded;
 612          }
 613  
 614          return $data;
 615      }
 616  
 617      /**
 618       * Wraps the response in an envelope.
 619       *
 620       * The enveloping technique is used to work around browser/client
 621       * compatibility issues. Essentially, it converts the full HTTP response to
 622       * data instead.
 623       *
 624       * @since 4.4.0
 625       *
 626       * @param WP_REST_Response $response Response object.
 627       * @param bool             $embed    Whether links should be embedded.
 628       * @return WP_REST_Response New response with wrapped data
 629       */
 630  	public function envelope_response( $response, $embed ) {
 631          $envelope = array(
 632              'body'    => $this->response_to_data( $response, $embed ),
 633              'status'  => $response->get_status(),
 634              'headers' => $response->get_headers(),
 635          );
 636  
 637          /**
 638           * Filters the enveloped form of a response.
 639           *
 640           * @since 4.4.0
 641           *
 642           * @param array            $envelope Envelope data.
 643           * @param WP_REST_Response $response Original response data.
 644           */
 645          $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
 646  
 647          // Ensure it's still a response and return.
 648          return rest_ensure_response( $envelope );
 649      }
 650  
 651      /**
 652       * Registers a route to the server.
 653       *
 654       * @since 4.4.0
 655       *
 656       * @param string $namespace  Namespace.
 657       * @param string $route      The REST route.
 658       * @param array  $route_args Route arguments.
 659       * @param bool   $override   Optional. Whether the route should be overridden if it already exists.
 660       *                           Default false.
 661       */
 662  	public function register_route( $namespace, $route, $route_args, $override = false ) {
 663          if ( ! isset( $this->namespaces[ $namespace ] ) ) {
 664              $this->namespaces[ $namespace ] = array();
 665  
 666              $this->register_route(
 667                  $namespace,
 668                  '/' . $namespace,
 669                  array(
 670                      array(
 671                          'methods'  => self::READABLE,
 672                          'callback' => array( $this, 'get_namespace_index' ),
 673                          'args'     => array(
 674                              'namespace' => array(
 675                                  'default' => $namespace,
 676                              ),
 677                              'context'   => array(
 678                                  'default' => 'view',
 679                              ),
 680                          ),
 681                      ),
 682                  )
 683              );
 684          }
 685  
 686          // Associative to avoid double-registration.
 687          $this->namespaces[ $namespace ][ $route ] = true;
 688          $route_args['namespace']                  = $namespace;
 689  
 690          if ( $override || empty( $this->endpoints[ $route ] ) ) {
 691              $this->endpoints[ $route ] = $route_args;
 692          } else {
 693              $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
 694          }
 695      }
 696  
 697      /**
 698       * Retrieves the route map.
 699       *
 700       * The route map is an associative array with path regexes as the keys. The
 701       * value is an indexed array with the callback function/method as the first
 702       * item, and a bitmask of HTTP methods as the second item (see the class
 703       * constants).
 704       *
 705       * Each route can be mapped to more than one callback by using an array of
 706       * the indexed arrays. This allows mapping e.g. GET requests to one callback
 707       * and POST requests to another.
 708       *
 709       * Note that the path regexes (array keys) must have @ escaped, as this is
 710       * used as the delimiter with preg_match()
 711       *
 712       * @since 4.4.0
 713       *
 714       * @return array `'/path/regex' => array( $callback, $bitmask )` or
 715       *               `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
 716       */
 717  	public function get_routes() {
 718  
 719          /**
 720           * Filters the array of available endpoints.
 721           *
 722           * @since 4.4.0
 723           *
 724           * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
 725           *                         to an array of callbacks for the endpoint. These take the format
 726           *                         `'/path/regex' => array( $callback, $bitmask )` or
 727           *                         `'/path/regex' => array( array( $callback, $bitmask ).
 728           */
 729          $endpoints = apply_filters( 'rest_endpoints', $this->endpoints );
 730  
 731          // Normalise the endpoints.
 732          $defaults = array(
 733              'methods'       => '',
 734              'accept_json'   => false,
 735              'accept_raw'    => false,
 736              'show_in_index' => true,
 737              'args'          => array(),
 738          );
 739  
 740          foreach ( $endpoints as $route => &$handlers ) {
 741  
 742              if ( isset( $handlers['callback'] ) ) {
 743                  // Single endpoint, add one deeper.
 744                  $handlers = array( $handlers );
 745              }
 746  
 747              if ( ! isset( $this->route_options[ $route ] ) ) {
 748                  $this->route_options[ $route ] = array();
 749              }
 750  
 751              foreach ( $handlers as $key => &$handler ) {
 752  
 753                  if ( ! is_numeric( $key ) ) {
 754                      // Route option, move it to the options.
 755                      $this->route_options[ $route ][ $key ] = $handler;
 756                      unset( $handlers[ $key ] );
 757                      continue;
 758                  }
 759  
 760                  $handler = wp_parse_args( $handler, $defaults );
 761  
 762                  // Allow comma-separated HTTP methods.
 763                  if ( is_string( $handler['methods'] ) ) {
 764                      $methods = explode( ',', $handler['methods'] );
 765                  } elseif ( is_array( $handler['methods'] ) ) {
 766                      $methods = $handler['methods'];
 767                  } else {
 768                      $methods = array();
 769                  }
 770  
 771                  $handler['methods'] = array();
 772  
 773                  foreach ( $methods as $method ) {
 774                      $method                        = strtoupper( trim( $method ) );
 775                      $handler['methods'][ $method ] = true;
 776                  }
 777              }
 778          }
 779  
 780          return $endpoints;
 781      }
 782  
 783      /**
 784       * Retrieves namespaces registered on the server.
 785       *
 786       * @since 4.4.0
 787       *
 788       * @return array List of registered namespaces.
 789       */
 790  	public function get_namespaces() {
 791          return array_keys( $this->namespaces );
 792      }
 793  
 794      /**
 795       * Retrieves specified options for a route.
 796       *
 797       * @since 4.4.0
 798       *
 799       * @param string $route Route pattern to fetch options for.
 800       * @return array|null Data as an associative array if found, or null if not found.
 801       */
 802  	public function get_route_options( $route ) {
 803          if ( ! isset( $this->route_options[ $route ] ) ) {
 804              return null;
 805          }
 806  
 807          return $this->route_options[ $route ];
 808      }
 809  
 810      /**
 811       * Matches the request to a callback and call it.
 812       *
 813       * @since 4.4.0
 814       *
 815       * @param WP_REST_Request $request Request to attempt dispatching.
 816       * @return WP_REST_Response Response returned by the callback.
 817       */
 818  	public function dispatch( $request ) {
 819          /**
 820           * Filters the pre-calculated result of a REST dispatch request.
 821           *
 822           * Allow hijacking the request before dispatching by returning a non-empty. The returned value
 823           * will be used to serve the request instead.
 824           *
 825           * @since 4.4.0
 826           *
 827           * @param mixed           $result  Response to replace the requested version with. Can be anything
 828           *                                 a normal endpoint can return, or null to not hijack the request.
 829           * @param WP_REST_Server  $this    Server instance.
 830           * @param WP_REST_Request $request Request used to generate the response.
 831           */
 832          $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
 833  
 834          if ( ! empty( $result ) ) {
 835              return $result;
 836          }
 837  
 838          $method = $request->get_method();
 839          $path   = $request->get_route();
 840  
 841          foreach ( $this->get_routes() as $route => $handlers ) {
 842              $match = preg_match( '@^' . $route . '$@i', $path, $matches );
 843  
 844              if ( ! $match ) {
 845                  continue;
 846              }
 847  
 848              $args = array();
 849              foreach ( $matches as $param => $value ) {
 850                  if ( ! is_int( $param ) ) {
 851                      $args[ $param ] = $value;
 852                  }
 853              }
 854  
 855              foreach ( $handlers as $handler ) {
 856                  $callback = $handler['callback'];
 857                  $response = null;
 858  
 859                  // Fallback to GET method if no HEAD method is registered.
 860                  $checked_method = $method;
 861                  if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
 862                      $checked_method = 'GET';
 863                  }
 864                  if ( empty( $handler['methods'][ $checked_method ] ) ) {
 865                      continue;
 866                  }
 867  
 868                  if ( ! is_callable( $callback ) ) {
 869                      $response = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) );
 870                  }
 871  
 872                  if ( ! is_wp_error( $response ) ) {
 873                      // Remove the redundant preg_match argument.
 874                      unset( $args[0] );
 875  
 876                      $request->set_url_params( $args );
 877                      $request->set_attributes( $handler );
 878  
 879                      $defaults = array();
 880  
 881                      foreach ( $handler['args'] as $arg => $options ) {
 882                          if ( isset( $options['default'] ) ) {
 883                              $defaults[ $arg ] = $options['default'];
 884                          }
 885                      }
 886  
 887                      $request->set_default_params( $defaults );
 888  
 889                      $check_required = $request->has_valid_params();
 890                      if ( is_wp_error( $check_required ) ) {
 891                          $response = $check_required;
 892                      } else {
 893                          $check_sanitized = $request->sanitize_params();
 894                          if ( is_wp_error( $check_sanitized ) ) {
 895                              $response = $check_sanitized;
 896                          }
 897                      }
 898                  }
 899  
 900                  /**
 901                   * Filters the response before executing any REST API callbacks.
 902                   *
 903                   * Allows plugins to perform additional validation after a
 904                   * request is initialized and matched to a registered route,
 905                   * but before it is executed.
 906                   *
 907                   * Note that this filter will not be called for requests that
 908                   * fail to authenticate or match to a registered route.
 909                   *
 910                   * @since 4.7.0
 911                   *
 912                   * @param WP_HTTP_Response|WP_Error $response Result to send to the client. Usually a WP_REST_Response or WP_Error.
 913                   * @param array                     $handler  Route handler used for the request.
 914                   * @param WP_REST_Request           $request  Request used to generate the response.
 915                   */
 916                  $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
 917  
 918                  if ( ! is_wp_error( $response ) ) {
 919                      // Check permission specified on the route.
 920                      if ( ! empty( $handler['permission_callback'] ) ) {
 921                          $permission = call_user_func( $handler['permission_callback'], $request );
 922  
 923                          if ( is_wp_error( $permission ) ) {
 924                              $response = $permission;
 925                          } elseif ( false === $permission || null === $permission ) {
 926                              $response = new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.' ), array( 'status' => rest_authorization_required_code() ) );
 927                          }
 928                      }
 929                  }
 930  
 931                  if ( ! is_wp_error( $response ) ) {
 932                      /**
 933                       * Filters the REST dispatch request result.
 934                       *
 935                       * Allow plugins to override dispatching the request.
 936                       *
 937                       * @since 4.4.0
 938                       * @since 4.5.0 Added `$route` and `$handler` parameters.
 939                       *
 940                       * @param mixed           $dispatch_result Dispatch result, will be used if not empty.
 941                       * @param WP_REST_Request $request         Request used to generate the response.
 942                       * @param string          $route           Route matched for the request.
 943                       * @param array           $handler         Route handler used for the request.
 944                       */
 945                      $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
 946  
 947                      // Allow plugins to halt the request via this filter.
 948                      if ( null !== $dispatch_result ) {
 949                          $response = $dispatch_result;
 950                      } else {
 951                          $response = call_user_func( $callback, $request );
 952                      }
 953                  }
 954  
 955                  /**
 956                   * Filters the response immediately after executing any REST API
 957                   * callbacks.
 958                   *
 959                   * Allows plugins to perform any needed cleanup, for example,
 960                   * to undo changes made during the {@see 'rest_request_before_callbacks'}
 961                   * filter.
 962                   *
 963                   * Note that this filter will not be called for requests that
 964                   * fail to authenticate or match to a registered route.
 965                   *
 966                   * Note that an endpoint's `permission_callback` can still be
 967                   * called after this filter - see `rest_send_allow_header()`.
 968                   *
 969                   * @since 4.7.0
 970                   *
 971                   * @param WP_HTTP_Response|WP_Error $response Result to send to the client. Usually a WP_REST_Response or WP_Error.
 972                   * @param array                     $handler  Route handler used for the request.
 973                   * @param WP_REST_Request           $request  Request used to generate the response.
 974                   */
 975                  $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
 976  
 977                  if ( is_wp_error( $response ) ) {
 978                      $response = $this->error_to_response( $response );
 979                  } else {
 980                      $response = rest_ensure_response( $response );
 981                  }
 982  
 983                  $response->set_matched_route( $route );
 984                  $response->set_matched_handler( $handler );
 985  
 986                  return $response;
 987              }
 988          }
 989  
 990          return $this->error_to_response( new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), array( 'status' => 404 ) ) );
 991      }
 992  
 993      /**
 994       * Returns if an error occurred during most recent JSON encode/decode.
 995       *
 996       * Strings to be translated will be in format like
 997       * "Encoding error: Maximum stack depth exceeded".
 998       *
 999       * @since 4.4.0
1000       *
1001       * @return bool|string Boolean false or string error message.
1002       */
1003  	protected function get_json_last_error() {
1004          $last_error_code = json_last_error();
1005  
1006          if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) {
1007              return false;
1008          }
1009  
1010          return json_last_error_msg();
1011      }
1012  
1013      /**
1014       * Retrieves the site index.
1015       *
1016       * This endpoint describes the capabilities of the site.
1017       *
1018       * @since 4.4.0
1019       *
1020       * @param array $request {
1021       *     Request.
1022       *
1023       *     @type string $context Context.
1024       * }
1025       * @return array Index entity
1026       */
1027  	public function get_index( $request ) {
1028          // General site data.
1029          $available = array(
1030              'name'            => get_option( 'blogname' ),
1031              'description'     => get_option( 'blogdescription' ),
1032              'url'             => get_option( 'siteurl' ),
1033              'home'            => home_url(),
1034              'gmt_offset'      => get_option( 'gmt_offset' ),
1035              'timezone_string' => get_option( 'timezone_string' ),
1036              'namespaces'      => array_keys( $this->namespaces ),
1037              'authentication'  => array(),
1038              'routes'          => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
1039          );
1040  
1041          $response = new WP_REST_Response( $available );
1042  
1043          $response->add_link( 'help', 'http://v2.wp-api.org/' );
1044  
1045          /**
1046           * Filters the API root index data.
1047           *
1048           * This contains the data describing the API. This includes information
1049           * about supported authentication schemes, supported namespaces, routes
1050           * available on the API, and a small amount of data about the site.
1051           *
1052           * @since 4.4.0
1053           *
1054           * @param WP_REST_Response $response Response data.
1055           */
1056          return apply_filters( 'rest_index', $response );
1057      }
1058  
1059      /**
1060       * Retrieves the index for a namespace.
1061       *
1062       * @since 4.4.0
1063       *
1064       * @param WP_REST_Request $request REST request instance.
1065       * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
1066       *                                   WP_Error if the namespace isn't set.
1067       */
1068  	public function get_namespace_index( $request ) {
1069          $namespace = $request['namespace'];
1070  
1071          if ( ! isset( $this->namespaces[ $namespace ] ) ) {
1072              return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) );
1073          }
1074  
1075          $routes    = $this->namespaces[ $namespace ];
1076          $endpoints = array_intersect_key( $this->get_routes(), $routes );
1077  
1078          $data     = array(
1079              'namespace' => $namespace,
1080              'routes'    => $this->get_data_for_routes( $endpoints, $request['context'] ),
1081          );
1082          $response = rest_ensure_response( $data );
1083  
1084          // Link to the root index.
1085          $response->add_link( 'up', rest_url( '/' ) );
1086  
1087          /**
1088           * Filters the namespace index data.
1089           *
1090           * This typically is just the route data for the namespace, but you can
1091           * add any data you'd like here.
1092           *
1093           * @since 4.4.0
1094           *
1095           * @param WP_REST_Response $response Response data.
1096           * @param WP_REST_Request  $request  Request data. The namespace is passed as the 'namespace' parameter.
1097           */
1098          return apply_filters( 'rest_namespace_index', $response, $request );
1099      }
1100  
1101      /**
1102       * Retrieves the publicly-visible data for routes.
1103       *
1104       * @since 4.4.0
1105       *
1106       * @param array  $routes  Routes to get data for.
1107       * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
1108       * @return array Route data to expose in indexes.
1109       */
1110  	public function get_data_for_routes( $routes, $context = 'view' ) {
1111          $available = array();
1112  
1113          // Find the available routes.
1114          foreach ( $routes as $route => $callbacks ) {
1115              $data = $this->get_data_for_route( $route, $callbacks, $context );
1116              if ( empty( $data ) ) {
1117                  continue;
1118              }
1119  
1120              /**
1121               * Filters the REST endpoint data.
1122               *
1123               * @since 4.4.0
1124               *
1125               * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
1126               */
1127              $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
1128          }
1129  
1130          /**
1131           * Filters the publicly-visible data for routes.
1132           *
1133           * This data is exposed on indexes and can be used by clients or
1134           * developers to investigate the site and find out how to use it. It
1135           * acts as a form of self-documentation.
1136           *
1137           * @since 4.4.0
1138           *
1139           * @param array $available Map of route to route data.
1140           * @param array $routes    Internal route data as an associative array.
1141           */
1142          return apply_filters( 'rest_route_data', $available, $routes );
1143      }
1144  
1145      /**
1146       * Retrieves publicly-visible data for the route.
1147       *
1148       * @since 4.4.0
1149       *
1150       * @param string $route     Route to get data for.
1151       * @param array  $callbacks Callbacks to convert to data.
1152       * @param string $context   Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
1153       * @return array|null Data for the route, or null if no publicly-visible data.
1154       */
1155  	public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
1156          $data = array(
1157              'namespace' => '',
1158              'methods'   => array(),
1159              'endpoints' => array(),
1160          );
1161  
1162          if ( isset( $this->route_options[ $route ] ) ) {
1163              $options = $this->route_options[ $route ];
1164  
1165              if ( isset( $options['namespace'] ) ) {
1166                  $data['namespace'] = $options['namespace'];
1167              }
1168  
1169              if ( isset( $options['schema'] ) && 'help' === $context ) {
1170                  $data['schema'] = call_user_func( $options['schema'] );
1171              }
1172          }
1173  
1174          $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
1175  
1176          foreach ( $callbacks as $callback ) {
1177              // Skip to the next route if any callback is hidden.
1178              if ( empty( $callback['show_in_index'] ) ) {
1179                  continue;
1180              }
1181  
1182              $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
1183              $endpoint_data   = array(
1184                  'methods' => array_keys( $callback['methods'] ),
1185              );
1186  
1187              if ( isset( $callback['args'] ) ) {
1188                  $endpoint_data['args'] = array();
1189                  foreach ( $callback['args'] as $key => $opts ) {
1190                      $arg_data = array(
1191                          'required' => ! empty( $opts['required'] ),
1192                      );
1193                      if ( isset( $opts['default'] ) ) {
1194                          $arg_data['default'] = $opts['default'];
1195                      }
1196                      if ( isset( $opts['enum'] ) ) {
1197                          $arg_data['enum'] = $opts['enum'];
1198                      }
1199                      if ( isset( $opts['description'] ) ) {
1200                          $arg_data['description'] = $opts['description'];
1201                      }
1202                      if ( isset( $opts['type'] ) ) {
1203                          $arg_data['type'] = $opts['type'];
1204                      }
1205                      if ( isset( $opts['items'] ) ) {
1206                          $arg_data['items'] = $opts['items'];
1207                      }
1208                      $endpoint_data['args'][ $key ] = $arg_data;
1209                  }
1210              }
1211  
1212              $data['endpoints'][] = $endpoint_data;
1213  
1214              // For non-variable routes, generate links.
1215              if ( strpos( $route, '{' ) === false ) {
1216                  $data['_links'] = array(
1217                      'self' => rest_url( $route ),
1218                  );
1219              }
1220          }
1221  
1222          if ( empty( $data['methods'] ) ) {
1223              // No methods supported, hide the route.
1224              return null;
1225          }
1226  
1227          return $data;
1228      }
1229  
1230      /**
1231       * Sends an HTTP status code.
1232       *
1233       * @since 4.4.0
1234       *
1235       * @param int $code HTTP status.
1236       */
1237  	protected function set_status( $code ) {
1238          status_header( $code );
1239      }
1240  
1241      /**
1242       * Sends an HTTP header.
1243       *
1244       * @since 4.4.0
1245       *
1246       * @param string $key Header key.
1247       * @param string $value Header value.
1248       */
1249  	public function send_header( $key, $value ) {
1250          /*
1251           * Sanitize as per RFC2616 (Section 4.2):
1252           *
1253           * Any LWS that occurs between field-content MAY be replaced with a
1254           * single SP before interpreting the field value or forwarding the
1255           * message downstream.
1256           */
1257          $value = preg_replace( '/\s+/', ' ', $value );
1258          header( sprintf( '%s: %s', $key, $value ) );
1259      }
1260  
1261      /**
1262       * Sends multiple HTTP headers.
1263       *
1264       * @since 4.4.0
1265       *
1266       * @param array $headers Map of header name to header value.
1267       */
1268  	public function send_headers( $headers ) {
1269          foreach ( $headers as $key => $value ) {
1270              $this->send_header( $key, $value );
1271          }
1272      }
1273  
1274      /**
1275       * Removes an HTTP header from the current response.
1276       *
1277       * @since 4.8.0
1278       *
1279       * @param string $key Header key.
1280       */
1281  	public function remove_header( $key ) {
1282          header_remove( $key );
1283      }
1284  
1285      /**
1286       * Retrieves the raw request entity (body).
1287       *
1288       * @since 4.4.0
1289       *
1290       * @global string $HTTP_RAW_POST_DATA Raw post data.
1291       *
1292       * @return string Raw request data.
1293       */
1294  	public static function get_raw_data() {
1295          global $HTTP_RAW_POST_DATA;
1296  
1297          /*
1298           * A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
1299           * but we can do it ourself.
1300           */
1301          if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
1302              $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
1303          }
1304  
1305          return $HTTP_RAW_POST_DATA;
1306      }
1307  
1308      /**
1309       * Extracts headers from a PHP-style $_SERVER array.
1310       *
1311       * @since 4.4.0
1312       *
1313       * @param array $server Associative array similar to `$_SERVER`.
1314       * @return array Headers extracted from the input.
1315       */
1316  	public function get_headers( $server ) {
1317          $headers = array();
1318  
1319          // CONTENT_* headers are not prefixed with HTTP_.
1320          $additional = array(
1321              'CONTENT_LENGTH' => true,
1322              'CONTENT_MD5'    => true,
1323              'CONTENT_TYPE'   => true,
1324          );
1325  
1326          foreach ( $server as $key => $value ) {
1327              if ( strpos( $key, 'HTTP_' ) === 0 ) {
1328                  $headers[ substr( $key, 5 ) ] = $value;
1329              } elseif ( isset( $additional[ $key ] ) ) {
1330                  $headers[ $key ] = $value;
1331              }
1332          }
1333  
1334          return $headers;
1335      }
1336  }


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