]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/rest-api.php
WordPress 4.4
[autoinstalls/wordpress.git] / wp-includes / rest-api.php
1 <?php
2 /**
3  * REST API functions.
4  *
5  * @package WordPress
6  * @subpackage REST_API
7  * @since 4.4.0
8  */
9
10 /**
11  * Version number for our API.
12  *
13  * @var string
14  */
15 define( 'REST_API_VERSION', '2.0' );
16
17 /**
18  * Registers a REST API route.
19  *
20  * @since 4.4.0
21  *
22  * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
23  *
24  * @param string $namespace The first URL segment after core prefix. Should be unique to your package/plugin.
25  * @param string $route     The base URL for route you are adding.
26  * @param array  $args      Optional. Either an array of options for the endpoint, or an array of arrays for
27  *                          multiple methods. Default empty array.
28  * @param bool   $override  Optional. If the route already exists, should we override it? True overrides,
29  *                          false merges (with newer overriding if duplicate keys exist). Default false.
30  * @return bool True on success, false on error.
31  */
32 function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
33         /** @var WP_REST_Server $wp_rest_server */
34         global $wp_rest_server;
35
36         if ( empty( $namespace ) ) {
37                 /*
38                  * Non-namespaced routes are not allowed, with the exception of the main
39                  * and namespace indexes. If you really need to register a
40                  * non-namespaced route, call `WP_REST_Server::register_route` directly.
41                  */
42                 _doing_it_wrong( 'register_rest_route', 'Routes must be namespaced with plugin or theme name and version.', '4.4.0' );
43                 return false;
44         } else if ( empty( $route ) ) {
45                 _doing_it_wrong( 'register_rest_route', 'Route must be specified.', '4.4.0' );
46                 return false;
47         }
48
49         if ( isset( $args['callback'] ) ) {
50                 // Upgrade a single set to multiple.
51                 $args = array( $args );
52         }
53
54         $defaults = array(
55                 'methods'         => 'GET',
56                 'callback'        => null,
57                 'args'            => array(),
58         );
59         foreach ( $args as $key => &$arg_group ) {
60                 if ( ! is_numeric( $arg_group ) ) {
61                         // Route option, skip here.
62                         continue;
63                 }
64
65                 $arg_group = array_merge( $defaults, $arg_group );
66         }
67
68         $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
69         $wp_rest_server->register_route( $namespace, $full_route, $args, $override );
70         return true;
71 }
72
73 /**
74  * Registers rewrite rules for the API.
75  *
76  * @since 4.4.0
77  *
78  * @see rest_api_register_rewrites()
79  * @global WP $wp Current WordPress environment instance.
80  */
81 function rest_api_init() {
82         rest_api_register_rewrites();
83
84         global $wp;
85         $wp->add_query_var( 'rest_route' );
86 }
87
88 /**
89  * Adds REST rewrite rules.
90  *
91  * @since 4.4.0
92  *
93  * @see add_rewrite_rule()
94  */
95 function rest_api_register_rewrites() {
96         add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$','index.php?rest_route=/','top' );
97         add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?','index.php?rest_route=/$matches[1]','top' );
98 }
99
100 /**
101  * Registers the default REST API filters.
102  *
103  * Attached to the {@see 'rest_api_init'} action
104  * to make testing and disabling these filters easier.
105  *
106  * @since 4.4.0
107  */
108 function rest_api_default_filters() {
109         // Deprecated reporting.
110         add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 );
111         add_filter( 'deprecated_function_trigger_error', '__return_false' );
112         add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 );
113         add_filter( 'deprecated_argument_trigger_error', '__return_false' );
114
115         // Default serving.
116         add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
117         add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
118
119         add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );
120 }
121
122 /**
123  * Loads the REST API.
124  *
125  * @since 4.4.0
126  *
127  * @global WP             $wp             Current WordPress environment instance.
128  * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
129  */
130 function rest_api_loaded() {
131         if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
132                 return;
133         }
134
135         /**
136          * Whether this is a REST Request.
137          *
138          * @since 4.4.0
139          * @var bool
140          */
141         define( 'REST_REQUEST', true );
142
143         /** @var WP_REST_Server $wp_rest_server */
144         global $wp_rest_server;
145
146         /**
147          * Filter the REST Server Class.
148          *
149          * This filter allows you to adjust the server class used by the API, using a
150          * different class to handle requests.
151          *
152          * @since 4.4.0
153          *
154          * @param string $class_name The name of the server class. Default 'WP_REST_Server'.
155          */
156         $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
157         $wp_rest_server = new $wp_rest_server_class;
158
159         /**
160          * Fires when preparing to serve an API request.
161          *
162          * Endpoint objects should be created and register their hooks on this action rather
163          * than another action to ensure they're only loaded when needed.
164          *
165          * @since 4.4.0
166          *
167          * @param WP_REST_Server $wp_rest_server Server object.
168          */
169         do_action( 'rest_api_init', $wp_rest_server );
170
171         // Fire off the request.
172         $wp_rest_server->serve_request( $GLOBALS['wp']->query_vars['rest_route'] );
173
174         // We're done.
175         die();
176 }
177
178 /**
179  * Retrieves the URL prefix for any API resource.
180  *
181  * @since 4.4.0
182  *
183  * @return string Prefix.
184  */
185 function rest_get_url_prefix() {
186         /**
187          * Filter the REST URL prefix.
188          *
189          * @since 4.4.0
190          *
191          * @param string $prefix URL prefix. Default 'wp-json'.
192          */
193         return apply_filters( 'rest_url_prefix', 'wp-json' );
194 }
195
196 /**
197  * Retrieves the URL to a REST endpoint on a site.
198  *
199  * Note: The returned URL is NOT escaped.
200  *
201  * @since 4.4.0
202  *
203  * @todo Check if this is even necessary
204  *
205  * @param int    $blog_id Optional. Blog ID. Default of null returns URL for current blog.
206  * @param string $path    Optional. REST route. Default '/'.
207  * @param string $scheme  Optional. Sanitization scheme. Default 'rest'.
208  * @return string Full URL to the endpoint.
209  */
210 function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
211         if ( empty( $path ) ) {
212                 $path = '/';
213         }
214
215         if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
216                 $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
217                 $url .= '/' . ltrim( $path, '/' );
218         } else {
219                 $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
220
221                 $path = '/' . ltrim( $path, '/' );
222
223                 $url = add_query_arg( 'rest_route', $path, $url );
224         }
225
226         if ( is_ssl() ) {
227                 // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
228                 if ( $_SERVER['SERVER_NAME'] === parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) ) {
229                         $url = set_url_scheme( $url, 'https' );
230                 }
231         }
232
233         /**
234          * Filter the REST URL.
235          *
236          * Use this filter to adjust the url returned by the `get_rest_url` function.
237          *
238          * @since 4.4.0
239          *
240          * @param string $url     REST URL.
241          * @param string $path    REST route.
242          * @param int    $blog_id Blog ID.
243          * @param string $scheme  Sanitization scheme.
244          */
245         return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
246 }
247
248 /**
249  * Retrieves the URL to a REST endpoint.
250  *
251  * Note: The returned URL is NOT escaped.
252  *
253  * @since 4.4.0
254  *
255  * @param string $path   Optional. REST route. Default empty.
256  * @param string $scheme Optional. Sanitization scheme. Default 'json'.
257  * @return string Full URL to the endpoint.
258  */
259 function rest_url( $path = '', $scheme = 'json' ) {
260         return get_rest_url( null, $path, $scheme );
261 }
262
263 /**
264  * Do a REST request.
265  *
266  * Used primarily to route internal requests through WP_REST_Server.
267  *
268  * @since 4.4.0
269  *
270  * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
271  *
272  * @param WP_REST_Request|string $request Request.
273  * @return WP_REST_Response REST response.
274  */
275 function rest_do_request( $request ) {
276         global $wp_rest_server;
277         $request = rest_ensure_request( $request );
278         return $wp_rest_server->dispatch( $request );
279 }
280
281 /**
282  * Ensures request arguments are a request object (for consistency).
283  *
284  * @since 4.4.0
285  *
286  * @param array|WP_REST_Request $request Request to check.
287  * @return WP_REST_Request REST request instance.
288  */
289 function rest_ensure_request( $request ) {
290         if ( $request instanceof WP_REST_Request ) {
291                 return $request;
292         }
293
294         return new WP_REST_Request( 'GET', '', $request );
295 }
296
297 /**
298  * Ensures a REST response is a response object (for consistency).
299  *
300  * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
301  * without needing to double-check the object. Will also allow WP_Error to indicate error
302  * responses, so users should immediately check for this value.
303  *
304  * @since 4.4.0
305  *
306  * @param WP_Error|WP_HTTP_Response|mixed $response Response to check.
307  * @return mixed WP_Error if response generated an error, WP_HTTP_Response if response
308  *               is a already an instance, otherwise returns a new WP_REST_Response instance.
309  */
310 function rest_ensure_response( $response ) {
311         if ( is_wp_error( $response ) ) {
312                 return $response;
313         }
314
315         if ( $response instanceof WP_HTTP_Response ) {
316                 return $response;
317         }
318
319         return new WP_REST_Response( $response );
320 }
321
322 /**
323  * Handles _deprecated_function() errors.
324  *
325  * @since 4.4.0
326  *
327  * @param string $function    Function name.
328  * @param string $replacement Replacement function name.
329  * @param string $version     Version.
330  */
331 function rest_handle_deprecated_function( $function, $replacement, $version ) {
332         if ( ! empty( $replacement ) ) {
333                 /* translators: 1: function name, 2: WordPress version number, 3: new function name */
334                 $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
335         } else {
336                 /* translators: 1: function name, 2: WordPress version number */
337                 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
338         }
339
340         header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
341 }
342
343 /**
344  * Handles _deprecated_argument() errors.
345  *
346  * @since 4.4.0
347  *
348  * @param string $function    Function name.
349  * @param string $replacement Replacement function name.
350  * @param string $version     Version.
351  */
352 function rest_handle_deprecated_argument( $function, $replacement, $version ) {
353         if ( ! empty( $replacement ) ) {
354                 /* translators: 1: function name, 2: WordPress version number, 3: new argument name */
355                 $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $replacement );
356         } else {
357                 /* translators: 1: function name, 2: WordPress version number */
358                 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
359         }
360
361         header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
362 }
363
364 /**
365  * Sends Cross-Origin Resource Sharing headers with API requests.
366  *
367  * @since 4.4.0
368  *
369  * @param mixed $value Response data.
370  * @return mixed Response data.
371  */
372 function rest_send_cors_headers( $value ) {
373         $origin = get_http_origin();
374
375         if ( $origin ) {
376                 header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
377                 header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
378                 header( 'Access-Control-Allow-Credentials: true' );
379         }
380
381         return $value;
382 }
383
384 /**
385  * Handles OPTIONS requests for the server.
386  *
387  * This is handled outside of the server code, as it doesn't obey normal route
388  * mapping.
389  *
390  * @since 4.4.0
391  *
392  * @param mixed           $response Current response, either response or `null` to indicate pass-through.
393  * @param WP_REST_Server  $handler  ResponseHandler instance (usually WP_REST_Server).
394  * @param WP_REST_Request $request  The request that was used to make current response.
395  * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
396  */
397 function rest_handle_options_request( $response, $handler, $request ) {
398         if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
399                 return $response;
400         }
401
402         $response = new WP_REST_Response();
403         $data = array();
404
405         $accept = array();
406
407         foreach ( $handler->get_routes() as $route => $endpoints ) {
408                 $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $args );
409
410                 if ( ! $match ) {
411                         continue;
412                 }
413
414                 $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
415                 $accept = array_merge( $accept, $data['methods'] );
416                 break;
417         }
418         $response->header( 'Accept', implode( ', ', $accept ) );
419
420         $response->set_data( $data );
421         return $response;
422 }
423
424 /**
425  * Sends the "Allow" header to state all methods that can be sent to the current route.
426  *
427  * @since 4.4.0
428  *
429  * @param WP_REST_Response $response Current response being served.
430  * @param WP_REST_Server   $server   ResponseHandler instance (usually WP_REST_Server).
431  * @param WP_REST_Request  $request  The request that was used to make current response.
432  * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
433  */
434 function rest_send_allow_header( $response, $server, $request ) {
435         $matched_route = $response->get_matched_route();
436
437         if ( ! $matched_route ) {
438                 return $response;
439         }
440
441         $routes = $server->get_routes();
442
443         $allowed_methods = array();
444
445         // Get the allowed methods across the routes.
446         foreach ( $routes[ $matched_route ] as $_handler ) {
447                 foreach ( $_handler['methods'] as $handler_method => $value ) {
448
449                         if ( ! empty( $_handler['permission_callback'] ) ) {
450
451                                 $permission = call_user_func( $_handler['permission_callback'], $request );
452
453                                 $allowed_methods[ $handler_method ] = true === $permission;
454                         } else {
455                                 $allowed_methods[ $handler_method ] = true;
456                         }
457                 }
458         }
459
460         // Strip out all the methods that are not allowed (false values).
461         $allowed_methods = array_filter( $allowed_methods );
462
463         if ( $allowed_methods ) {
464                 $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
465         }
466
467         return $response;
468 }
469
470 /**
471  * Adds the REST API URL to the WP RSD endpoint.
472  *
473  * @since 4.4.0
474  *
475  * @see get_rest_url()
476  */
477 function rest_output_rsd() {
478         $api_root = get_rest_url();
479
480         if ( empty( $api_root ) ) {
481                 return;
482         }
483         ?>
484         <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
485         <?php
486 }
487
488 /**
489  * Outputs the REST API link tag into page header.
490  *
491  * @since 4.4.0
492  *
493  * @see get_rest_url()
494  */
495 function rest_output_link_wp_head() {
496         $api_root = get_rest_url();
497
498         if ( empty( $api_root ) ) {
499                 return;
500         }
501
502         echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
503 }
504
505 /**
506  * Sends a Link header for the REST API.
507  *
508  * @since 4.4.0
509  */
510 function rest_output_link_header() {
511         if ( headers_sent() ) {
512                 return;
513         }
514
515         $api_root = get_rest_url();
516
517         if ( empty( $api_root ) ) {
518                 return;
519         }
520
521         header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
522 }
523
524 /**
525  * Checks for errors when using cookie-based authentication.
526  *
527  * WordPress' built-in cookie authentication is always active
528  * for logged in users. However, the API has to check nonces
529  * for each request to ensure users are not vulnerable to CSRF.
530  *
531  * @since 4.4.0
532  *
533  * @global mixed $wp_rest_auth_cookie
534  *
535  * @param WP_Error|mixed $result Error from another authentication handler, null if we should handle it,
536  *                               or another value if not.
537  * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
538  */
539 function rest_cookie_check_errors( $result ) {
540         if ( ! empty( $result ) ) {
541                 return $result;
542         }
543
544         global $wp_rest_auth_cookie;
545
546         /*
547          * Is cookie authentication being used? (If we get an auth
548          * error, but we're still logged in, another authentication
549          * must have been used).
550          */
551         if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
552                 return $result;
553         }
554
555         // Determine if there is a nonce.
556         $nonce = null;
557
558         if ( isset( $_REQUEST['_wpnonce'] ) ) {
559                 $nonce = $_REQUEST['_wpnonce'];
560         } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
561                 $nonce = $_SERVER['HTTP_X_WP_NONCE'];
562         }
563
564         if ( null === $nonce ) {
565                 // No nonce at all, so act as if it's an unauthenticated request.
566                 wp_set_current_user( 0 );
567                 return true;
568         }
569
570         // Check the nonce.
571         $result = wp_verify_nonce( $nonce, 'wp_rest' );
572
573         if ( ! $result ) {
574                 return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
575         }
576
577         return true;
578 }
579
580 /**
581  * Collects cookie authentication status.
582  *
583  * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
584  *
585  * @since 4.4.0
586  *
587  * @see current_action()
588  * @global mixed $wp_rest_auth_cookie
589  */
590 function rest_cookie_collect_status() {
591         global $wp_rest_auth_cookie;
592
593         $status_type = current_action();
594
595         if ( 'auth_cookie_valid' !== $status_type ) {
596                 $wp_rest_auth_cookie = substr( $status_type, 12 );
597                 return;
598         }
599
600         $wp_rest_auth_cookie = true;
601 }
602
603 /**
604  * Parses an RFC3339 timestamp into a DateTime.
605  *
606  * @since 4.4.0
607  *
608  * @param string $date      RFC3339 timestamp.
609  * @param bool   $force_utc Optional. Whether to force UTC timezone instead of using
610  *                          the timestamp's timezone. Default false.
611  * @return DateTime DateTime instance.
612  */
613 function rest_parse_date( $date, $force_utc = false ) {
614         if ( $force_utc ) {
615                 $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
616         }
617
618         $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
619
620         if ( ! preg_match( $regex, $date, $matches ) ) {
621                 return false;
622         }
623
624         return strtotime( $date );
625 }
626
627 /**
628  * Retrieves a local date with its GMT equivalent, in MySQL datetime format.
629  *
630  * @since 4.4.0
631  *
632  * @see rest_parse_date()
633  *
634  * @param string $date      RFC3339 timestamp.
635  * @param bool   $force_utc Whether a UTC timestamp should be forced. Default false.
636  * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
637  *                    null on failure.
638  */
639 function rest_get_date_with_gmt( $date, $force_utc = false ) {
640         $date = rest_parse_date( $date, $force_utc );
641
642         if ( empty( $date ) ) {
643                 return null;
644         }
645
646         $utc = date( 'Y-m-d H:i:s', $date );
647         $local = get_date_from_gmt( $utc );
648
649         return array( $local, $utc );
650 }