3 * REST API: WP_REST_Server class
11 * Core class used to implement the WordPress REST API server.
15 class WP_REST_Server {
18 * Alias for GET transport method.
23 const READABLE = 'GET';
26 * Alias for POST transport method.
31 const CREATABLE = 'POST';
34 * Alias for POST, PUT, PATCH transport methods together.
39 const EDITABLE = 'POST, PUT, PATCH';
42 * Alias for DELETE transport method.
47 const DELETABLE = 'DELETE';
50 * Alias for GET, POST, PUT, PATCH & DELETE transport methods together.
55 const ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE';
58 * Namespaces registered to the server.
64 protected $namespaces = array();
67 * Endpoints registered to the server.
73 protected $endpoints = array();
76 * Options defined for the routes.
82 protected $route_options = array();
85 * Instantiates the REST server.
90 public function __construct() {
91 $this->endpoints = array(
94 'callback' => array( $this, 'get_index' ),
107 * Checks the authentication headers if supplied.
112 * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful
113 * or no authentication provided
115 public function check_authentication() {
117 * Pass an authentication error to the API
119 * This is used to pass a WP_Error from an authentication method back to
122 * Authentication methods should check first if they're being used, as
123 * multiple authentication methods can be enabled on a site (cookies,
124 * HTTP basic auth, OAuth). If the authentication method hooked in is
125 * not actually being attempted, null should be returned to indicate
126 * another authentication method should check instead. Similarly,
127 * callbacks should ensure the value is `null` before checking for
130 * A WP_Error instance can be returned if an error occurs, and this should
131 * match the format used by API methods internally (that is, the `status`
132 * data should be used). A callback can return `true` to indicate that
133 * the authentication method was used, and it succeeded.
137 * @param WP_Error|null|bool WP_Error if authentication error, null if authentication
138 * method wasn't used, true if authentication succeeded.
140 return apply_filters( 'rest_authentication_errors', null );
144 * Converts an error to a response object.
146 * This iterates over all error codes and messages to change it into a flat
147 * array. This enables simpler client behaviour, as it is represented as a
148 * list in JSON rather than an object/map.
153 * @param WP_Error $error WP_Error instance.
154 * @return WP_REST_Response List of associative arrays with code and message keys.
156 protected function error_to_response( $error ) {
157 $error_data = $error->get_error_data();
159 if ( is_array( $error_data ) && isset( $error_data['status'] ) ) {
160 $status = $error_data['status'];
167 foreach ( (array) $error->errors as $code => $messages ) {
168 foreach ( (array) $messages as $message ) {
169 $errors[] = array( 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) );
174 if ( count( $errors ) > 1 ) {
175 // Remove the primary error.
176 array_shift( $errors );
177 $data['additional_errors'] = $errors;
180 $response = new WP_REST_Response( $data, $status );
186 * Retrieves an appropriate error representation in JSON.
188 * Note: This should only be used in WP_REST_Server::serve_request(), as it
189 * cannot handle WP_Error internally. All callbacks and other internal methods
190 * should instead return a WP_Error with the data set to an array that includes
191 * a 'status' key, with the value being the HTTP status to send.
196 * @param string $code WP_Error-style code.
197 * @param string $message Human-readable message.
198 * @param int $status Optional. HTTP status code to send. Default null.
199 * @return string JSON representation of the error
201 protected function json_error( $code, $message, $status = null ) {
203 $this->set_status( $status );
206 $error = compact( 'code', 'message' );
208 return wp_json_encode( $error );
212 * Handles serving an API request.
214 * Matches the current server URI to a route and runs the first matching
215 * callback then outputs a JSON representation of the returned value.
220 * @see WP_REST_Server::dispatch()
222 * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
224 * @return false|null Null if not served and a HEAD request, false otherwise.
226 public function serve_request( $path = null ) {
227 $content_type = isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json';
228 $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
231 * Mitigate possible JSONP Flash attacks.
233 * http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
235 $this->send_header( 'X-Content-Type-Options', 'nosniff' );
236 $this->send_header( 'Access-Control-Expose-Headers', 'X-WP-Total, X-WP-TotalPages' );
237 $this->send_header( 'Access-Control-Allow-Headers', 'Authorization' );
240 * Send nocache headers on authenticated requests.
244 * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
246 $send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
247 if ( $send_no_cache_headers ) {
248 foreach ( wp_get_nocache_headers() as $header => $header_value ) {
249 $this->send_header( $header, $header_value );
254 * Filter whether the REST API is enabled.
258 * @param bool $rest_enabled Whether the REST API is enabled. Default true.
260 $enabled = apply_filters( 'rest_enabled', true );
263 * Filter whether jsonp is enabled.
267 * @param bool $jsonp_enabled Whether jsonp is enabled. Default true.
269 $jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true );
271 $jsonp_callback = null;
274 echo $this->json_error( 'rest_disabled', __( 'The REST API is disabled on this site.' ), 404 );
277 if ( isset( $_GET['_jsonp'] ) ) {
278 if ( ! $jsonp_enabled ) {
279 echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
283 // Check for invalid characters (only alphanumeric allowed).
284 if ( is_string( $_GET['_jsonp'] ) ) {
285 $jsonp_callback = preg_replace( '/[^\w\.]/', '', wp_unslash( $_GET['_jsonp'] ), -1, $illegal_char_count );
286 if ( 0 !== $illegal_char_count ) {
287 $jsonp_callback = null;
290 if ( null === $jsonp_callback ) {
291 echo $this->json_error( 'rest_callback_invalid', __( 'The JSONP callback function is invalid.' ), 400 );
296 if ( empty( $path ) ) {
297 if ( isset( $_SERVER['PATH_INFO'] ) ) {
298 $path = $_SERVER['PATH_INFO'];
304 $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
306 $request->set_query_params( $_GET );
307 $request->set_body_params( $_POST );
308 $request->set_file_params( $_FILES );
309 $request->set_headers( $this->get_headers( $_SERVER ) );
310 $request->set_body( $this->get_raw_data() );
313 * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
314 * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
317 if ( isset( $_GET['_method'] ) ) {
318 $request->set_method( $_GET['_method'] );
319 } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
320 $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
323 $result = $this->check_authentication();
325 if ( ! is_wp_error( $result ) ) {
326 $result = $this->dispatch( $request );
329 // Normalize to either WP_Error or WP_REST_Response...
330 $result = rest_ensure_response( $result );
332 // ...then convert WP_Error across.
333 if ( is_wp_error( $result ) ) {
334 $result = $this->error_to_response( $result );
338 * Filter the API response.
340 * Allows modification of the response before returning.
344 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
345 * @param WP_REST_Server $this Server instance.
346 * @param WP_REST_Request $request Request used to generate the response.
348 $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
350 // Wrap the response in an envelope if asked for.
351 if ( isset( $_GET['_envelope'] ) ) {
352 $result = $this->envelope_response( $result, isset( $_GET['_embed'] ) );
355 // Send extra data from response objects.
356 $headers = $result->get_headers();
357 $this->send_headers( $headers );
359 $code = $result->get_status();
360 $this->set_status( $code );
363 * Filter whether the request has already been served.
365 * Allow sending the request manually - by returning true, the API result
366 * will not be sent to the client.
370 * @param bool $served Whether the request has already been served.
372 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
373 * @param WP_REST_Request $request Request used to generate the response.
374 * @param WP_REST_Server $this Server instance.
376 $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
379 if ( 'HEAD' === $request->get_method() ) {
383 // Embed links inside the request.
384 $result = $this->response_to_data( $result, isset( $_GET['_embed'] ) );
386 $result = wp_json_encode( $result );
388 $json_error_message = $this->get_json_last_error();
389 if ( $json_error_message ) {
390 $json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, array( 'status' => 500 ) );
391 $result = $this->error_to_response( $json_error_obj );
392 $result = wp_json_encode( $result->data[0] );
395 if ( $jsonp_callback ) {
396 // Prepend '/**/' to mitigate possible JSONP Flash attacks
397 // http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
398 echo '/**/' . $jsonp_callback . '(' . $result . ')';
407 * Converts a response to data to send.
412 * @param WP_REST_Response $response Response object.
413 * @param bool $embed Whether links should be embedded.
415 * Data with sub-requests embedded.
417 * @type array [$_links] Links.
418 * @type array [$_embedded] Embeddeds.
421 public function response_to_data( $response, $embed ) {
422 $data = $response->get_data();
423 $links = $this->get_response_links( $response );
425 if ( ! empty( $links ) ) {
426 // Convert links to part of the data.
427 $data['_links'] = $links;
430 // Determine if this is a numeric array.
431 if ( wp_is_numeric_array( $data ) ) {
432 $data = array_map( array( $this, 'embed_links' ), $data );
434 $data = $this->embed_links( $data );
442 * Retrieves links from a response.
444 * Extracts the links from a response into a structured hash, suitable for
451 * @param WP_REST_Response $response Response to extract links from.
452 * @return array Map of link relation to list of link hashes.
454 public static function get_response_links( $response ) {
455 $links = $response->get_links();
457 if ( empty( $links ) ) {
461 // Convert links to part of the data.
463 foreach ( $links as $rel => $items ) {
464 $data[ $rel ] = array();
466 foreach ( $items as $item ) {
467 $attributes = $item['attributes'];
468 $attributes['href'] = $item['href'];
469 $data[ $rel ][] = $attributes;
477 * Embeds the links from the data into the request.
482 * @param array $data Data from the request.
484 * Data with sub-requests embedded.
486 * @type array [$_links] Links.
487 * @type array [$_embedded] Embeddeds.
490 protected function embed_links( $data ) {
491 if ( empty( $data['_links'] ) ) {
496 $api_root = rest_url();
498 foreach ( $data['_links'] as $rel => $links ) {
499 // Ignore links to self, for obvious reasons.
500 if ( 'self' === $rel ) {
506 foreach ( $links as $item ) {
507 // Determine if the link is embeddable.
508 if ( empty( $item['embeddable'] ) || strpos( $item['href'], $api_root ) !== 0 ) {
509 // Ensure we keep the same order.
514 // Run through our internal routing and serve.
515 $route = substr( $item['href'], strlen( untrailingslashit( $api_root ) ) );
516 $query_params = array();
518 // Parse out URL query parameters.
519 $parsed = parse_url( $route );
520 if ( empty( $parsed['path'] ) ) {
525 if ( ! empty( $parsed['query'] ) ) {
526 parse_str( $parsed['query'], $query_params );
528 // Ensure magic quotes are stripped.
529 if ( get_magic_quotes_gpc() ) {
530 $query_params = stripslashes_deep( $query_params );
534 // Embedded resources get passed context=embed.
535 if ( empty( $query_params['context'] ) ) {
536 $query_params['context'] = 'embed';
539 $request = new WP_REST_Request( 'GET', $parsed['path'] );
541 $request->set_query_params( $query_params );
542 $response = $this->dispatch( $request );
544 $embeds[] = $this->response_to_data( $response, false );
547 // Determine if any real links were found.
548 $has_links = count( array_filter( $embeds ) );
550 $embedded[ $rel ] = $embeds;
554 if ( ! empty( $embedded ) ) {
555 $data['_embedded'] = $embedded;
562 * Wraps the response in an envelope.
564 * The enveloping technique is used to work around browser/client
565 * compatibility issues. Essentially, it converts the full HTTP response to
571 * @param WP_REST_Response $response Response object.
572 * @param bool $embed Whether links should be embedded.
573 * @return WP_REST_Response New response with wrapped data
575 public function envelope_response( $response, $embed ) {
577 'body' => $this->response_to_data( $response, $embed ),
578 'status' => $response->get_status(),
579 'headers' => $response->get_headers(),
583 * Filter the enveloped form of a response.
587 * @param array $envelope Envelope data.
588 * @param WP_REST_Response $response Original response data.
590 $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
592 // Ensure it's still a response and return.
593 return rest_ensure_response( $envelope );
597 * Registers a route to the server.
602 * @param string $namespace Namespace.
603 * @param string $route The REST route.
604 * @param array $route_args Route arguments.
605 * @param bool $override Optional. Whether the route should be overriden if it already exists.
608 public function register_route( $namespace, $route, $route_args, $override = false ) {
609 if ( ! isset( $this->namespaces[ $namespace ] ) ) {
610 $this->namespaces[ $namespace ] = array();
612 $this->register_route( $namespace, '/' . $namespace, array(
614 'methods' => self::READABLE,
615 'callback' => array( $this, 'get_namespace_index' ),
617 'namespace' => array(
618 'default' => $namespace,
628 // Associative to avoid double-registration.
629 $this->namespaces[ $namespace ][ $route ] = true;
630 $route_args['namespace'] = $namespace;
632 if ( $override || empty( $this->endpoints[ $route ] ) ) {
633 $this->endpoints[ $route ] = $route_args;
635 $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
640 * Retrieves the route map.
642 * The route map is an associative array with path regexes as the keys. The
643 * value is an indexed array with the callback function/method as the first
644 * item, and a bitmask of HTTP methods as the second item (see the class
647 * Each route can be mapped to more than one callback by using an array of
648 * the indexed arrays. This allows mapping e.g. GET requests to one callback
649 * and POST requests to another.
651 * Note that the path regexes (array keys) must have @ escaped, as this is
652 * used as the delimiter with preg_match()
657 * @return array `'/path/regex' => array( $callback, $bitmask )` or
658 * `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
660 public function get_routes() {
663 * Filter the array of available endpoints.
667 * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
668 * to an array of callbacks for the endpoint. These take the format
669 * `'/path/regex' => array( $callback, $bitmask )` or
670 * `'/path/regex' => array( array( $callback, $bitmask ).
672 $endpoints = apply_filters( 'rest_endpoints', $this->endpoints );
674 // Normalise the endpoints.
677 'accept_json' => false,
678 'accept_raw' => false,
679 'show_in_index' => true,
683 foreach ( $endpoints as $route => &$handlers ) {
685 if ( isset( $handlers['callback'] ) ) {
686 // Single endpoint, add one deeper.
687 $handlers = array( $handlers );
690 if ( ! isset( $this->route_options[ $route ] ) ) {
691 $this->route_options[ $route ] = array();
694 foreach ( $handlers as $key => &$handler ) {
696 if ( ! is_numeric( $key ) ) {
697 // Route option, move it to the options.
698 $this->route_options[ $route ][ $key ] = $handler;
699 unset( $handlers[ $key ] );
703 $handler = wp_parse_args( $handler, $defaults );
705 // Allow comma-separated HTTP methods.
706 if ( is_string( $handler['methods'] ) ) {
707 $methods = explode( ',', $handler['methods'] );
708 } else if ( is_array( $handler['methods'] ) ) {
709 $methods = $handler['methods'];
714 $handler['methods'] = array();
716 foreach ( $methods as $method ) {
717 $method = strtoupper( trim( $method ) );
718 $handler['methods'][ $method ] = true;
726 * Retrieves namespaces registered on the server.
731 * @return array List of registered namespaces.
733 public function get_namespaces() {
734 return array_keys( $this->namespaces );
738 * Retrieves specified options for a route.
743 * @param string $route Route pattern to fetch options for.
744 * @return array|null Data as an associative array if found, or null if not found.
746 public function get_route_options( $route ) {
747 if ( ! isset( $this->route_options[ $route ] ) ) {
751 return $this->route_options[ $route ];
755 * Matches the request to a callback and call it.
760 * @param WP_REST_Request $request Request to attempt dispatching.
761 * @return WP_REST_Response Response returned by the callback.
763 public function dispatch( $request ) {
765 * Filter the pre-calculated result of a REST dispatch request.
767 * Allow hijacking the request before dispatching by returning a non-empty. The returned value
768 * will be used to serve the request instead.
772 * @param mixed $result Response to replace the requested version with. Can be anything
773 * a normal endpoint can return, or null to not hijack the request.
774 * @param WP_REST_Server $this Server instance.
775 * @param WP_REST_Request $request Request used to generate the response.
777 $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
779 if ( ! empty( $result ) ) {
783 $method = $request->get_method();
784 $path = $request->get_route();
786 foreach ( $this->get_routes() as $route => $handlers ) {
787 $match = preg_match( '@^' . $route . '$@i', $path, $args );
793 foreach ( $handlers as $handler ) {
794 $callback = $handler['callback'];
797 $checked_method = 'HEAD' === $method ? 'GET' : $method;
798 if ( empty( $handler['methods'][ $checked_method ] ) ) {
802 if ( ! is_callable( $callback ) ) {
803 $response = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) );
806 if ( ! is_wp_error( $response ) ) {
807 // Remove the redundant preg_match argument.
810 $request->set_url_params( $args );
811 $request->set_attributes( $handler );
813 $request->sanitize_params();
817 foreach ( $handler['args'] as $arg => $options ) {
818 if ( isset( $options['default'] ) ) {
819 $defaults[ $arg ] = $options['default'];
823 $request->set_default_params( $defaults );
825 $check_required = $request->has_valid_params();
826 if ( is_wp_error( $check_required ) ) {
827 $response = $check_required;
831 if ( ! is_wp_error( $response ) ) {
832 // Check permission specified on the route.
833 if ( ! empty( $handler['permission_callback'] ) ) {
834 $permission = call_user_func( $handler['permission_callback'], $request );
836 if ( is_wp_error( $permission ) ) {
837 $response = $permission;
838 } else if ( false === $permission || null === $permission ) {
839 $response = new WP_Error( 'rest_forbidden', __( "You don't have permission to do this." ), array( 'status' => 403 ) );
844 if ( ! is_wp_error( $response ) ) {
846 * Filter the REST dispatch request result.
848 * Allow plugins to override dispatching the request.
852 * @param bool $dispatch_result Dispatch result, will be used if not empty.
853 * @param WP_REST_Request $request Request used to generate the response.
855 $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request );
857 // Allow plugins to halt the request via this filter.
858 if ( null !== $dispatch_result ) {
859 $response = $dispatch_result;
861 $response = call_user_func( $callback, $request );
865 if ( is_wp_error( $response ) ) {
866 $response = $this->error_to_response( $response );
868 $response = rest_ensure_response( $response );
871 $response->set_matched_route( $route );
872 $response->set_matched_handler( $handler );
878 return $this->error_to_response( new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), array( 'status' => 404 ) ) );
882 * Returns if an error occurred during most recent JSON encode/decode.
884 * Strings to be translated will be in format like
885 * "Encoding error: Maximum stack depth exceeded".
890 * @return bool|string Boolean false or string error message.
892 protected function get_json_last_error() {
893 // See https://core.trac.wordpress.org/ticket/27799.
894 if ( ! function_exists( 'json_last_error' ) ) {
898 $last_error_code = json_last_error();
900 if ( ( defined( 'JSON_ERROR_NONE' ) && JSON_ERROR_NONE === $last_error_code ) || empty( $last_error_code ) ) {
904 return json_last_error_msg();
908 * Retrieves the site index.
910 * This endpoint describes the capabilities of the site.
915 * @param array $request {
918 * @type string $context Context.
920 * @return array Index entity
922 public function get_index( $request ) {
923 // General site data.
925 'name' => get_option( 'blogname' ),
926 'description' => get_option( 'blogdescription' ),
927 'url' => get_option( 'siteurl' ),
928 'namespaces' => array_keys( $this->namespaces ),
929 'authentication' => array(),
930 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
933 $response = new WP_REST_Response( $available );
935 $response->add_link( 'help', 'http://v2.wp-api.org/' );
938 * Filter the API root index data.
940 * This contains the data describing the API. This includes information
941 * about supported authentication schemes, supported namespaces, routes
942 * available on the API, and a small amount of data about the site.
946 * @param WP_REST_Response $response Response data.
948 return apply_filters( 'rest_index', $response );
952 * Retrieves the index for a namespace.
957 * @param WP_REST_Request $request REST request instance.
958 * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
959 * WP_Error if the namespace isn't set.
961 public function get_namespace_index( $request ) {
962 $namespace = $request['namespace'];
964 if ( ! isset( $this->namespaces[ $namespace ] ) ) {
965 return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) );
968 $routes = $this->namespaces[ $namespace ];
969 $endpoints = array_intersect_key( $this->get_routes(), $routes );
972 'namespace' => $namespace,
973 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ),
975 $response = rest_ensure_response( $data );
977 // Link to the root index.
978 $response->add_link( 'up', rest_url( '/' ) );
981 * Filter the namespace index data.
983 * This typically is just the route data for the namespace, but you can
984 * add any data you'd like here.
988 * @param WP_REST_Response $response Response data.
989 * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
991 return apply_filters( 'rest_namespace_index', $response, $request );
995 * Retrieves the publicly-visible data for routes.
1000 * @param array $routes Routes to get data for.
1001 * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
1002 * @return array Route data to expose in indexes.
1004 public function get_data_for_routes( $routes, $context = 'view' ) {
1005 $available = array();
1007 // Find the available routes.
1008 foreach ( $routes as $route => $callbacks ) {
1009 $data = $this->get_data_for_route( $route, $callbacks, $context );
1010 if ( empty( $data ) ) {
1015 * Filter the REST endpoint data.
1019 * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
1021 $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
1025 * Filter the publicly-visible data for routes.
1027 * This data is exposed on indexes and can be used by clients or
1028 * developers to investigate the site and find out how to use it. It
1029 * acts as a form of self-documentation.
1033 * @param array $available Map of route to route data.
1034 * @param array $routes Internal route data as an associative array.
1036 return apply_filters( 'rest_route_data', $available, $routes );
1040 * Retrieves publicly-visible data for the route.
1045 * @param string $route Route to get data for.
1046 * @param array $callbacks Callbacks to convert to data.
1047 * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
1048 * @return array|null Data for the route, or null if no publicly-visible data.
1050 public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
1053 'methods' => array(),
1054 'endpoints' => array(),
1057 if ( isset( $this->route_options[ $route ] ) ) {
1058 $options = $this->route_options[ $route ];
1060 if ( isset( $options['namespace'] ) ) {
1061 $data['namespace'] = $options['namespace'];
1064 if ( isset( $options['schema'] ) && 'help' === $context ) {
1065 $data['schema'] = call_user_func( $options['schema'] );
1069 $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
1071 foreach ( $callbacks as $callback ) {
1072 // Skip to the next route if any callback is hidden.
1073 if ( empty( $callback['show_in_index'] ) ) {
1077 $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
1078 $endpoint_data = array(
1079 'methods' => array_keys( $callback['methods'] ),
1082 if ( isset( $callback['args'] ) ) {
1083 $endpoint_data['args'] = array();
1084 foreach ( $callback['args'] as $key => $opts ) {
1086 'required' => ! empty( $opts['required'] ),
1088 if ( isset( $opts['default'] ) ) {
1089 $arg_data['default'] = $opts['default'];
1091 if ( isset( $opts['enum'] ) ) {
1092 $arg_data['enum'] = $opts['enum'];
1094 if ( isset( $opts['description'] ) ) {
1095 $arg_data['description'] = $opts['description'];
1097 $endpoint_data['args'][ $key ] = $arg_data;
1101 $data['endpoints'][] = $endpoint_data;
1103 // For non-variable routes, generate links.
1104 if ( strpos( $route, '{' ) === false ) {
1105 $data['_links'] = array(
1106 'self' => rest_url( $route ),
1111 if ( empty( $data['methods'] ) ) {
1112 // No methods supported, hide the route.
1120 * Sends an HTTP status code.
1125 * @param int $code HTTP status.
1127 protected function set_status( $code ) {
1128 status_header( $code );
1132 * Sends an HTTP header.
1137 * @param string $key Header key.
1138 * @param string $value Header value.
1140 public function send_header( $key, $value ) {
1142 * Sanitize as per RFC2616 (Section 4.2):
1144 * Any LWS that occurs between field-content MAY be replaced with a
1145 * single SP before interpreting the field value or forwarding the
1146 * message downstream.
1148 $value = preg_replace( '/\s+/', ' ', $value );
1149 header( sprintf( '%s: %s', $key, $value ) );
1153 * Sends multiple HTTP headers.
1158 * @param array $headers Map of header name to header value.
1160 public function send_headers( $headers ) {
1161 foreach ( $headers as $key => $value ) {
1162 $this->send_header( $key, $value );
1167 * Retrieves the raw request entity (body).
1172 * @global string $HTTP_RAW_POST_DATA Raw post data.
1174 * @return string Raw request data.
1176 public static function get_raw_data() {
1177 global $HTTP_RAW_POST_DATA;
1180 * A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
1181 * but we can do it ourself.
1183 if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
1184 $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
1187 return $HTTP_RAW_POST_DATA;
1191 * Extracts headers from a PHP-style $_SERVER array.
1196 * @param array $server Associative array similar to `$_SERVER`.
1197 * @return array Headers extracted from the input.
1199 public function get_headers( $server ) {
1202 // CONTENT_* headers are not prefixed with HTTP_.
1203 $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true );
1205 foreach ( $server as $key => $value ) {
1206 if ( strpos( $key, 'HTTP_' ) === 0 ) {
1207 $headers[ substr( $key, 5 ) ] = $value;
1208 } elseif ( isset( $additional[ $key ] ) ) {
1209 $headers[ $key ] = $value;