class-wp-rest-server.php 37 KB

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