Ei kuvausta

class-wp-rest-server.php 49KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  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. * Caches embedded requests.
  73. *
  74. * @since 5.4.0
  75. * @var array
  76. */
  77. protected $embed_cache = array();
  78. /**
  79. * Instantiates the REST server.
  80. *
  81. * @since 4.4.0
  82. */
  83. public function __construct() {
  84. $this->endpoints = array(
  85. // Meta endpoints.
  86. '/' => array(
  87. 'callback' => array( $this, 'get_index' ),
  88. 'methods' => 'GET',
  89. 'args' => array(
  90. 'context' => array(
  91. 'default' => 'view',
  92. ),
  93. ),
  94. ),
  95. '/batch/v1' => array(
  96. 'callback' => array( $this, 'serve_batch_request_v1' ),
  97. 'methods' => 'POST',
  98. 'args' => array(
  99. 'validation' => array(
  100. 'type' => 'string',
  101. 'enum' => array( 'require-all-validate', 'normal' ),
  102. 'default' => 'normal',
  103. ),
  104. 'requests' => array(
  105. 'required' => true,
  106. 'type' => 'array',
  107. 'maxItems' => $this->get_max_batch_size(),
  108. 'items' => array(
  109. 'type' => 'object',
  110. 'properties' => array(
  111. 'method' => array(
  112. 'type' => 'string',
  113. 'enum' => array( 'POST', 'PUT', 'PATCH', 'DELETE' ),
  114. 'default' => 'POST',
  115. ),
  116. 'path' => array(
  117. 'type' => 'string',
  118. 'required' => true,
  119. ),
  120. 'body' => array(
  121. 'type' => 'object',
  122. 'properties' => array(),
  123. 'additionalProperties' => true,
  124. ),
  125. 'headers' => array(
  126. 'type' => 'object',
  127. 'properties' => array(),
  128. 'additionalProperties' => array(
  129. 'type' => array( 'string', 'array' ),
  130. 'items' => array(
  131. 'type' => 'string',
  132. ),
  133. ),
  134. ),
  135. ),
  136. ),
  137. ),
  138. ),
  139. ),
  140. );
  141. }
  142. /**
  143. * Checks the authentication headers if supplied.
  144. *
  145. * @since 4.4.0
  146. *
  147. * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful
  148. * or no authentication provided
  149. */
  150. public function check_authentication() {
  151. /**
  152. * Filters REST API authentication errors.
  153. *
  154. * This is used to pass a WP_Error from an authentication method back to
  155. * the API.
  156. *
  157. * Authentication methods should check first if they're being used, as
  158. * multiple authentication methods can be enabled on a site (cookies,
  159. * HTTP basic auth, OAuth). If the authentication method hooked in is
  160. * not actually being attempted, null should be returned to indicate
  161. * another authentication method should check instead. Similarly,
  162. * callbacks should ensure the value is `null` before checking for
  163. * errors.
  164. *
  165. * A WP_Error instance can be returned if an error occurs, and this should
  166. * match the format used by API methods internally (that is, the `status`
  167. * data should be used). A callback can return `true` to indicate that
  168. * the authentication method was used, and it succeeded.
  169. *
  170. * @since 4.4.0
  171. *
  172. * @param WP_Error|null|true $errors WP_Error if authentication error, null if authentication
  173. * method wasn't used, true if authentication succeeded.
  174. */
  175. return apply_filters( 'rest_authentication_errors', null );
  176. }
  177. /**
  178. * Converts an error to a response object.
  179. *
  180. * This iterates over all error codes and messages to change it into a flat
  181. * array. This enables simpler client behaviour, as it is represented as a
  182. * list in JSON rather than an object/map.
  183. *
  184. * @since 4.4.0
  185. * @since 5.7.0 Converted to a wrapper of {@see rest_convert_error_to_response()}.
  186. *
  187. * @param WP_Error $error WP_Error instance.
  188. * @return WP_REST_Response List of associative arrays with code and message keys.
  189. */
  190. protected function error_to_response( $error ) {
  191. return rest_convert_error_to_response( $error );
  192. }
  193. /**
  194. * Retrieves an appropriate error representation in JSON.
  195. *
  196. * Note: This should only be used in WP_REST_Server::serve_request(), as it
  197. * cannot handle WP_Error internally. All callbacks and other internal methods
  198. * should instead return a WP_Error with the data set to an array that includes
  199. * a 'status' key, with the value being the HTTP status to send.
  200. *
  201. * @since 4.4.0
  202. *
  203. * @param string $code WP_Error-style code.
  204. * @param string $message Human-readable message.
  205. * @param int $status Optional. HTTP status code to send. Default null.
  206. * @return string JSON representation of the error
  207. */
  208. protected function json_error( $code, $message, $status = null ) {
  209. if ( $status ) {
  210. $this->set_status( $status );
  211. }
  212. $error = compact( 'code', 'message' );
  213. return wp_json_encode( $error );
  214. }
  215. /**
  216. * Handles serving a REST API request.
  217. *
  218. * Matches the current server URI to a route and runs the first matching
  219. * callback then outputs a JSON representation of the returned value.
  220. *
  221. * @since 4.4.0
  222. *
  223. * @see WP_REST_Server::dispatch()
  224. *
  225. * @global WP_User $current_user The currently authenticated user.
  226. *
  227. * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used.
  228. * Default null.
  229. * @return null|false Null if not served and a HEAD request, false otherwise.
  230. */
  231. public function serve_request( $path = null ) {
  232. /* @var WP_User|null $current_user */
  233. global $current_user;
  234. if ( $current_user instanceof WP_User && ! $current_user->exists() ) {
  235. /*
  236. * If there is no current user authenticated via other means, clear
  237. * the cached lack of user, so that an authenticate check can set it
  238. * properly.
  239. *
  240. * This is done because for authentications such as Application
  241. * Passwords, we don't want it to be accepted unless the current HTTP
  242. * request is a REST API request, which can't always be identified early
  243. * enough in evaluation.
  244. */
  245. $current_user = null;
  246. }
  247. /**
  248. * Filters whether JSONP is enabled for the REST API.
  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 = false;
  256. if ( isset( $_GET['_jsonp'] ) ) {
  257. $jsonp_callback = $_GET['_jsonp'];
  258. }
  259. $content_type = ( $jsonp_callback && $jsonp_enabled ) ? 'application/javascript' : 'application/json';
  260. $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) );
  261. $this->send_header( 'X-Robots-Tag', 'noindex' );
  262. $api_root = get_rest_url();
  263. if ( ! empty( $api_root ) ) {
  264. $this->send_header( 'Link', '<' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"' );
  265. }
  266. /*
  267. * Mitigate possible JSONP Flash attacks.
  268. *
  269. * https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  270. */
  271. $this->send_header( 'X-Content-Type-Options', 'nosniff' );
  272. $expose_headers = array( 'X-WP-Total', 'X-WP-TotalPages', 'Link' );
  273. /**
  274. * Filters the list of response headers that are exposed to REST API CORS requests.
  275. *
  276. * @since 5.5.0
  277. *
  278. * @param string[] $expose_headers The list of response headers to expose.
  279. */
  280. $expose_headers = apply_filters( 'rest_exposed_cors_headers', $expose_headers );
  281. $this->send_header( 'Access-Control-Expose-Headers', implode( ', ', $expose_headers ) );
  282. $allow_headers = array(
  283. 'Authorization',
  284. 'X-WP-Nonce',
  285. 'Content-Disposition',
  286. 'Content-MD5',
  287. 'Content-Type',
  288. );
  289. /**
  290. * Filters the list of request headers that are allowed for REST API CORS requests.
  291. *
  292. * The allowed headers are passed to the browser to specify which
  293. * headers can be passed to the REST API. By default, we allow the
  294. * Content-* headers needed to upload files to the media endpoints.
  295. * As well as the Authorization and Nonce headers for allowing authentication.
  296. *
  297. * @since 5.5.0
  298. *
  299. * @param string[] $allow_headers The list of request headers to allow.
  300. */
  301. $allow_headers = apply_filters( 'rest_allowed_cors_headers', $allow_headers );
  302. $this->send_header( 'Access-Control-Allow-Headers', implode( ', ', $allow_headers ) );
  303. /**
  304. * Filters whether to send nocache headers on a REST API request.
  305. *
  306. * @since 4.4.0
  307. *
  308. * @param bool $rest_send_nocache_headers Whether to send no-cache headers.
  309. */
  310. $send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() );
  311. if ( $send_no_cache_headers ) {
  312. foreach ( wp_get_nocache_headers() as $header => $header_value ) {
  313. if ( empty( $header_value ) ) {
  314. $this->remove_header( $header );
  315. } else {
  316. $this->send_header( $header, $header_value );
  317. }
  318. }
  319. }
  320. /**
  321. * Filters whether the REST API is enabled.
  322. *
  323. * @since 4.4.0
  324. * @deprecated 4.7.0 Use the {@see 'rest_authentication_errors'} filter to
  325. * restrict access to the REST API.
  326. *
  327. * @param bool $rest_enabled Whether the REST API is enabled. Default true.
  328. */
  329. apply_filters_deprecated(
  330. 'rest_enabled',
  331. array( true ),
  332. '4.7.0',
  333. 'rest_authentication_errors',
  334. sprintf(
  335. /* translators: %s: rest_authentication_errors */
  336. __( 'The REST API can no longer be completely disabled, the %s filter can be used to restrict access to the API, instead.' ),
  337. 'rest_authentication_errors'
  338. )
  339. );
  340. if ( $jsonp_callback ) {
  341. if ( ! $jsonp_enabled ) {
  342. echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 );
  343. return false;
  344. }
  345. if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) {
  346. echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 );
  347. return false;
  348. }
  349. }
  350. if ( empty( $path ) ) {
  351. if ( isset( $_SERVER['PATH_INFO'] ) ) {
  352. $path = $_SERVER['PATH_INFO'];
  353. } else {
  354. $path = '/';
  355. }
  356. }
  357. $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path );
  358. $request->set_query_params( wp_unslash( $_GET ) );
  359. $request->set_body_params( wp_unslash( $_POST ) );
  360. $request->set_file_params( $_FILES );
  361. $request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) );
  362. $request->set_body( self::get_raw_data() );
  363. /*
  364. * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check
  365. * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE
  366. * header.
  367. */
  368. if ( isset( $_GET['_method'] ) ) {
  369. $request->set_method( $_GET['_method'] );
  370. } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
  371. $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] );
  372. }
  373. $result = $this->check_authentication();
  374. if ( ! is_wp_error( $result ) ) {
  375. $result = $this->dispatch( $request );
  376. }
  377. // Normalize to either WP_Error or WP_REST_Response...
  378. $result = rest_ensure_response( $result );
  379. // ...then convert WP_Error across.
  380. if ( is_wp_error( $result ) ) {
  381. $result = $this->error_to_response( $result );
  382. }
  383. /**
  384. * Filters the REST API response.
  385. *
  386. * Allows modification of the response before returning.
  387. *
  388. * @since 4.4.0
  389. * @since 4.5.0 Applied to embedded responses.
  390. *
  391. * @param WP_HTTP_Response $result Result to send to the client. Usually a `WP_REST_Response`.
  392. * @param WP_REST_Server $server Server instance.
  393. * @param WP_REST_Request $request Request used to generate the response.
  394. */
  395. $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request );
  396. // Wrap the response in an envelope if asked for.
  397. if ( isset( $_GET['_envelope'] ) ) {
  398. $result = $this->envelope_response( $result, isset( $_GET['_embed'] ) );
  399. }
  400. // Send extra data from response objects.
  401. $headers = $result->get_headers();
  402. $this->send_headers( $headers );
  403. $code = $result->get_status();
  404. $this->set_status( $code );
  405. /**
  406. * Filters whether the REST API request has already been served.
  407. *
  408. * Allow sending the request manually - by returning true, the API result
  409. * will not be sent to the client.
  410. *
  411. * @since 4.4.0
  412. *
  413. * @param bool $served Whether the request has already been served.
  414. * Default false.
  415. * @param WP_HTTP_Response $result Result to send to the client. Usually a `WP_REST_Response`.
  416. * @param WP_REST_Request $request Request used to generate the response.
  417. * @param WP_REST_Server $server Server instance.
  418. */
  419. $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
  420. if ( ! $served ) {
  421. if ( 'HEAD' === $request->get_method() ) {
  422. return null;
  423. }
  424. // Embed links inside the request.
  425. $embed = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
  426. $result = $this->response_to_data( $result, $embed );
  427. /**
  428. * Filters the REST API response.
  429. *
  430. * Allows modification of the response data after inserting
  431. * embedded data (if any) and before echoing the response data.
  432. *
  433. * @since 4.8.1
  434. *
  435. * @param array $result Response data to send to the client.
  436. * @param WP_REST_Server $server Server instance.
  437. * @param WP_REST_Request $request Request used to generate the response.
  438. */
  439. $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
  440. // The 204 response shouldn't have a body.
  441. if ( 204 === $code || null === $result ) {
  442. return null;
  443. }
  444. $result = wp_json_encode( $result );
  445. $json_error_message = $this->get_json_last_error();
  446. if ( $json_error_message ) {
  447. $json_error_obj = new WP_Error(
  448. 'rest_encode_error',
  449. $json_error_message,
  450. array( 'status' => 500 )
  451. );
  452. $result = $this->error_to_response( $json_error_obj );
  453. $result = wp_json_encode( $result->data );
  454. }
  455. if ( $jsonp_callback ) {
  456. // Prepend '/**/' to mitigate possible JSONP Flash attacks.
  457. // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  458. echo '/**/' . $jsonp_callback . '(' . $result . ')';
  459. } else {
  460. echo $result;
  461. }
  462. }
  463. return null;
  464. }
  465. /**
  466. * Converts a response to data to send.
  467. *
  468. * @since 4.4.0
  469. * @since 5.4.0 The $embed parameter can now contain a list of link relations to include.
  470. *
  471. * @param WP_REST_Response $response Response object.
  472. * @param bool|string[] $embed Whether to embed all links, a filtered list of link relations, or no links.
  473. * @return array {
  474. * Data with sub-requests embedded.
  475. *
  476. * @type array $_links Links.
  477. * @type array $_embedded Embedded objects.
  478. * }
  479. */
  480. public function response_to_data( $response, $embed ) {
  481. $data = $response->get_data();
  482. $links = self::get_compact_response_links( $response );
  483. if ( ! empty( $links ) ) {
  484. // Convert links to part of the data.
  485. $data['_links'] = $links;
  486. }
  487. if ( $embed ) {
  488. $this->embed_cache = array();
  489. // Determine if this is a numeric array.
  490. if ( wp_is_numeric_array( $data ) ) {
  491. foreach ( $data as $key => $item ) {
  492. $data[ $key ] = $this->embed_links( $item, $embed );
  493. }
  494. } else {
  495. $data = $this->embed_links( $data, $embed );
  496. }
  497. $this->embed_cache = array();
  498. }
  499. return $data;
  500. }
  501. /**
  502. * Retrieves links from a response.
  503. *
  504. * Extracts the links from a response into a structured hash, suitable for
  505. * direct output.
  506. *
  507. * @since 4.4.0
  508. *
  509. * @param WP_REST_Response $response Response to extract links from.
  510. * @return array Map of link relation to list of link hashes.
  511. */
  512. public static function get_response_links( $response ) {
  513. $links = $response->get_links();
  514. if ( empty( $links ) ) {
  515. return array();
  516. }
  517. // Convert links to part of the data.
  518. $data = array();
  519. foreach ( $links as $rel => $items ) {
  520. $data[ $rel ] = array();
  521. foreach ( $items as $item ) {
  522. $attributes = $item['attributes'];
  523. $attributes['href'] = $item['href'];
  524. $data[ $rel ][] = $attributes;
  525. }
  526. }
  527. return $data;
  528. }
  529. /**
  530. * Retrieves the CURIEs (compact URIs) used for relations.
  531. *
  532. * Extracts the links from a response into a structured hash, suitable for
  533. * direct output.
  534. *
  535. * @since 4.5.0
  536. *
  537. * @param WP_REST_Response $response Response to extract links from.
  538. * @return array Map of link relation to list of link hashes.
  539. */
  540. public static function get_compact_response_links( $response ) {
  541. $links = self::get_response_links( $response );
  542. if ( empty( $links ) ) {
  543. return array();
  544. }
  545. $curies = $response->get_curies();
  546. $used_curies = array();
  547. foreach ( $links as $rel => $items ) {
  548. // Convert $rel URIs to their compact versions if they exist.
  549. foreach ( $curies as $curie ) {
  550. $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
  551. if ( strpos( $rel, $href_prefix ) !== 0 ) {
  552. continue;
  553. }
  554. // Relation now changes from '$uri' to '$curie:$relation'.
  555. $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
  556. preg_match( '!' . $rel_regex . '!', $rel, $matches );
  557. if ( $matches ) {
  558. $new_rel = $curie['name'] . ':' . $matches[1];
  559. $used_curies[ $curie['name'] ] = $curie;
  560. $links[ $new_rel ] = $items;
  561. unset( $links[ $rel ] );
  562. break;
  563. }
  564. }
  565. }
  566. // Push the curies onto the start of the links array.
  567. if ( $used_curies ) {
  568. $links['curies'] = array_values( $used_curies );
  569. }
  570. return $links;
  571. }
  572. /**
  573. * Embeds the links from the data into the request.
  574. *
  575. * @since 4.4.0
  576. * @since 5.4.0 The $embed parameter can now contain a list of link relations to include.
  577. *
  578. * @param array $data Data from the request.
  579. * @param bool|string[] $embed Whether to embed all links or a filtered list of link relations.
  580. * @return array {
  581. * Data with sub-requests embedded.
  582. *
  583. * @type array $_links Links.
  584. * @type array $_embedded Embedded objects.
  585. * }
  586. */
  587. protected function embed_links( $data, $embed = true ) {
  588. if ( empty( $data['_links'] ) ) {
  589. return $data;
  590. }
  591. $embedded = array();
  592. foreach ( $data['_links'] as $rel => $links ) {
  593. // If a list of relations was specified, and the link relation
  594. // is not in the list of allowed relations, don't process the link.
  595. if ( is_array( $embed ) && ! in_array( $rel, $embed, true ) ) {
  596. continue;
  597. }
  598. $embeds = array();
  599. foreach ( $links as $item ) {
  600. // Determine if the link is embeddable.
  601. if ( empty( $item['embeddable'] ) ) {
  602. // Ensure we keep the same order.
  603. $embeds[] = array();
  604. continue;
  605. }
  606. if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) {
  607. // Run through our internal routing and serve.
  608. $request = WP_REST_Request::from_url( $item['href'] );
  609. if ( ! $request ) {
  610. $embeds[] = array();
  611. continue;
  612. }
  613. // Embedded resources get passed context=embed.
  614. if ( empty( $request['context'] ) ) {
  615. $request['context'] = 'embed';
  616. }
  617. $response = $this->dispatch( $request );
  618. /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
  619. $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
  620. $this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false );
  621. }
  622. $embeds[] = $this->embed_cache[ $item['href'] ];
  623. }
  624. // Determine if any real links were found.
  625. $has_links = count( array_filter( $embeds ) );
  626. if ( $has_links ) {
  627. $embedded[ $rel ] = $embeds;
  628. }
  629. }
  630. if ( ! empty( $embedded ) ) {
  631. $data['_embedded'] = $embedded;
  632. }
  633. return $data;
  634. }
  635. /**
  636. * Wraps the response in an envelope.
  637. *
  638. * The enveloping technique is used to work around browser/client
  639. * compatibility issues. Essentially, it converts the full HTTP response to
  640. * data instead.
  641. *
  642. * @since 4.4.0
  643. *
  644. * @param WP_REST_Response $response Response object.
  645. * @param bool $embed Whether links should be embedded.
  646. * @return WP_REST_Response New response with wrapped data
  647. */
  648. public function envelope_response( $response, $embed ) {
  649. $envelope = array(
  650. 'body' => $this->response_to_data( $response, $embed ),
  651. 'status' => $response->get_status(),
  652. 'headers' => $response->get_headers(),
  653. );
  654. /**
  655. * Filters the enveloped form of a REST API response.
  656. *
  657. * @since 4.4.0
  658. *
  659. * @param array $envelope {
  660. * Envelope data.
  661. *
  662. * @type array $body Response data.
  663. * @type int $status The 3-digit HTTP status code.
  664. * @type array $headers Map of header name to header value.
  665. * }
  666. * @param WP_REST_Response $response Original response data.
  667. */
  668. $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
  669. // Ensure it's still a response and return.
  670. return rest_ensure_response( $envelope );
  671. }
  672. /**
  673. * Registers a route to the server.
  674. *
  675. * @since 4.4.0
  676. *
  677. * @param string $namespace Namespace.
  678. * @param string $route The REST route.
  679. * @param array $route_args Route arguments.
  680. * @param bool $override Optional. Whether the route should be overridden if it already exists.
  681. * Default false.
  682. */
  683. public function register_route( $namespace, $route, $route_args, $override = false ) {
  684. if ( ! isset( $this->namespaces[ $namespace ] ) ) {
  685. $this->namespaces[ $namespace ] = array();
  686. $this->register_route(
  687. $namespace,
  688. '/' . $namespace,
  689. array(
  690. array(
  691. 'methods' => self::READABLE,
  692. 'callback' => array( $this, 'get_namespace_index' ),
  693. 'args' => array(
  694. 'namespace' => array(
  695. 'default' => $namespace,
  696. ),
  697. 'context' => array(
  698. 'default' => 'view',
  699. ),
  700. ),
  701. ),
  702. )
  703. );
  704. }
  705. // Associative to avoid double-registration.
  706. $this->namespaces[ $namespace ][ $route ] = true;
  707. $route_args['namespace'] = $namespace;
  708. if ( $override || empty( $this->endpoints[ $route ] ) ) {
  709. $this->endpoints[ $route ] = $route_args;
  710. } else {
  711. $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
  712. }
  713. }
  714. /**
  715. * Retrieves the route map.
  716. *
  717. * The route map is an associative array with path regexes as the keys. The
  718. * value is an indexed array with the callback function/method as the first
  719. * item, and a bitmask of HTTP methods as the second item (see the class
  720. * constants).
  721. *
  722. * Each route can be mapped to more than one callback by using an array of
  723. * the indexed arrays. This allows mapping e.g. GET requests to one callback
  724. * and POST requests to another.
  725. *
  726. * Note that the path regexes (array keys) must have @ escaped, as this is
  727. * used as the delimiter with preg_match()
  728. *
  729. * @since 4.4.0
  730. * @since 5.4.0 Add $namespace parameter.
  731. *
  732. * @param string $namespace Optionally, only return routes in the given namespace.
  733. * @return array `'/path/regex' => array( $callback, $bitmask )` or
  734. * `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
  735. */
  736. public function get_routes( $namespace = '' ) {
  737. $endpoints = $this->endpoints;
  738. if ( $namespace ) {
  739. $endpoints = wp_list_filter( $endpoints, array( 'namespace' => $namespace ) );
  740. }
  741. /**
  742. * Filters the array of available REST API endpoints.
  743. *
  744. * @since 4.4.0
  745. *
  746. * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
  747. * to an array of callbacks for the endpoint. These take the format
  748. * `'/path/regex' => array( $callback, $bitmask )` or
  749. * `'/path/regex' => array( array( $callback, $bitmask ).
  750. */
  751. $endpoints = apply_filters( 'rest_endpoints', $endpoints );
  752. // Normalise the endpoints.
  753. $defaults = array(
  754. 'methods' => '',
  755. 'accept_json' => false,
  756. 'accept_raw' => false,
  757. 'show_in_index' => true,
  758. 'args' => array(),
  759. );
  760. foreach ( $endpoints as $route => &$handlers ) {
  761. if ( isset( $handlers['callback'] ) ) {
  762. // Single endpoint, add one deeper.
  763. $handlers = array( $handlers );
  764. }
  765. if ( ! isset( $this->route_options[ $route ] ) ) {
  766. $this->route_options[ $route ] = array();
  767. }
  768. foreach ( $handlers as $key => &$handler ) {
  769. if ( ! is_numeric( $key ) ) {
  770. // Route option, move it to the options.
  771. $this->route_options[ $route ][ $key ] = $handler;
  772. unset( $handlers[ $key ] );
  773. continue;
  774. }
  775. $handler = wp_parse_args( $handler, $defaults );
  776. // Allow comma-separated HTTP methods.
  777. if ( is_string( $handler['methods'] ) ) {
  778. $methods = explode( ',', $handler['methods'] );
  779. } elseif ( is_array( $handler['methods'] ) ) {
  780. $methods = $handler['methods'];
  781. } else {
  782. $methods = array();
  783. }
  784. $handler['methods'] = array();
  785. foreach ( $methods as $method ) {
  786. $method = strtoupper( trim( $method ) );
  787. $handler['methods'][ $method ] = true;
  788. }
  789. }
  790. }
  791. return $endpoints;
  792. }
  793. /**
  794. * Retrieves namespaces registered on the server.
  795. *
  796. * @since 4.4.0
  797. *
  798. * @return string[] List of registered namespaces.
  799. */
  800. public function get_namespaces() {
  801. return array_keys( $this->namespaces );
  802. }
  803. /**
  804. * Retrieves specified options for a route.
  805. *
  806. * @since 4.4.0
  807. *
  808. * @param string $route Route pattern to fetch options for.
  809. * @return array|null Data as an associative array if found, or null if not found.
  810. */
  811. public function get_route_options( $route ) {
  812. if ( ! isset( $this->route_options[ $route ] ) ) {
  813. return null;
  814. }
  815. return $this->route_options[ $route ];
  816. }
  817. /**
  818. * Matches the request to a callback and call it.
  819. *
  820. * @since 4.4.0
  821. *
  822. * @param WP_REST_Request $request Request to attempt dispatching.
  823. * @return WP_REST_Response Response returned by the callback.
  824. */
  825. public function dispatch( $request ) {
  826. /**
  827. * Filters the pre-calculated result of a REST API dispatch request.
  828. *
  829. * Allow hijacking the request before dispatching by returning a non-empty. The returned value
  830. * will be used to serve the request instead.
  831. *
  832. * @since 4.4.0
  833. *
  834. * @param mixed $result Response to replace the requested version with. Can be anything
  835. * a normal endpoint can return, or null to not hijack the request.
  836. * @param WP_REST_Server $server Server instance.
  837. * @param WP_REST_Request $request Request used to generate the response.
  838. */
  839. $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
  840. if ( ! empty( $result ) ) {
  841. return $result;
  842. }
  843. $error = null;
  844. $matched = $this->match_request_to_handler( $request );
  845. if ( is_wp_error( $matched ) ) {
  846. return $this->error_to_response( $matched );
  847. }
  848. list( $route, $handler ) = $matched;
  849. if ( ! is_callable( $handler['callback'] ) ) {
  850. $error = new WP_Error(
  851. 'rest_invalid_handler',
  852. __( 'The handler for the route is invalid.' ),
  853. array( 'status' => 500 )
  854. );
  855. }
  856. if ( ! is_wp_error( $error ) ) {
  857. $check_required = $request->has_valid_params();
  858. if ( is_wp_error( $check_required ) ) {
  859. $error = $check_required;
  860. } else {
  861. $check_sanitized = $request->sanitize_params();
  862. if ( is_wp_error( $check_sanitized ) ) {
  863. $error = $check_sanitized;
  864. }
  865. }
  866. }
  867. return $this->respond_to_request( $request, $route, $handler, $error );
  868. }
  869. /**
  870. * Matches a request object to its handler.
  871. *
  872. * @access private
  873. * @since 5.6.0
  874. *
  875. * @param WP_REST_Request $request The request object.
  876. * @return array|WP_Error The route and request handler on success or a WP_Error instance if no handler was found.
  877. */
  878. protected function match_request_to_handler( $request ) {
  879. $method = $request->get_method();
  880. $path = $request->get_route();
  881. $with_namespace = array();
  882. foreach ( $this->get_namespaces() as $namespace ) {
  883. if ( 0 === strpos( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) {
  884. $with_namespace[] = $this->get_routes( $namespace );
  885. }
  886. }
  887. if ( $with_namespace ) {
  888. $routes = array_merge( ...$with_namespace );
  889. } else {
  890. $routes = $this->get_routes();
  891. }
  892. foreach ( $routes as $route => $handlers ) {
  893. $match = preg_match( '@^' . $route . '$@i', $path, $matches );
  894. if ( ! $match ) {
  895. continue;
  896. }
  897. $args = array();
  898. foreach ( $matches as $param => $value ) {
  899. if ( ! is_int( $param ) ) {
  900. $args[ $param ] = $value;
  901. }
  902. }
  903. foreach ( $handlers as $handler ) {
  904. $callback = $handler['callback'];
  905. $response = null;
  906. // Fallback to GET method if no HEAD method is registered.
  907. $checked_method = $method;
  908. if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
  909. $checked_method = 'GET';
  910. }
  911. if ( empty( $handler['methods'][ $checked_method ] ) ) {
  912. continue;
  913. }
  914. if ( ! is_callable( $callback ) ) {
  915. return array( $route, $handler );
  916. }
  917. $request->set_url_params( $args );
  918. $request->set_attributes( $handler );
  919. $defaults = array();
  920. foreach ( $handler['args'] as $arg => $options ) {
  921. if ( isset( $options['default'] ) ) {
  922. $defaults[ $arg ] = $options['default'];
  923. }
  924. }
  925. $request->set_default_params( $defaults );
  926. return array( $route, $handler );
  927. }
  928. }
  929. return new WP_Error(
  930. 'rest_no_route',
  931. __( 'No route was found matching the URL and request method.' ),
  932. array( 'status' => 404 )
  933. );
  934. }
  935. /**
  936. * Dispatches the request to the callback handler.
  937. *
  938. * @access private
  939. * @since 5.6.0
  940. *
  941. * @param WP_REST_Request $request The request object.
  942. * @param array $handler The matched route handler.
  943. * @param string $route The matched route regex.
  944. * @param WP_Error|null $response The current error object if any.
  945. * @return WP_REST_Response
  946. */
  947. protected function respond_to_request( $request, $route, $handler, $response ) {
  948. /**
  949. * Filters the response before executing any REST API callbacks.
  950. *
  951. * Allows plugins to perform additional validation after a
  952. * request is initialized and matched to a registered route,
  953. * but before it is executed.
  954. *
  955. * Note that this filter will not be called for requests that
  956. * fail to authenticate or match to a registered route.
  957. *
  958. * @since 4.7.0
  959. *
  960. * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
  961. * Usually a WP_REST_Response or WP_Error.
  962. * @param array $handler Route handler used for the request.
  963. * @param WP_REST_Request $request Request used to generate the response.
  964. */
  965. $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
  966. // Check permission specified on the route.
  967. if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) {
  968. $permission = call_user_func( $handler['permission_callback'], $request );
  969. if ( is_wp_error( $permission ) ) {
  970. $response = $permission;
  971. } elseif ( false === $permission || null === $permission ) {
  972. $response = new WP_Error(
  973. 'rest_forbidden',
  974. __( 'Sorry, you are not allowed to do that.' ),
  975. array( 'status' => rest_authorization_required_code() )
  976. );
  977. }
  978. }
  979. if ( ! is_wp_error( $response ) ) {
  980. /**
  981. * Filters the REST API dispatch request result.
  982. *
  983. * Allow plugins to override dispatching the request.
  984. *
  985. * @since 4.4.0
  986. * @since 4.5.0 Added `$route` and `$handler` parameters.
  987. *
  988. * @param mixed $dispatch_result Dispatch result, will be used if not empty.
  989. * @param WP_REST_Request $request Request used to generate the response.
  990. * @param string $route Route matched for the request.
  991. * @param array $handler Route handler used for the request.
  992. */
  993. $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
  994. // Allow plugins to halt the request via this filter.
  995. if ( null !== $dispatch_result ) {
  996. $response = $dispatch_result;
  997. } else {
  998. $response = call_user_func( $handler['callback'], $request );
  999. }
  1000. }
  1001. /**
  1002. * Filters the response immediately after executing any REST API
  1003. * callbacks.
  1004. *
  1005. * Allows plugins to perform any needed cleanup, for example,
  1006. * to undo changes made during the {@see 'rest_request_before_callbacks'}
  1007. * filter.
  1008. *
  1009. * Note that this filter will not be called for requests that
  1010. * fail to authenticate or match to a registered route.
  1011. *
  1012. * Note that an endpoint's `permission_callback` can still be
  1013. * called after this filter - see `rest_send_allow_header()`.
  1014. *
  1015. * @since 4.7.0
  1016. *
  1017. * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
  1018. * Usually a WP_REST_Response or WP_Error.
  1019. * @param array $handler Route handler used for the request.
  1020. * @param WP_REST_Request $request Request used to generate the response.
  1021. */
  1022. $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
  1023. if ( is_wp_error( $response ) ) {
  1024. $response = $this->error_to_response( $response );
  1025. } else {
  1026. $response = rest_ensure_response( $response );
  1027. }
  1028. $response->set_matched_route( $route );
  1029. $response->set_matched_handler( $handler );
  1030. return $response;
  1031. }
  1032. /**
  1033. * Returns if an error occurred during most recent JSON encode/decode.
  1034. *
  1035. * Strings to be translated will be in format like
  1036. * "Encoding error: Maximum stack depth exceeded".
  1037. *
  1038. * @since 4.4.0
  1039. *
  1040. * @return false|string Boolean false or string error message.
  1041. */
  1042. protected function get_json_last_error() {
  1043. $last_error_code = json_last_error();
  1044. if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) {
  1045. return false;
  1046. }
  1047. return json_last_error_msg();
  1048. }
  1049. /**
  1050. * Retrieves the site index.
  1051. *
  1052. * This endpoint describes the capabilities of the site.
  1053. *
  1054. * @since 4.4.0
  1055. *
  1056. * @param array $request {
  1057. * Request.
  1058. *
  1059. * @type string $context Context.
  1060. * }
  1061. * @return WP_REST_Response The API root index data.
  1062. */
  1063. public function get_index( $request ) {
  1064. // General site data.
  1065. $available = array(
  1066. 'name' => get_option( 'blogname' ),
  1067. 'description' => get_option( 'blogdescription' ),
  1068. 'url' => get_option( 'siteurl' ),
  1069. 'home' => home_url(),
  1070. 'gmt_offset' => get_option( 'gmt_offset' ),
  1071. 'timezone_string' => get_option( 'timezone_string' ),
  1072. 'namespaces' => array_keys( $this->namespaces ),
  1073. 'authentication' => array(),
  1074. 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
  1075. );
  1076. $response = new WP_REST_Response( $available );
  1077. $response->add_link( 'help', 'https://developer.wordpress.org/rest-api/' );
  1078. $this->add_active_theme_link_to_index( $response );
  1079. $this->add_site_logo_to_index( $response );
  1080. /**
  1081. * Filters the REST API root index data.
  1082. *
  1083. * This contains the data describing the API. This includes information
  1084. * about supported authentication schemes, supported namespaces, routes
  1085. * available on the API, and a small amount of data about the site.
  1086. *
  1087. * @since 4.4.0
  1088. *
  1089. * @param WP_REST_Response $response Response data.
  1090. */
  1091. return apply_filters( 'rest_index', $response );
  1092. }
  1093. /**
  1094. * Adds a link to the active theme for users who have proper permissions.
  1095. *
  1096. * @since 5.7.0
  1097. *
  1098. * @param WP_REST_Response $response REST API response.
  1099. */
  1100. protected function add_active_theme_link_to_index( WP_REST_Response $response ) {
  1101. $should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' );
  1102. if ( ! $should_add && current_user_can( 'edit_posts' ) ) {
  1103. $should_add = true;
  1104. }
  1105. if ( ! $should_add ) {
  1106. foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
  1107. if ( current_user_can( $post_type->cap->edit_posts ) ) {
  1108. $should_add = true;
  1109. break;
  1110. }
  1111. }
  1112. }
  1113. if ( $should_add ) {
  1114. $theme = wp_get_theme();
  1115. $response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) );
  1116. }
  1117. }
  1118. /**
  1119. * Exposes the site logo through the WordPress REST API.
  1120. * This is used for fetching this information when user has no rights
  1121. * to update settings.
  1122. *
  1123. * @since 5.8.0
  1124. *
  1125. * @param WP_REST_Response $response REST API response.
  1126. */
  1127. protected function add_site_logo_to_index( WP_REST_Response $response ) {
  1128. $site_logo_id = get_theme_mod( 'custom_logo' );
  1129. $response->data['site_logo'] = $site_logo_id;
  1130. if ( $site_logo_id ) {
  1131. $response->add_link(
  1132. 'https://api.w.org/featuredmedia',
  1133. rest_url( 'wp/v2/media/' . $site_logo_id ),
  1134. array(
  1135. 'embeddable' => true,
  1136. )
  1137. );
  1138. }
  1139. }
  1140. /**
  1141. * Retrieves the index for a namespace.
  1142. *
  1143. * @since 4.4.0
  1144. *
  1145. * @param WP_REST_Request $request REST request instance.
  1146. * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
  1147. * WP_Error if the namespace isn't set.
  1148. */
  1149. public function get_namespace_index( $request ) {
  1150. $namespace = $request['namespace'];
  1151. if ( ! isset( $this->namespaces[ $namespace ] ) ) {
  1152. return new WP_Error(
  1153. 'rest_invalid_namespace',
  1154. __( 'The specified namespace could not be found.' ),
  1155. array( 'status' => 404 )
  1156. );
  1157. }
  1158. $routes = $this->namespaces[ $namespace ];
  1159. $endpoints = array_intersect_key( $this->get_routes(), $routes );
  1160. $data = array(
  1161. 'namespace' => $namespace,
  1162. 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ),
  1163. );
  1164. $response = rest_ensure_response( $data );
  1165. // Link to the root index.
  1166. $response->add_link( 'up', rest_url( '/' ) );
  1167. /**
  1168. * Filters the REST API namespace index data.
  1169. *
  1170. * This typically is just the route data for the namespace, but you can
  1171. * add any data you'd like here.
  1172. *
  1173. * @since 4.4.0
  1174. *
  1175. * @param WP_REST_Response $response Response data.
  1176. * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
  1177. */
  1178. return apply_filters( 'rest_namespace_index', $response, $request );
  1179. }
  1180. /**
  1181. * Retrieves the publicly-visible data for routes.
  1182. *
  1183. * @since 4.4.0
  1184. *
  1185. * @param array $routes Routes to get data for.
  1186. * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
  1187. * @return array[] Route data to expose in indexes, keyed by route.
  1188. */
  1189. public function get_data_for_routes( $routes, $context = 'view' ) {
  1190. $available = array();
  1191. // Find the available routes.
  1192. foreach ( $routes as $route => $callbacks ) {
  1193. $data = $this->get_data_for_route( $route, $callbacks, $context );
  1194. if ( empty( $data ) ) {
  1195. continue;
  1196. }
  1197. /**
  1198. * Filters the REST API endpoint data.
  1199. *
  1200. * @since 4.4.0
  1201. *
  1202. * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
  1203. */
  1204. $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
  1205. }
  1206. /**
  1207. * Filters the publicly-visible data for REST API routes.
  1208. *
  1209. * This data is exposed on indexes and can be used by clients or
  1210. * developers to investigate the site and find out how to use it. It
  1211. * acts as a form of self-documentation.
  1212. *
  1213. * @since 4.4.0
  1214. *
  1215. * @param array[] $available Route data to expose in indexes, keyed by route.
  1216. * @param array $routes Internal route data as an associative array.
  1217. */
  1218. return apply_filters( 'rest_route_data', $available, $routes );
  1219. }
  1220. /**
  1221. * Retrieves publicly-visible data for the route.
  1222. *
  1223. * @since 4.4.0
  1224. *
  1225. * @param string $route Route to get data for.
  1226. * @param array $callbacks Callbacks to convert to data.
  1227. * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
  1228. * @return array|null Data for the route, or null if no publicly-visible data.
  1229. */
  1230. public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
  1231. $data = array(
  1232. 'namespace' => '',
  1233. 'methods' => array(),
  1234. 'endpoints' => array(),
  1235. );
  1236. if ( isset( $this->route_options[ $route ] ) ) {
  1237. $options = $this->route_options[ $route ];
  1238. if ( isset( $options['namespace'] ) ) {
  1239. $data['namespace'] = $options['namespace'];
  1240. }
  1241. if ( isset( $options['schema'] ) && 'help' === $context ) {
  1242. $data['schema'] = call_user_func( $options['schema'] );
  1243. }
  1244. }
  1245. $allowed_schema_keywords = array_flip( rest_get_allowed_schema_keywords() );
  1246. $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
  1247. foreach ( $callbacks as $callback ) {
  1248. // Skip to the next route if any callback is hidden.
  1249. if ( empty( $callback['show_in_index'] ) ) {
  1250. continue;
  1251. }
  1252. $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
  1253. $endpoint_data = array(
  1254. 'methods' => array_keys( $callback['methods'] ),
  1255. );
  1256. if ( isset( $callback['args'] ) ) {
  1257. $endpoint_data['args'] = array();
  1258. foreach ( $callback['args'] as $key => $opts ) {
  1259. $arg_data = array_intersect_key( $opts, $allowed_schema_keywords );
  1260. $arg_data['required'] = ! empty( $opts['required'] );
  1261. $endpoint_data['args'][ $key ] = $arg_data;
  1262. }
  1263. }
  1264. $data['endpoints'][] = $endpoint_data;
  1265. // For non-variable routes, generate links.
  1266. if ( strpos( $route, '{' ) === false ) {
  1267. $data['_links'] = array(
  1268. 'self' => array(
  1269. array(
  1270. 'href' => rest_url( $route ),
  1271. ),
  1272. ),
  1273. );
  1274. }
  1275. }
  1276. if ( empty( $data['methods'] ) ) {
  1277. // No methods supported, hide the route.
  1278. return null;
  1279. }
  1280. return $data;
  1281. }
  1282. /**
  1283. * Gets the maximum number of requests that can be included in a batch.
  1284. *
  1285. * @since 5.6.0
  1286. *
  1287. * @return int The maximum requests.
  1288. */
  1289. protected function get_max_batch_size() {
  1290. /**
  1291. * Filters the maximum number of REST API requests that can be included in a batch.
  1292. *
  1293. * @since 5.6.0
  1294. *
  1295. * @param int $max_size The maximum size.
  1296. */
  1297. return apply_filters( 'rest_get_max_batch_size', 25 );
  1298. }
  1299. /**
  1300. * Serves the batch/v1 request.
  1301. *
  1302. * @since 5.6.0
  1303. *
  1304. * @param WP_REST_Request $batch_request The batch request object.
  1305. * @return WP_REST_Response The generated response object.
  1306. */
  1307. public function serve_batch_request_v1( WP_REST_Request $batch_request ) {
  1308. $requests = array();
  1309. foreach ( $batch_request['requests'] as $args ) {
  1310. $parsed_url = wp_parse_url( $args['path'] );
  1311. if ( false === $parsed_url ) {
  1312. $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) );
  1313. continue;
  1314. }
  1315. $single_request = new WP_REST_Request( isset( $args['method'] ) ? $args['method'] : 'POST', $parsed_url['path'] );
  1316. if ( ! empty( $parsed_url['query'] ) ) {
  1317. $query_args = null; // Satisfy linter.
  1318. wp_parse_str( $parsed_url['query'], $query_args );
  1319. $single_request->set_query_params( $query_args );
  1320. }
  1321. if ( ! empty( $args['body'] ) ) {
  1322. $single_request->set_body_params( $args['body'] );
  1323. }
  1324. if ( ! empty( $args['headers'] ) ) {
  1325. $single_request->set_headers( $args['headers'] );
  1326. }
  1327. $requests[] = $single_request;
  1328. }
  1329. $matches = array();
  1330. $validation = array();
  1331. $has_error = false;
  1332. foreach ( $requests as $single_request ) {
  1333. $match = $this->match_request_to_handler( $single_request );
  1334. $matches[] = $match;
  1335. $error = null;
  1336. if ( is_wp_error( $match ) ) {
  1337. $error = $match;
  1338. }
  1339. if ( ! $error ) {
  1340. list( $route, $handler ) = $match;
  1341. if ( isset( $handler['allow_batch'] ) ) {
  1342. $allow_batch = $handler['allow_batch'];
  1343. } else {
  1344. $route_options = $this->get_route_options( $route );
  1345. $allow_batch = isset( $route_options['allow_batch'] ) ? $route_options['allow_batch'] : false;
  1346. }
  1347. if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) {
  1348. $error = new WP_Error(
  1349. 'rest_batch_not_allowed',
  1350. __( 'The requested route does not support batch requests.' ),
  1351. array( 'status' => 400 )
  1352. );
  1353. }
  1354. }
  1355. if ( ! $error ) {
  1356. $check_required = $single_request->has_valid_params();
  1357. if ( is_wp_error( $check_required ) ) {
  1358. $error = $check_required;
  1359. }
  1360. }
  1361. if ( ! $error ) {
  1362. $check_sanitized = $single_request->sanitize_params();
  1363. if ( is_wp_error( $check_sanitized ) ) {
  1364. $error = $check_sanitized;
  1365. }
  1366. }
  1367. if ( $error ) {
  1368. $has_error = true;
  1369. $validation[] = $error;
  1370. } else {
  1371. $validation[] = true;
  1372. }
  1373. }
  1374. $responses = array();
  1375. if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) {
  1376. foreach ( $validation as $valid ) {
  1377. if ( is_wp_error( $valid ) ) {
  1378. $responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data();
  1379. } else {
  1380. $responses[] = null;
  1381. }
  1382. }
  1383. return new WP_REST_Response(
  1384. array(
  1385. 'failed' => 'validation',
  1386. 'responses' => $responses,
  1387. ),
  1388. WP_Http::MULTI_STATUS
  1389. );
  1390. }
  1391. foreach ( $requests as $i => $single_request ) {
  1392. $clean_request = clone $single_request;
  1393. $clean_request->set_url_params( array() );
  1394. $clean_request->set_attributes( array() );
  1395. $clean_request->set_default_params( array() );
  1396. /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
  1397. $result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );
  1398. if ( empty( $result ) ) {
  1399. $match = $matches[ $i ];
  1400. $error = null;
  1401. if ( is_wp_error( $validation[ $i ] ) ) {
  1402. $error = $validation[ $i ];
  1403. }
  1404. if ( is_wp_error( $match ) ) {
  1405. $result = $this->error_to_response( $match );
  1406. } else {
  1407. list( $route, $handler ) = $match;
  1408. if ( ! $error && ! is_callable( $handler['callback'] ) ) {
  1409. $error = new WP_Error(
  1410. 'rest_invalid_handler',
  1411. __( 'The handler for the route is invalid' ),
  1412. array( 'status' => 500 )
  1413. );
  1414. }
  1415. $result = $this->respond_to_request( $single_request, $route, $handler, $error );
  1416. }
  1417. }
  1418. /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
  1419. $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request );
  1420. $responses[] = $this->envelope_response( $result, false )->get_data();
  1421. }
  1422. return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS );
  1423. }
  1424. /**
  1425. * Sends an HTTP status code.
  1426. *
  1427. * @since 4.4.0
  1428. *
  1429. * @param int $code HTTP status.
  1430. */
  1431. protected function set_status( $code ) {
  1432. status_header( $code );
  1433. }
  1434. /**
  1435. * Sends an HTTP header.
  1436. *
  1437. * @since 4.4.0
  1438. *
  1439. * @param string $key Header key.
  1440. * @param string $value Header value.
  1441. */
  1442. public function send_header( $key, $value ) {
  1443. /*
  1444. * Sanitize as per RFC2616 (Section 4.2):
  1445. *
  1446. * Any LWS that occurs between field-content MAY be replaced with a
  1447. * single SP before interpreting the field value or forwarding the
  1448. * message downstream.
  1449. */
  1450. $value = preg_replace( '/\s+/', ' ', $value );
  1451. header( sprintf( '%s: %s', $key, $value ) );
  1452. }
  1453. /**
  1454. * Sends multiple HTTP headers.
  1455. *
  1456. * @since 4.4.0
  1457. *
  1458. * @param array $headers Map of header name to header value.
  1459. */
  1460. public function send_headers( $headers ) {
  1461. foreach ( $headers as $key => $value ) {
  1462. $this->send_header( $key, $value );
  1463. }
  1464. }
  1465. /**
  1466. * Removes an HTTP header from the current response.
  1467. *
  1468. * @since 4.8.0
  1469. *
  1470. * @param string $key Header key.
  1471. */
  1472. public function remove_header( $key ) {
  1473. header_remove( $key );
  1474. }
  1475. /**
  1476. * Retrieves the raw request entity (body).
  1477. *
  1478. * @since 4.4.0
  1479. *
  1480. * @global string $HTTP_RAW_POST_DATA Raw post data.
  1481. *
  1482. * @return string Raw request data.
  1483. */
  1484. public static function get_raw_data() {
  1485. // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
  1486. global $HTTP_RAW_POST_DATA;
  1487. // $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0.
  1488. if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
  1489. $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
  1490. }
  1491. return $HTTP_RAW_POST_DATA;
  1492. // phpcs:enable
  1493. }
  1494. /**
  1495. * Extracts headers from a PHP-style $_SERVER array.
  1496. *
  1497. * @since 4.4.0
  1498. *
  1499. * @param array $server Associative array similar to `$_SERVER`.
  1500. * @return array Headers extracted from the input.
  1501. */
  1502. public function get_headers( $server ) {
  1503. $headers = array();
  1504. // CONTENT_* headers are not prefixed with HTTP_.
  1505. $additional = array(
  1506. 'CONTENT_LENGTH' => true,
  1507. 'CONTENT_MD5' => true,
  1508. 'CONTENT_TYPE' => true,
  1509. );
  1510. foreach ( $server as $key => $value ) {
  1511. if ( strpos( $key, 'HTTP_' ) === 0 ) {
  1512. $headers[ substr( $key, 5 ) ] = $value;
  1513. } elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) {
  1514. /*
  1515. * In some server configurations, the authorization header is passed in this alternate location.
  1516. * Since it would not be passed in in both places we do not check for both headers and resolve.
  1517. */
  1518. $headers['AUTHORIZATION'] = $value;
  1519. } elseif ( isset( $additional[ $key ] ) ) {
  1520. $headers[ $key ] = $value;
  1521. }
  1522. }
  1523. return $headers;
  1524. }
  1525. }