class-wp-rest-server.php 38 KB

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