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