Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

1311 linhas
37 KiB

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