class-wp-rest-server.php 38 KB

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