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( wp_unslash( $_GET ) );
307 $request->set_body_params( wp_unslash( $_POST ) );
308 $request->set_file_params( $_FILES );
309 $request->set_headers( $this->get_headers( wp_unslash( $_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.
343 * @since 4.5.0 Applied to embedded responses.
345 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
346 * @param WP_REST_Server $this Server instance.
347 * @param WP_REST_Request $request Request used to generate the response.
349 $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
351 // Wrap the response in an envelope if asked for.
352 if ( isset( $_GET['_envelope'] ) ) {
353 $result = $this->envelope_response( $result, isset( $_GET['_embed'] ) );
356 // Send extra data from response objects.
357 $headers = $result->get_headers();
358 $this->send_headers( $headers );
360 $code = $result->get_status();
361 $this->set_status( $code );
364 * Filter whether the request has already been served.
366 * Allow sending the request manually - by returning true, the API result
367 * will not be sent to the client.
371 * @param bool $served Whether the request has already been served.
373 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
374 * @param WP_REST_Request $request Request used to generate the response.
375 * @param WP_REST_Server $this Server instance.
377 $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
380 if ( 'HEAD' === $request->get_method() ) {
384 // Embed links inside the request.
385 $result = $this->response_to_data( $result, isset( $_GET['_embed'] ) );
387 $result = wp_json_encode( $result );
389 $json_error_message = $this->get_json_last_error();
390 if ( $json_error_message ) {
391 $json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, array( 'status' => 500 ) );
392 $result = $this->error_to_response( $json_error_obj );
393 $result = wp_json_encode( $result->data[0] );
396 if ( $jsonp_callback ) {
397 // Prepend '/**/' to mitigate possible JSONP Flash attacks
398 // http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
399 echo '/**/' . $jsonp_callback . '(' . $result . ')';
408 * Converts a response to data to send.
413 * @param WP_REST_Response $response Response object.
414 * @param bool $embed Whether links should be embedded.
416 * Data with sub-requests embedded.
418 * @type array [$_links] Links.
419 * @type array [$_embedded] Embeddeds.
422 public function response_to_data( $response, $embed ) {
423 $data = $response->get_data();
424 $links = $this->get_compact_response_links( $response );
426 if ( ! empty( $links ) ) {
427 // Convert links to part of the data.
428 $data['_links'] = $links;
431 // Determine if this is a numeric array.
432 if ( wp_is_numeric_array( $data ) ) {
433 $data = array_map( array( $this, 'embed_links' ), $data );
435 $data = $this->embed_links( $data );
443 * Retrieves links from a response.
445 * Extracts the links from a response into a structured hash, suitable for
452 * @param WP_REST_Response $response Response to extract links from.
453 * @return array Map of link relation to list of link hashes.
455 public static function get_response_links( $response ) {
456 $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 * Retrieves the CURIEs (compact URIs) used for relations.
479 * Extracts the links from a response into a structured hash, suitable for
486 * @param WP_REST_Response $response Response to extract links from.
487 * @return array Map of link relation to list of link hashes.
489 public static function get_compact_response_links( $response ) {
490 $links = self::get_response_links( $response );
492 if ( empty( $links ) ) {
496 $curies = $response->get_curies();
497 $used_curies = array();
499 foreach ( $links as $rel => $items ) {
501 // Convert $rel URIs to their compact versions if they exist.
502 foreach ( $curies as $curie ) {
503 $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
504 if ( strpos( $rel, $href_prefix ) !== 0 ) {
508 // Relation now changes from '$uri' to '$curie:$relation'
509 $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
510 preg_match( '!' . $rel_regex . '!', $rel, $matches );
512 $new_rel = $curie['name'] . ':' . $matches[1];
513 $used_curies[ $curie['name'] ] = $curie;
514 $links[ $new_rel ] = $items;
515 unset( $links[ $rel ] );
521 // Push the curies onto the start of the links array.
522 if ( $used_curies ) {
523 $links['curies'] = array_values( $used_curies );
530 * Embeds the links from the data into the request.
535 * @param array $data Data from the request.
537 * Data with sub-requests embedded.
539 * @type array [$_links] Links.
540 * @type array [$_embedded] Embeddeds.
543 protected function embed_links( $data ) {
544 if ( empty( $data['_links'] ) ) {
550 foreach ( $data['_links'] as $rel => $links ) {
551 // Ignore links to self, for obvious reasons.
552 if ( 'self' === $rel ) {
558 foreach ( $links as $item ) {
559 // Determine if the link is embeddable.
560 if ( empty( $item['embeddable'] ) ) {
561 // Ensure we keep the same order.
566 // Run through our internal routing and serve.
567 $request = WP_REST_Request::from_url( $item['href'] );
573 // Embedded resources get passed context=embed.
574 if ( empty( $request['context'] ) ) {
575 $request['context'] = 'embed';
578 $response = $this->dispatch( $request );
580 /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
581 $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
583 $embeds[] = $this->response_to_data( $response, false );
586 // Determine if any real links were found.
587 $has_links = count( array_filter( $embeds ) );
589 $embedded[ $rel ] = $embeds;
593 if ( ! empty( $embedded ) ) {
594 $data['_embedded'] = $embedded;
601 * Wraps the response in an envelope.
603 * The enveloping technique is used to work around browser/client
604 * compatibility issues. Essentially, it converts the full HTTP response to
610 * @param WP_REST_Response $response Response object.
611 * @param bool $embed Whether links should be embedded.
612 * @return WP_REST_Response New response with wrapped data
614 public function envelope_response( $response, $embed ) {
616 'body' => $this->response_to_data( $response, $embed ),
617 'status' => $response->get_status(),
618 'headers' => $response->get_headers(),
622 * Filter the enveloped form of a response.
626 * @param array $envelope Envelope data.
627 * @param WP_REST_Response $response Original response data.
629 $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
631 // Ensure it's still a response and return.
632 return rest_ensure_response( $envelope );
636 * Registers a route to the server.
641 * @param string $namespace Namespace.
642 * @param string $route The REST route.
643 * @param array $route_args Route arguments.
644 * @param bool $override Optional. Whether the route should be overriden if it already exists.
647 public function register_route( $namespace, $route, $route_args, $override = false ) {
648 if ( ! isset( $this->namespaces[ $namespace ] ) ) {
649 $this->namespaces[ $namespace ] = array();
651 $this->register_route( $namespace, '/' . $namespace, array(
653 'methods' => self::READABLE,
654 'callback' => array( $this, 'get_namespace_index' ),
656 'namespace' => array(
657 'default' => $namespace,
667 // Associative to avoid double-registration.
668 $this->namespaces[ $namespace ][ $route ] = true;
669 $route_args['namespace'] = $namespace;
671 if ( $override || empty( $this->endpoints[ $route ] ) ) {
672 $this->endpoints[ $route ] = $route_args;
674 $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
679 * Retrieves the route map.
681 * The route map is an associative array with path regexes as the keys. The
682 * value is an indexed array with the callback function/method as the first
683 * item, and a bitmask of HTTP methods as the second item (see the class
686 * Each route can be mapped to more than one callback by using an array of
687 * the indexed arrays. This allows mapping e.g. GET requests to one callback
688 * and POST requests to another.
690 * Note that the path regexes (array keys) must have @ escaped, as this is
691 * used as the delimiter with preg_match()
696 * @return array `'/path/regex' => array( $callback, $bitmask )` or
697 * `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
699 public function get_routes() {
702 * Filter the array of available endpoints.
706 * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
707 * to an array of callbacks for the endpoint. These take the format
708 * `'/path/regex' => array( $callback, $bitmask )` or
709 * `'/path/regex' => array( array( $callback, $bitmask ).
711 $endpoints = apply_filters( 'rest_endpoints', $this->endpoints );
713 // Normalise the endpoints.
716 'accept_json' => false,
717 'accept_raw' => false,
718 'show_in_index' => true,
722 foreach ( $endpoints as $route => &$handlers ) {
724 if ( isset( $handlers['callback'] ) ) {
725 // Single endpoint, add one deeper.
726 $handlers = array( $handlers );
729 if ( ! isset( $this->route_options[ $route ] ) ) {
730 $this->route_options[ $route ] = array();
733 foreach ( $handlers as $key => &$handler ) {
735 if ( ! is_numeric( $key ) ) {
736 // Route option, move it to the options.
737 $this->route_options[ $route ][ $key ] = $handler;
738 unset( $handlers[ $key ] );
742 $handler = wp_parse_args( $handler, $defaults );
744 // Allow comma-separated HTTP methods.
745 if ( is_string( $handler['methods'] ) ) {
746 $methods = explode( ',', $handler['methods'] );
747 } else if ( is_array( $handler['methods'] ) ) {
748 $methods = $handler['methods'];
753 $handler['methods'] = array();
755 foreach ( $methods as $method ) {
756 $method = strtoupper( trim( $method ) );
757 $handler['methods'][ $method ] = true;
765 * Retrieves namespaces registered on the server.
770 * @return array List of registered namespaces.
772 public function get_namespaces() {
773 return array_keys( $this->namespaces );
777 * Retrieves specified options for a route.
782 * @param string $route Route pattern to fetch options for.
783 * @return array|null Data as an associative array if found, or null if not found.
785 public function get_route_options( $route ) {
786 if ( ! isset( $this->route_options[ $route ] ) ) {
790 return $this->route_options[ $route ];
794 * Matches the request to a callback and call it.
799 * @param WP_REST_Request $request Request to attempt dispatching.
800 * @return WP_REST_Response Response returned by the callback.
802 public function dispatch( $request ) {
804 * Filter the pre-calculated result of a REST dispatch request.
806 * Allow hijacking the request before dispatching by returning a non-empty. The returned value
807 * will be used to serve the request instead.
811 * @param mixed $result Response to replace the requested version with. Can be anything
812 * a normal endpoint can return, or null to not hijack the request.
813 * @param WP_REST_Server $this Server instance.
814 * @param WP_REST_Request $request Request used to generate the response.
816 $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
818 if ( ! empty( $result ) ) {
822 $method = $request->get_method();
823 $path = $request->get_route();
825 foreach ( $this->get_routes() as $route => $handlers ) {
826 $match = preg_match( '@^' . $route . '$@i', $path, $args );
832 foreach ( $handlers as $handler ) {
833 $callback = $handler['callback'];
836 // Fallback to GET method if no HEAD method is registered.
837 $checked_method = $method;
838 if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
839 $checked_method = 'GET';
841 if ( empty( $handler['methods'][ $checked_method ] ) ) {
845 if ( ! is_callable( $callback ) ) {
846 $response = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) );
849 if ( ! is_wp_error( $response ) ) {
850 // Remove the redundant preg_match argument.
853 $request->set_url_params( $args );
854 $request->set_attributes( $handler );
856 $request->sanitize_params();
860 foreach ( $handler['args'] as $arg => $options ) {
861 if ( isset( $options['default'] ) ) {
862 $defaults[ $arg ] = $options['default'];
866 $request->set_default_params( $defaults );
868 $check_required = $request->has_valid_params();
869 if ( is_wp_error( $check_required ) ) {
870 $response = $check_required;
874 if ( ! is_wp_error( $response ) ) {
875 // Check permission specified on the route.
876 if ( ! empty( $handler['permission_callback'] ) ) {
877 $permission = call_user_func( $handler['permission_callback'], $request );
879 if ( is_wp_error( $permission ) ) {
880 $response = $permission;
881 } else if ( false === $permission || null === $permission ) {
882 $response = new WP_Error( 'rest_forbidden', __( "You don't have permission to do this." ), array( 'status' => 403 ) );
887 if ( ! is_wp_error( $response ) ) {
889 * Filter the REST dispatch request result.
891 * Allow plugins to override dispatching the request.
894 * @since 4.5.0 Added `$route` and `$handler` parameters.
896 * @param bool $dispatch_result Dispatch result, will be used if not empty.
897 * @param WP_REST_Request $request Request used to generate the response.
898 * @param string $route Route matched for the request.
899 * @param array $handler Route handler used for the request.
901 $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
903 // Allow plugins to halt the request via this filter.
904 if ( null !== $dispatch_result ) {
905 $response = $dispatch_result;
907 $response = call_user_func( $callback, $request );
911 if ( is_wp_error( $response ) ) {
912 $response = $this->error_to_response( $response );
914 $response = rest_ensure_response( $response );
917 $response->set_matched_route( $route );
918 $response->set_matched_handler( $handler );
924 return $this->error_to_response( new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), array( 'status' => 404 ) ) );
928 * Returns if an error occurred during most recent JSON encode/decode.
930 * Strings to be translated will be in format like
931 * "Encoding error: Maximum stack depth exceeded".
936 * @return bool|string Boolean false or string error message.
938 protected function get_json_last_error() {
939 // See https://core.trac.wordpress.org/ticket/27799.
940 if ( ! function_exists( 'json_last_error' ) ) {
944 $last_error_code = json_last_error();
946 if ( ( defined( 'JSON_ERROR_NONE' ) && JSON_ERROR_NONE === $last_error_code ) || empty( $last_error_code ) ) {
950 return json_last_error_msg();
954 * Retrieves the site index.
956 * This endpoint describes the capabilities of the site.
961 * @param array $request {
964 * @type string $context Context.
966 * @return array Index entity
968 public function get_index( $request ) {
969 // General site data.
971 'name' => get_option( 'blogname' ),
972 'description' => get_option( 'blogdescription' ),
973 'url' => get_option( 'siteurl' ),
974 'home' => home_url(),
975 'namespaces' => array_keys( $this->namespaces ),
976 'authentication' => array(),
977 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
980 $response = new WP_REST_Response( $available );
982 $response->add_link( 'help', 'http://v2.wp-api.org/' );
985 * Filter the API root index data.
987 * This contains the data describing the API. This includes information
988 * about supported authentication schemes, supported namespaces, routes
989 * available on the API, and a small amount of data about the site.
993 * @param WP_REST_Response $response Response data.
995 return apply_filters( 'rest_index', $response );
999 * Retrieves the index for a namespace.
1004 * @param WP_REST_Request $request REST request instance.
1005 * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
1006 * WP_Error if the namespace isn't set.
1008 public function get_namespace_index( $request ) {
1009 $namespace = $request['namespace'];
1011 if ( ! isset( $this->namespaces[ $namespace ] ) ) {
1012 return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) );
1015 $routes = $this->namespaces[ $namespace ];
1016 $endpoints = array_intersect_key( $this->get_routes(), $routes );
1019 'namespace' => $namespace,
1020 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ),
1022 $response = rest_ensure_response( $data );
1024 // Link to the root index.
1025 $response->add_link( 'up', rest_url( '/' ) );
1028 * Filter the namespace index data.
1030 * This typically is just the route data for the namespace, but you can
1031 * add any data you'd like here.
1035 * @param WP_REST_Response $response Response data.
1036 * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
1038 return apply_filters( 'rest_namespace_index', $response, $request );
1042 * Retrieves the publicly-visible data for routes.
1047 * @param array $routes Routes to get data for.
1048 * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
1049 * @return array Route data to expose in indexes.
1051 public function get_data_for_routes( $routes, $context = 'view' ) {
1052 $available = array();
1054 // Find the available routes.
1055 foreach ( $routes as $route => $callbacks ) {
1056 $data = $this->get_data_for_route( $route, $callbacks, $context );
1057 if ( empty( $data ) ) {
1062 * Filter the REST endpoint data.
1066 * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
1068 $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
1072 * Filter the publicly-visible data for routes.
1074 * This data is exposed on indexes and can be used by clients or
1075 * developers to investigate the site and find out how to use it. It
1076 * acts as a form of self-documentation.
1080 * @param array $available Map of route to route data.
1081 * @param array $routes Internal route data as an associative array.
1083 return apply_filters( 'rest_route_data', $available, $routes );
1087 * Retrieves publicly-visible data for the route.
1092 * @param string $route Route to get data for.
1093 * @param array $callbacks Callbacks to convert to data.
1094 * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
1095 * @return array|null Data for the route, or null if no publicly-visible data.
1097 public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
1100 'methods' => array(),
1101 'endpoints' => array(),
1104 if ( isset( $this->route_options[ $route ] ) ) {
1105 $options = $this->route_options[ $route ];
1107 if ( isset( $options['namespace'] ) ) {
1108 $data['namespace'] = $options['namespace'];
1111 if ( isset( $options['schema'] ) && 'help' === $context ) {
1112 $data['schema'] = call_user_func( $options['schema'] );
1116 $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
1118 foreach ( $callbacks as $callback ) {
1119 // Skip to the next route if any callback is hidden.
1120 if ( empty( $callback['show_in_index'] ) ) {
1124 $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
1125 $endpoint_data = array(
1126 'methods' => array_keys( $callback['methods'] ),
1129 if ( isset( $callback['args'] ) ) {
1130 $endpoint_data['args'] = array();
1131 foreach ( $callback['args'] as $key => $opts ) {
1133 'required' => ! empty( $opts['required'] ),
1135 if ( isset( $opts['default'] ) ) {
1136 $arg_data['default'] = $opts['default'];
1138 if ( isset( $opts['enum'] ) ) {
1139 $arg_data['enum'] = $opts['enum'];
1141 if ( isset( $opts['description'] ) ) {
1142 $arg_data['description'] = $opts['description'];
1144 $endpoint_data['args'][ $key ] = $arg_data;
1148 $data['endpoints'][] = $endpoint_data;
1150 // For non-variable routes, generate links.
1151 if ( strpos( $route, '{' ) === false ) {
1152 $data['_links'] = array(
1153 'self' => rest_url( $route ),
1158 if ( empty( $data['methods'] ) ) {
1159 // No methods supported, hide the route.
1167 * Sends an HTTP status code.
1172 * @param int $code HTTP status.
1174 protected function set_status( $code ) {
1175 status_header( $code );
1179 * Sends an HTTP header.
1184 * @param string $key Header key.
1185 * @param string $value Header value.
1187 public function send_header( $key, $value ) {
1189 * Sanitize as per RFC2616 (Section 4.2):
1191 * Any LWS that occurs between field-content MAY be replaced with a
1192 * single SP before interpreting the field value or forwarding the
1193 * message downstream.
1195 $value = preg_replace( '/\s+/', ' ', $value );
1196 header( sprintf( '%s: %s', $key, $value ) );
1200 * Sends multiple HTTP headers.
1205 * @param array $headers Map of header name to header value.
1207 public function send_headers( $headers ) {
1208 foreach ( $headers as $key => $value ) {
1209 $this->send_header( $key, $value );
1214 * Retrieves the raw request entity (body).
1219 * @global string $HTTP_RAW_POST_DATA Raw post data.
1221 * @return string Raw request data.
1223 public static function get_raw_data() {
1224 global $HTTP_RAW_POST_DATA;
1227 * A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
1228 * but we can do it ourself.
1230 if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
1231 $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
1234 return $HTTP_RAW_POST_DATA;
1238 * Extracts headers from a PHP-style $_SERVER array.
1243 * @param array $server Associative array similar to `$_SERVER`.
1244 * @return array Headers extracted from the input.
1246 public function get_headers( $server ) {
1249 // CONTENT_* headers are not prefixed with HTTP_.
1250 $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true );
1252 foreach ( $server as $key => $value ) {
1253 if ( strpos( $key, 'HTTP_' ) === 0 ) {
1254 $headers[ substr( $key, 5 ) ] = $value;
1255 } elseif ( isset( $additional[ $key ] ) ) {
1256 $headers[ $key ] = $value;