Nenhuma Descrição

class-wp-rest-server.php 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  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. $embed = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
  399. $result = $this->envelope_response( $result, $embed );
  400. }
  401. // Send extra data from response objects.
  402. $headers = $result->get_headers();
  403. $this->send_headers( $headers );
  404. $code = $result->get_status();
  405. $this->set_status( $code );
  406. /**
  407. * Filters whether the REST API request has already been served.
  408. *
  409. * Allow sending the request manually - by returning true, the API result
  410. * will not be sent to the client.
  411. *
  412. * @since 4.4.0
  413. *
  414. * @param bool $served Whether the request has already been served.
  415. * Default false.
  416. * @param WP_HTTP_Response $result Result to send to the client. Usually a `WP_REST_Response`.
  417. * @param WP_REST_Request $request Request used to generate the response.
  418. * @param WP_REST_Server $server Server instance.
  419. */
  420. $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this );
  421. if ( ! $served ) {
  422. if ( 'HEAD' === $request->get_method() ) {
  423. return null;
  424. }
  425. // Embed links inside the request.
  426. $embed = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false;
  427. $result = $this->response_to_data( $result, $embed );
  428. /**
  429. * Filters the REST API response.
  430. *
  431. * Allows modification of the response data after inserting
  432. * embedded data (if any) and before echoing the response data.
  433. *
  434. * @since 4.8.1
  435. *
  436. * @param array $result Response data to send to the client.
  437. * @param WP_REST_Server $server Server instance.
  438. * @param WP_REST_Request $request Request used to generate the response.
  439. */
  440. $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request );
  441. // The 204 response shouldn't have a body.
  442. if ( 204 === $code || null === $result ) {
  443. return null;
  444. }
  445. $result = wp_json_encode( $result );
  446. $json_error_message = $this->get_json_last_error();
  447. if ( $json_error_message ) {
  448. $this->set_status( 500 );
  449. $json_error_obj = new WP_Error(
  450. 'rest_encode_error',
  451. $json_error_message,
  452. array( 'status' => 500 )
  453. );
  454. $result = $this->error_to_response( $json_error_obj );
  455. $result = wp_json_encode( $result->data );
  456. }
  457. if ( $jsonp_callback ) {
  458. // Prepend '/**/' to mitigate possible JSONP Flash attacks.
  459. // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
  460. echo '/**/' . $jsonp_callback . '(' . $result . ')';
  461. } else {
  462. echo $result;
  463. }
  464. }
  465. return null;
  466. }
  467. /**
  468. * Converts a response to data to send.
  469. *
  470. * @since 4.4.0
  471. * @since 5.4.0 The $embed parameter can now contain a list of link relations to include.
  472. *
  473. * @param WP_REST_Response $response Response object.
  474. * @param bool|string[] $embed Whether to embed all links, a filtered list of link relations, or no links.
  475. * @return array {
  476. * Data with sub-requests embedded.
  477. *
  478. * @type array $_links Links.
  479. * @type array $_embedded Embedded objects.
  480. * }
  481. */
  482. public function response_to_data( $response, $embed ) {
  483. $data = $response->get_data();
  484. $links = self::get_compact_response_links( $response );
  485. if ( ! empty( $links ) ) {
  486. // Convert links to part of the data.
  487. $data['_links'] = $links;
  488. }
  489. if ( $embed ) {
  490. $this->embed_cache = array();
  491. // Determine if this is a numeric array.
  492. if ( wp_is_numeric_array( $data ) ) {
  493. foreach ( $data as $key => $item ) {
  494. $data[ $key ] = $this->embed_links( $item, $embed );
  495. }
  496. } else {
  497. $data = $this->embed_links( $data, $embed );
  498. }
  499. $this->embed_cache = array();
  500. }
  501. return $data;
  502. }
  503. /**
  504. * Retrieves links from a response.
  505. *
  506. * Extracts the links from a response into a structured hash, suitable for
  507. * direct output.
  508. *
  509. * @since 4.4.0
  510. *
  511. * @param WP_REST_Response $response Response to extract links from.
  512. * @return array Map of link relation to list of link hashes.
  513. */
  514. public static function get_response_links( $response ) {
  515. $links = $response->get_links();
  516. if ( empty( $links ) ) {
  517. return array();
  518. }
  519. // Convert links to part of the data.
  520. $data = array();
  521. foreach ( $links as $rel => $items ) {
  522. $data[ $rel ] = array();
  523. foreach ( $items as $item ) {
  524. $attributes = $item['attributes'];
  525. $attributes['href'] = $item['href'];
  526. $data[ $rel ][] = $attributes;
  527. }
  528. }
  529. return $data;
  530. }
  531. /**
  532. * Retrieves the CURIEs (compact URIs) used for relations.
  533. *
  534. * Extracts the links from a response into a structured hash, suitable for
  535. * direct output.
  536. *
  537. * @since 4.5.0
  538. *
  539. * @param WP_REST_Response $response Response to extract links from.
  540. * @return array Map of link relation to list of link hashes.
  541. */
  542. public static function get_compact_response_links( $response ) {
  543. $links = self::get_response_links( $response );
  544. if ( empty( $links ) ) {
  545. return array();
  546. }
  547. $curies = $response->get_curies();
  548. $used_curies = array();
  549. foreach ( $links as $rel => $items ) {
  550. // Convert $rel URIs to their compact versions if they exist.
  551. foreach ( $curies as $curie ) {
  552. $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) );
  553. if ( strpos( $rel, $href_prefix ) !== 0 ) {
  554. continue;
  555. }
  556. // Relation now changes from '$uri' to '$curie:$relation'.
  557. $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) );
  558. preg_match( '!' . $rel_regex . '!', $rel, $matches );
  559. if ( $matches ) {
  560. $new_rel = $curie['name'] . ':' . $matches[1];
  561. $used_curies[ $curie['name'] ] = $curie;
  562. $links[ $new_rel ] = $items;
  563. unset( $links[ $rel ] );
  564. break;
  565. }
  566. }
  567. }
  568. // Push the curies onto the start of the links array.
  569. if ( $used_curies ) {
  570. $links['curies'] = array_values( $used_curies );
  571. }
  572. return $links;
  573. }
  574. /**
  575. * Embeds the links from the data into the request.
  576. *
  577. * @since 4.4.0
  578. * @since 5.4.0 The $embed parameter can now contain a list of link relations to include.
  579. *
  580. * @param array $data Data from the request.
  581. * @param bool|string[] $embed Whether to embed all links or a filtered list of link relations.
  582. * @return array {
  583. * Data with sub-requests embedded.
  584. *
  585. * @type array $_links Links.
  586. * @type array $_embedded Embedded objects.
  587. * }
  588. */
  589. protected function embed_links( $data, $embed = true ) {
  590. if ( empty( $data['_links'] ) ) {
  591. return $data;
  592. }
  593. $embedded = array();
  594. foreach ( $data['_links'] as $rel => $links ) {
  595. // If a list of relations was specified, and the link relation
  596. // is not in the list of allowed relations, don't process the link.
  597. if ( is_array( $embed ) && ! in_array( $rel, $embed, true ) ) {
  598. continue;
  599. }
  600. $embeds = array();
  601. foreach ( $links as $item ) {
  602. // Determine if the link is embeddable.
  603. if ( empty( $item['embeddable'] ) ) {
  604. // Ensure we keep the same order.
  605. $embeds[] = array();
  606. continue;
  607. }
  608. if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) {
  609. // Run through our internal routing and serve.
  610. $request = WP_REST_Request::from_url( $item['href'] );
  611. if ( ! $request ) {
  612. $embeds[] = array();
  613. continue;
  614. }
  615. // Embedded resources get passed context=embed.
  616. if ( empty( $request['context'] ) ) {
  617. $request['context'] = 'embed';
  618. }
  619. $response = $this->dispatch( $request );
  620. /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
  621. $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request );
  622. $this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false );
  623. }
  624. $embeds[] = $this->embed_cache[ $item['href'] ];
  625. }
  626. // Determine if any real links were found.
  627. $has_links = count( array_filter( $embeds ) );
  628. if ( $has_links ) {
  629. $embedded[ $rel ] = $embeds;
  630. }
  631. }
  632. if ( ! empty( $embedded ) ) {
  633. $data['_embedded'] = $embedded;
  634. }
  635. return $data;
  636. }
  637. /**
  638. * Wraps the response in an envelope.
  639. *
  640. * The enveloping technique is used to work around browser/client
  641. * compatibility issues. Essentially, it converts the full HTTP response to
  642. * data instead.
  643. *
  644. * @since 4.4.0
  645. * @since 6.0.0 The $embed parameter can now contain a list of link relations to include
  646. *
  647. * @param WP_REST_Response $response Response object.
  648. * @param bool|string[] $embed Whether to embed all links, a filtered list of link relations, or no links.
  649. * @return WP_REST_Response New response with wrapped data
  650. */
  651. public function envelope_response( $response, $embed ) {
  652. $envelope = array(
  653. 'body' => $this->response_to_data( $response, $embed ),
  654. 'status' => $response->get_status(),
  655. 'headers' => $response->get_headers(),
  656. );
  657. /**
  658. * Filters the enveloped form of a REST API response.
  659. *
  660. * @since 4.4.0
  661. *
  662. * @param array $envelope {
  663. * Envelope data.
  664. *
  665. * @type array $body Response data.
  666. * @type int $status The 3-digit HTTP status code.
  667. * @type array $headers Map of header name to header value.
  668. * }
  669. * @param WP_REST_Response $response Original response data.
  670. */
  671. $envelope = apply_filters( 'rest_envelope_response', $envelope, $response );
  672. // Ensure it's still a response and return.
  673. return rest_ensure_response( $envelope );
  674. }
  675. /**
  676. * Registers a route to the server.
  677. *
  678. * @since 4.4.0
  679. *
  680. * @param string $namespace Namespace.
  681. * @param string $route The REST route.
  682. * @param array $route_args Route arguments.
  683. * @param bool $override Optional. Whether the route should be overridden if it already exists.
  684. * Default false.
  685. */
  686. public function register_route( $namespace, $route, $route_args, $override = false ) {
  687. if ( ! isset( $this->namespaces[ $namespace ] ) ) {
  688. $this->namespaces[ $namespace ] = array();
  689. $this->register_route(
  690. $namespace,
  691. '/' . $namespace,
  692. array(
  693. array(
  694. 'methods' => self::READABLE,
  695. 'callback' => array( $this, 'get_namespace_index' ),
  696. 'args' => array(
  697. 'namespace' => array(
  698. 'default' => $namespace,
  699. ),
  700. 'context' => array(
  701. 'default' => 'view',
  702. ),
  703. ),
  704. ),
  705. )
  706. );
  707. }
  708. // Associative to avoid double-registration.
  709. $this->namespaces[ $namespace ][ $route ] = true;
  710. $route_args['namespace'] = $namespace;
  711. if ( $override || empty( $this->endpoints[ $route ] ) ) {
  712. $this->endpoints[ $route ] = $route_args;
  713. } else {
  714. $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args );
  715. }
  716. }
  717. /**
  718. * Retrieves the route map.
  719. *
  720. * The route map is an associative array with path regexes as the keys. The
  721. * value is an indexed array with the callback function/method as the first
  722. * item, and a bitmask of HTTP methods as the second item (see the class
  723. * constants).
  724. *
  725. * Each route can be mapped to more than one callback by using an array of
  726. * the indexed arrays. This allows mapping e.g. GET requests to one callback
  727. * and POST requests to another.
  728. *
  729. * Note that the path regexes (array keys) must have @ escaped, as this is
  730. * used as the delimiter with preg_match()
  731. *
  732. * @since 4.4.0
  733. * @since 5.4.0 Add $namespace parameter.
  734. *
  735. * @param string $namespace Optionally, only return routes in the given namespace.
  736. * @return array `'/path/regex' => array( $callback, $bitmask )` or
  737. * `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
  738. */
  739. public function get_routes( $namespace = '' ) {
  740. $endpoints = $this->endpoints;
  741. if ( $namespace ) {
  742. $endpoints = wp_list_filter( $endpoints, array( 'namespace' => $namespace ) );
  743. }
  744. /**
  745. * Filters the array of available REST API endpoints.
  746. *
  747. * @since 4.4.0
  748. *
  749. * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped
  750. * to an array of callbacks for the endpoint. These take the format
  751. * `'/path/regex' => array( $callback, $bitmask )` or
  752. * `'/path/regex' => array( array( $callback, $bitmask ).
  753. */
  754. $endpoints = apply_filters( 'rest_endpoints', $endpoints );
  755. // Normalize the endpoints.
  756. $defaults = array(
  757. 'methods' => '',
  758. 'accept_json' => false,
  759. 'accept_raw' => false,
  760. 'show_in_index' => true,
  761. 'args' => array(),
  762. );
  763. foreach ( $endpoints as $route => &$handlers ) {
  764. if ( isset( $handlers['callback'] ) ) {
  765. // Single endpoint, add one deeper.
  766. $handlers = array( $handlers );
  767. }
  768. if ( ! isset( $this->route_options[ $route ] ) ) {
  769. $this->route_options[ $route ] = array();
  770. }
  771. foreach ( $handlers as $key => &$handler ) {
  772. if ( ! is_numeric( $key ) ) {
  773. // Route option, move it to the options.
  774. $this->route_options[ $route ][ $key ] = $handler;
  775. unset( $handlers[ $key ] );
  776. continue;
  777. }
  778. $handler = wp_parse_args( $handler, $defaults );
  779. // Allow comma-separated HTTP methods.
  780. if ( is_string( $handler['methods'] ) ) {
  781. $methods = explode( ',', $handler['methods'] );
  782. } elseif ( is_array( $handler['methods'] ) ) {
  783. $methods = $handler['methods'];
  784. } else {
  785. $methods = array();
  786. }
  787. $handler['methods'] = array();
  788. foreach ( $methods as $method ) {
  789. $method = strtoupper( trim( $method ) );
  790. $handler['methods'][ $method ] = true;
  791. }
  792. }
  793. }
  794. return $endpoints;
  795. }
  796. /**
  797. * Retrieves namespaces registered on the server.
  798. *
  799. * @since 4.4.0
  800. *
  801. * @return string[] List of registered namespaces.
  802. */
  803. public function get_namespaces() {
  804. return array_keys( $this->namespaces );
  805. }
  806. /**
  807. * Retrieves specified options for a route.
  808. *
  809. * @since 4.4.0
  810. *
  811. * @param string $route Route pattern to fetch options for.
  812. * @return array|null Data as an associative array if found, or null if not found.
  813. */
  814. public function get_route_options( $route ) {
  815. if ( ! isset( $this->route_options[ $route ] ) ) {
  816. return null;
  817. }
  818. return $this->route_options[ $route ];
  819. }
  820. /**
  821. * Matches the request to a callback and call it.
  822. *
  823. * @since 4.4.0
  824. *
  825. * @param WP_REST_Request $request Request to attempt dispatching.
  826. * @return WP_REST_Response Response returned by the callback.
  827. */
  828. public function dispatch( $request ) {
  829. /**
  830. * Filters the pre-calculated result of a REST API dispatch request.
  831. *
  832. * Allow hijacking the request before dispatching by returning a non-empty. The returned value
  833. * will be used to serve the request instead.
  834. *
  835. * @since 4.4.0
  836. *
  837. * @param mixed $result Response to replace the requested version with. Can be anything
  838. * a normal endpoint can return, or null to not hijack the request.
  839. * @param WP_REST_Server $server Server instance.
  840. * @param WP_REST_Request $request Request used to generate the response.
  841. */
  842. $result = apply_filters( 'rest_pre_dispatch', null, $this, $request );
  843. if ( ! empty( $result ) ) {
  844. return $result;
  845. }
  846. $error = null;
  847. $matched = $this->match_request_to_handler( $request );
  848. if ( is_wp_error( $matched ) ) {
  849. return $this->error_to_response( $matched );
  850. }
  851. list( $route, $handler ) = $matched;
  852. if ( ! is_callable( $handler['callback'] ) ) {
  853. $error = new WP_Error(
  854. 'rest_invalid_handler',
  855. __( 'The handler for the route is invalid.' ),
  856. array( 'status' => 500 )
  857. );
  858. }
  859. if ( ! is_wp_error( $error ) ) {
  860. $check_required = $request->has_valid_params();
  861. if ( is_wp_error( $check_required ) ) {
  862. $error = $check_required;
  863. } else {
  864. $check_sanitized = $request->sanitize_params();
  865. if ( is_wp_error( $check_sanitized ) ) {
  866. $error = $check_sanitized;
  867. }
  868. }
  869. }
  870. return $this->respond_to_request( $request, $route, $handler, $error );
  871. }
  872. /**
  873. * Matches a request object to its handler.
  874. *
  875. * @access private
  876. * @since 5.6.0
  877. *
  878. * @param WP_REST_Request $request The request object.
  879. * @return array|WP_Error The route and request handler on success or a WP_Error instance if no handler was found.
  880. */
  881. protected function match_request_to_handler( $request ) {
  882. $method = $request->get_method();
  883. $path = $request->get_route();
  884. $with_namespace = array();
  885. foreach ( $this->get_namespaces() as $namespace ) {
  886. if ( 0 === strpos( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) {
  887. $with_namespace[] = $this->get_routes( $namespace );
  888. }
  889. }
  890. if ( $with_namespace ) {
  891. $routes = array_merge( ...$with_namespace );
  892. } else {
  893. $routes = $this->get_routes();
  894. }
  895. foreach ( $routes as $route => $handlers ) {
  896. $match = preg_match( '@^' . $route . '$@i', $path, $matches );
  897. if ( ! $match ) {
  898. continue;
  899. }
  900. $args = array();
  901. foreach ( $matches as $param => $value ) {
  902. if ( ! is_int( $param ) ) {
  903. $args[ $param ] = $value;
  904. }
  905. }
  906. foreach ( $handlers as $handler ) {
  907. $callback = $handler['callback'];
  908. $response = null;
  909. // Fallback to GET method if no HEAD method is registered.
  910. $checked_method = $method;
  911. if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
  912. $checked_method = 'GET';
  913. }
  914. if ( empty( $handler['methods'][ $checked_method ] ) ) {
  915. continue;
  916. }
  917. if ( ! is_callable( $callback ) ) {
  918. return array( $route, $handler );
  919. }
  920. $request->set_url_params( $args );
  921. $request->set_attributes( $handler );
  922. $defaults = array();
  923. foreach ( $handler['args'] as $arg => $options ) {
  924. if ( isset( $options['default'] ) ) {
  925. $defaults[ $arg ] = $options['default'];
  926. }
  927. }
  928. $request->set_default_params( $defaults );
  929. return array( $route, $handler );
  930. }
  931. }
  932. return new WP_Error(
  933. 'rest_no_route',
  934. __( 'No route was found matching the URL and request method.' ),
  935. array( 'status' => 404 )
  936. );
  937. }
  938. /**
  939. * Dispatches the request to the callback handler.
  940. *
  941. * @access private
  942. * @since 5.6.0
  943. *
  944. * @param WP_REST_Request $request The request object.
  945. * @param string $route The matched route regex.
  946. * @param array $handler The matched route handler.
  947. * @param WP_Error|null $response The current error object if any.
  948. * @return WP_REST_Response
  949. */
  950. protected function respond_to_request( $request, $route, $handler, $response ) {
  951. /**
  952. * Filters the response before executing any REST API callbacks.
  953. *
  954. * Allows plugins to perform additional validation after a
  955. * request is initialized and matched to a registered route,
  956. * but before it is executed.
  957. *
  958. * Note that this filter will not be called for requests that
  959. * fail to authenticate or match to a registered route.
  960. *
  961. * @since 4.7.0
  962. *
  963. * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
  964. * Usually a WP_REST_Response or WP_Error.
  965. * @param array $handler Route handler used for the request.
  966. * @param WP_REST_Request $request Request used to generate the response.
  967. */
  968. $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
  969. // Check permission specified on the route.
  970. if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) {
  971. $permission = call_user_func( $handler['permission_callback'], $request );
  972. if ( is_wp_error( $permission ) ) {
  973. $response = $permission;
  974. } elseif ( false === $permission || null === $permission ) {
  975. $response = new WP_Error(
  976. 'rest_forbidden',
  977. __( 'Sorry, you are not allowed to do that.' ),
  978. array( 'status' => rest_authorization_required_code() )
  979. );
  980. }
  981. }
  982. if ( ! is_wp_error( $response ) ) {
  983. /**
  984. * Filters the REST API dispatch request result.
  985. *
  986. * Allow plugins to override dispatching the request.
  987. *
  988. * @since 4.4.0
  989. * @since 4.5.0 Added `$route` and `$handler` parameters.
  990. *
  991. * @param mixed $dispatch_result Dispatch result, will be used if not empty.
  992. * @param WP_REST_Request $request Request used to generate the response.
  993. * @param string $route Route matched for the request.
  994. * @param array $handler Route handler used for the request.
  995. */
  996. $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
  997. // Allow plugins to halt the request via this filter.
  998. if ( null !== $dispatch_result ) {
  999. $response = $dispatch_result;
  1000. } else {
  1001. $response = call_user_func( $handler['callback'], $request );
  1002. }
  1003. }
  1004. /**
  1005. * Filters the response immediately after executing any REST API
  1006. * callbacks.
  1007. *
  1008. * Allows plugins to perform any needed cleanup, for example,
  1009. * to undo changes made during the {@see 'rest_request_before_callbacks'}
  1010. * filter.
  1011. *
  1012. * Note that this filter will not be called for requests that
  1013. * fail to authenticate or match to a registered route.
  1014. *
  1015. * Note that an endpoint's `permission_callback` can still be
  1016. * called after this filter - see `rest_send_allow_header()`.
  1017. *
  1018. * @since 4.7.0
  1019. *
  1020. * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
  1021. * Usually a WP_REST_Response or WP_Error.
  1022. * @param array $handler Route handler used for the request.
  1023. * @param WP_REST_Request $request Request used to generate the response.
  1024. */
  1025. $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request );
  1026. if ( is_wp_error( $response ) ) {
  1027. $response = $this->error_to_response( $response );
  1028. } else {
  1029. $response = rest_ensure_response( $response );
  1030. }
  1031. $response->set_matched_route( $route );
  1032. $response->set_matched_handler( $handler );
  1033. return $response;
  1034. }
  1035. /**
  1036. * Returns if an error occurred during most recent JSON encode/decode.
  1037. *
  1038. * Strings to be translated will be in format like
  1039. * "Encoding error: Maximum stack depth exceeded".
  1040. *
  1041. * @since 4.4.0
  1042. *
  1043. * @return false|string Boolean false or string error message.
  1044. */
  1045. protected function get_json_last_error() {
  1046. $last_error_code = json_last_error();
  1047. if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) {
  1048. return false;
  1049. }
  1050. return json_last_error_msg();
  1051. }
  1052. /**
  1053. * Retrieves the site index.
  1054. *
  1055. * This endpoint describes the capabilities of the site.
  1056. *
  1057. * @since 4.4.0
  1058. *
  1059. * @param array $request {
  1060. * Request.
  1061. *
  1062. * @type string $context Context.
  1063. * }
  1064. * @return WP_REST_Response The API root index data.
  1065. */
  1066. public function get_index( $request ) {
  1067. // General site data.
  1068. $available = array(
  1069. 'name' => get_option( 'blogname' ),
  1070. 'description' => get_option( 'blogdescription' ),
  1071. 'url' => get_option( 'siteurl' ),
  1072. 'home' => home_url(),
  1073. 'gmt_offset' => get_option( 'gmt_offset' ),
  1074. 'timezone_string' => get_option( 'timezone_string' ),
  1075. 'namespaces' => array_keys( $this->namespaces ),
  1076. 'authentication' => array(),
  1077. 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
  1078. );
  1079. $response = new WP_REST_Response( $available );
  1080. $response->add_link( 'help', 'https://developer.wordpress.org/rest-api/' );
  1081. $this->add_active_theme_link_to_index( $response );
  1082. $this->add_site_logo_to_index( $response );
  1083. $this->add_site_icon_to_index( $response );
  1084. /**
  1085. * Filters the REST API root index data.
  1086. *
  1087. * This contains the data describing the API. This includes information
  1088. * about supported authentication schemes, supported namespaces, routes
  1089. * available on the API, and a small amount of data about the site.
  1090. *
  1091. * @since 4.4.0
  1092. * @since 6.0.0 Added `$request` parameter.
  1093. *
  1094. * @param WP_REST_Response $response Response data.
  1095. * @param WP_REST_Request $request Request data.
  1096. */
  1097. return apply_filters( 'rest_index', $response, $request );
  1098. }
  1099. /**
  1100. * Adds a link to the active theme for users who have proper permissions.
  1101. *
  1102. * @since 5.7.0
  1103. *
  1104. * @param WP_REST_Response $response REST API response.
  1105. */
  1106. protected function add_active_theme_link_to_index( WP_REST_Response $response ) {
  1107. $should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' );
  1108. if ( ! $should_add && current_user_can( 'edit_posts' ) ) {
  1109. $should_add = true;
  1110. }
  1111. if ( ! $should_add ) {
  1112. foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
  1113. if ( current_user_can( $post_type->cap->edit_posts ) ) {
  1114. $should_add = true;
  1115. break;
  1116. }
  1117. }
  1118. }
  1119. if ( $should_add ) {
  1120. $theme = wp_get_theme();
  1121. $response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) );
  1122. }
  1123. }
  1124. /**
  1125. * Exposes the site logo through the WordPress REST API.
  1126. *
  1127. * This is used for fetching this information when user has no rights
  1128. * to update settings.
  1129. *
  1130. * @since 5.8.0
  1131. *
  1132. * @param WP_REST_Response $response REST API response.
  1133. */
  1134. protected function add_site_logo_to_index( WP_REST_Response $response ) {
  1135. $site_logo_id = get_theme_mod( 'custom_logo', 0 );
  1136. $this->add_image_to_index( $response, $site_logo_id, 'site_logo' );
  1137. }
  1138. /**
  1139. * Exposes the site icon through the WordPress REST API.
  1140. *
  1141. * This is used for fetching this information when user has no rights
  1142. * to update settings.
  1143. *
  1144. * @since 5.9.0
  1145. *
  1146. * @param WP_REST_Response $response REST API response.
  1147. */
  1148. protected function add_site_icon_to_index( WP_REST_Response $response ) {
  1149. $site_icon_id = get_option( 'site_icon', 0 );
  1150. $this->add_image_to_index( $response, $site_icon_id, 'site_icon' );
  1151. }
  1152. /**
  1153. * Exposes an image through the WordPress REST API.
  1154. * This is used for fetching this information when user has no rights
  1155. * to update settings.
  1156. *
  1157. * @since 5.9.0
  1158. *
  1159. * @param WP_REST_Response $response REST API response.
  1160. * @param int $image_id Image attachment ID.
  1161. * @param string $type Type of Image.
  1162. */
  1163. protected function add_image_to_index( WP_REST_Response $response, $image_id, $type ) {
  1164. $response->data[ $type ] = (int) $image_id;
  1165. if ( $image_id ) {
  1166. $response->add_link(
  1167. 'https://api.w.org/featuredmedia',
  1168. rest_url( rest_get_route_for_post( $image_id ) ),
  1169. array(
  1170. 'embeddable' => true,
  1171. 'type' => $type,
  1172. )
  1173. );
  1174. }
  1175. }
  1176. /**
  1177. * Retrieves the index for a namespace.
  1178. *
  1179. * @since 4.4.0
  1180. *
  1181. * @param WP_REST_Request $request REST request instance.
  1182. * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found,
  1183. * WP_Error if the namespace isn't set.
  1184. */
  1185. public function get_namespace_index( $request ) {
  1186. $namespace = $request['namespace'];
  1187. if ( ! isset( $this->namespaces[ $namespace ] ) ) {
  1188. return new WP_Error(
  1189. 'rest_invalid_namespace',
  1190. __( 'The specified namespace could not be found.' ),
  1191. array( 'status' => 404 )
  1192. );
  1193. }
  1194. $routes = $this->namespaces[ $namespace ];
  1195. $endpoints = array_intersect_key( $this->get_routes(), $routes );
  1196. $data = array(
  1197. 'namespace' => $namespace,
  1198. 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ),
  1199. );
  1200. $response = rest_ensure_response( $data );
  1201. // Link to the root index.
  1202. $response->add_link( 'up', rest_url( '/' ) );
  1203. /**
  1204. * Filters the REST API namespace index data.
  1205. *
  1206. * This typically is just the route data for the namespace, but you can
  1207. * add any data you'd like here.
  1208. *
  1209. * @since 4.4.0
  1210. *
  1211. * @param WP_REST_Response $response Response data.
  1212. * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter.
  1213. */
  1214. return apply_filters( 'rest_namespace_index', $response, $request );
  1215. }
  1216. /**
  1217. * Retrieves the publicly-visible data for routes.
  1218. *
  1219. * @since 4.4.0
  1220. *
  1221. * @param array $routes Routes to get data for.
  1222. * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'.
  1223. * @return array[] Route data to expose in indexes, keyed by route.
  1224. */
  1225. public function get_data_for_routes( $routes, $context = 'view' ) {
  1226. $available = array();
  1227. // Find the available routes.
  1228. foreach ( $routes as $route => $callbacks ) {
  1229. $data = $this->get_data_for_route( $route, $callbacks, $context );
  1230. if ( empty( $data ) ) {
  1231. continue;
  1232. }
  1233. /**
  1234. * Filters the publicly-visible data for a single REST API route.
  1235. *
  1236. * @since 4.4.0
  1237. *
  1238. * @param array $data Publicly-visible data for the route.
  1239. */
  1240. $available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
  1241. }
  1242. /**
  1243. * Filters the publicly-visible data for REST API routes.
  1244. *
  1245. * This data is exposed on indexes and can be used by clients or
  1246. * developers to investigate the site and find out how to use it. It
  1247. * acts as a form of self-documentation.
  1248. *
  1249. * @since 4.4.0
  1250. *
  1251. * @param array[] $available Route data to expose in indexes, keyed by route.
  1252. * @param array $routes Internal route data as an associative array.
  1253. */
  1254. return apply_filters( 'rest_route_data', $available, $routes );
  1255. }
  1256. /**
  1257. * Retrieves publicly-visible data for the route.
  1258. *
  1259. * @since 4.4.0
  1260. *
  1261. * @param string $route Route to get data for.
  1262. * @param array $callbacks Callbacks to convert to data.
  1263. * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'.
  1264. * @return array|null Data for the route, or null if no publicly-visible data.
  1265. */
  1266. public function get_data_for_route( $route, $callbacks, $context = 'view' ) {
  1267. $data = array(
  1268. 'namespace' => '',
  1269. 'methods' => array(),
  1270. 'endpoints' => array(),
  1271. );
  1272. $allow_batch = false;
  1273. if ( isset( $this->route_options[ $route ] ) ) {
  1274. $options = $this->route_options[ $route ];
  1275. if ( isset( $options['namespace'] ) ) {
  1276. $data['namespace'] = $options['namespace'];
  1277. }
  1278. $allow_batch = isset( $options['allow_batch'] ) ? $options['allow_batch'] : false;
  1279. if ( isset( $options['schema'] ) && 'help' === $context ) {
  1280. $data['schema'] = call_user_func( $options['schema'] );
  1281. }
  1282. }
  1283. $allowed_schema_keywords = array_flip( rest_get_allowed_schema_keywords() );
  1284. $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route );
  1285. foreach ( $callbacks as $callback ) {
  1286. // Skip to the next route if any callback is hidden.
  1287. if ( empty( $callback['show_in_index'] ) ) {
  1288. continue;
  1289. }
  1290. $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) );
  1291. $endpoint_data = array(
  1292. 'methods' => array_keys( $callback['methods'] ),
  1293. );
  1294. $callback_batch = isset( $callback['allow_batch'] ) ? $callback['allow_batch'] : $allow_batch;
  1295. if ( $callback_batch ) {
  1296. $endpoint_data['allow_batch'] = $callback_batch;
  1297. }
  1298. if ( isset( $callback['args'] ) ) {
  1299. $endpoint_data['args'] = array();
  1300. foreach ( $callback['args'] as $key => $opts ) {
  1301. $arg_data = array_intersect_key( $opts, $allowed_schema_keywords );
  1302. $arg_data['required'] = ! empty( $opts['required'] );
  1303. $endpoint_data['args'][ $key ] = $arg_data;
  1304. }
  1305. }
  1306. $data['endpoints'][] = $endpoint_data;
  1307. // For non-variable routes, generate links.
  1308. if ( strpos( $route, '{' ) === false ) {
  1309. $data['_links'] = array(
  1310. 'self' => array(
  1311. array(
  1312. 'href' => rest_url( $route ),
  1313. ),
  1314. ),
  1315. );
  1316. }
  1317. }
  1318. if ( empty( $data['methods'] ) ) {
  1319. // No methods supported, hide the route.
  1320. return null;
  1321. }
  1322. return $data;
  1323. }
  1324. /**
  1325. * Gets the maximum number of requests that can be included in a batch.
  1326. *
  1327. * @since 5.6.0
  1328. *
  1329. * @return int The maximum requests.
  1330. */
  1331. protected function get_max_batch_size() {
  1332. /**
  1333. * Filters the maximum number of REST API requests that can be included in a batch.
  1334. *
  1335. * @since 5.6.0
  1336. *
  1337. * @param int $max_size The maximum size.
  1338. */
  1339. return apply_filters( 'rest_get_max_batch_size', 25 );
  1340. }
  1341. /**
  1342. * Serves the batch/v1 request.
  1343. *
  1344. * @since 5.6.0
  1345. *
  1346. * @param WP_REST_Request $batch_request The batch request object.
  1347. * @return WP_REST_Response The generated response object.
  1348. */
  1349. public function serve_batch_request_v1( WP_REST_Request $batch_request ) {
  1350. $requests = array();
  1351. foreach ( $batch_request['requests'] as $args ) {
  1352. $parsed_url = wp_parse_url( $args['path'] );
  1353. if ( false === $parsed_url ) {
  1354. $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) );
  1355. continue;
  1356. }
  1357. $single_request = new WP_REST_Request( isset( $args['method'] ) ? $args['method'] : 'POST', $parsed_url['path'] );
  1358. if ( ! empty( $parsed_url['query'] ) ) {
  1359. $query_args = null; // Satisfy linter.
  1360. wp_parse_str( $parsed_url['query'], $query_args );
  1361. $single_request->set_query_params( $query_args );
  1362. }
  1363. if ( ! empty( $args['body'] ) ) {
  1364. $single_request->set_body_params( $args['body'] );
  1365. }
  1366. if ( ! empty( $args['headers'] ) ) {
  1367. $single_request->set_headers( $args['headers'] );
  1368. }
  1369. $requests[] = $single_request;
  1370. }
  1371. $matches = array();
  1372. $validation = array();
  1373. $has_error = false;
  1374. foreach ( $requests as $single_request ) {
  1375. $match = $this->match_request_to_handler( $single_request );
  1376. $matches[] = $match;
  1377. $error = null;
  1378. if ( is_wp_error( $match ) ) {
  1379. $error = $match;
  1380. }
  1381. if ( ! $error ) {
  1382. list( $route, $handler ) = $match;
  1383. if ( isset( $handler['allow_batch'] ) ) {
  1384. $allow_batch = $handler['allow_batch'];
  1385. } else {
  1386. $route_options = $this->get_route_options( $route );
  1387. $allow_batch = isset( $route_options['allow_batch'] ) ? $route_options['allow_batch'] : false;
  1388. }
  1389. if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) {
  1390. $error = new WP_Error(
  1391. 'rest_batch_not_allowed',
  1392. __( 'The requested route does not support batch requests.' ),
  1393. array( 'status' => 400 )
  1394. );
  1395. }
  1396. }
  1397. if ( ! $error ) {
  1398. $check_required = $single_request->has_valid_params();
  1399. if ( is_wp_error( $check_required ) ) {
  1400. $error = $check_required;
  1401. }
  1402. }
  1403. if ( ! $error ) {
  1404. $check_sanitized = $single_request->sanitize_params();
  1405. if ( is_wp_error( $check_sanitized ) ) {
  1406. $error = $check_sanitized;
  1407. }
  1408. }
  1409. if ( $error ) {
  1410. $has_error = true;
  1411. $validation[] = $error;
  1412. } else {
  1413. $validation[] = true;
  1414. }
  1415. }
  1416. $responses = array();
  1417. if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) {
  1418. foreach ( $validation as $valid ) {
  1419. if ( is_wp_error( $valid ) ) {
  1420. $responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data();
  1421. } else {
  1422. $responses[] = null;
  1423. }
  1424. }
  1425. return new WP_REST_Response(
  1426. array(
  1427. 'failed' => 'validation',
  1428. 'responses' => $responses,
  1429. ),
  1430. WP_Http::MULTI_STATUS
  1431. );
  1432. }
  1433. foreach ( $requests as $i => $single_request ) {
  1434. $clean_request = clone $single_request;
  1435. $clean_request->set_url_params( array() );
  1436. $clean_request->set_attributes( array() );
  1437. $clean_request->set_default_params( array() );
  1438. /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
  1439. $result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );
  1440. if ( empty( $result ) ) {
  1441. $match = $matches[ $i ];
  1442. $error = null;
  1443. if ( is_wp_error( $validation[ $i ] ) ) {
  1444. $error = $validation[ $i ];
  1445. }
  1446. if ( is_wp_error( $match ) ) {
  1447. $result = $this->error_to_response( $match );
  1448. } else {
  1449. list( $route, $handler ) = $match;
  1450. if ( ! $error && ! is_callable( $handler['callback'] ) ) {
  1451. $error = new WP_Error(
  1452. 'rest_invalid_handler',
  1453. __( 'The handler for the route is invalid' ),
  1454. array( 'status' => 500 )
  1455. );
  1456. }
  1457. $result = $this->respond_to_request( $single_request, $route, $handler, $error );
  1458. }
  1459. }
  1460. /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
  1461. $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request );
  1462. $responses[] = $this->envelope_response( $result, false )->get_data();
  1463. }
  1464. return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS );
  1465. }
  1466. /**
  1467. * Sends an HTTP status code.
  1468. *
  1469. * @since 4.4.0
  1470. *
  1471. * @param int $code HTTP status.
  1472. */
  1473. protected function set_status( $code ) {
  1474. status_header( $code );
  1475. }
  1476. /**
  1477. * Sends an HTTP header.
  1478. *
  1479. * @since 4.4.0
  1480. *
  1481. * @param string $key Header key.
  1482. * @param string $value Header value.
  1483. */
  1484. public function send_header( $key, $value ) {
  1485. /*
  1486. * Sanitize as per RFC2616 (Section 4.2):
  1487. *
  1488. * Any LWS that occurs between field-content MAY be replaced with a
  1489. * single SP before interpreting the field value or forwarding the
  1490. * message downstream.
  1491. */
  1492. $value = preg_replace( '/\s+/', ' ', $value );
  1493. header( sprintf( '%s: %s', $key, $value ) );
  1494. }
  1495. /**
  1496. * Sends multiple HTTP headers.
  1497. *
  1498. * @since 4.4.0
  1499. *
  1500. * @param array $headers Map of header name to header value.
  1501. */
  1502. public function send_headers( $headers ) {
  1503. foreach ( $headers as $key => $value ) {
  1504. $this->send_header( $key, $value );
  1505. }
  1506. }
  1507. /**
  1508. * Removes an HTTP header from the current response.
  1509. *
  1510. * @since 4.8.0
  1511. *
  1512. * @param string $key Header key.
  1513. */
  1514. public function remove_header( $key ) {
  1515. header_remove( $key );
  1516. }
  1517. /**
  1518. * Retrieves the raw request entity (body).
  1519. *
  1520. * @since 4.4.0
  1521. *
  1522. * @global string $HTTP_RAW_POST_DATA Raw post data.
  1523. *
  1524. * @return string Raw request data.
  1525. */
  1526. public static function get_raw_data() {
  1527. // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
  1528. global $HTTP_RAW_POST_DATA;
  1529. // $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0.
  1530. if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
  1531. $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
  1532. }
  1533. return $HTTP_RAW_POST_DATA;
  1534. // phpcs:enable
  1535. }
  1536. /**
  1537. * Extracts headers from a PHP-style $_SERVER array.
  1538. *
  1539. * @since 4.4.0
  1540. *
  1541. * @param array $server Associative array similar to `$_SERVER`.
  1542. * @return array Headers extracted from the input.
  1543. */
  1544. public function get_headers( $server ) {
  1545. $headers = array();
  1546. // CONTENT_* headers are not prefixed with HTTP_.
  1547. $additional = array(
  1548. 'CONTENT_LENGTH' => true,
  1549. 'CONTENT_MD5' => true,
  1550. 'CONTENT_TYPE' => true,
  1551. );
  1552. foreach ( $server as $key => $value ) {
  1553. if ( strpos( $key, 'HTTP_' ) === 0 ) {
  1554. $headers[ substr( $key, 5 ) ] = $value;
  1555. } elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) {
  1556. /*
  1557. * In some server configurations, the authorization header is passed in this alternate location.
  1558. * Since it would not be passed in in both places we do not check for both headers and resolve.
  1559. */
  1560. $headers['AUTHORIZATION'] = $value;
  1561. } elseif ( isset( $additional[ $key ] ) ) {
  1562. $headers[ $key ] = $value;
  1563. }
  1564. }
  1565. return $headers;
  1566. }
  1567. }