class-wp-rest-server.php 52 KB

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