rest-api.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  1. <?php
  2. /**
  3. * REST API functions.
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.4.0
  8. */
  9. /**
  10. * Version number for our API.
  11. *
  12. * @var string
  13. */
  14. define( 'REST_API_VERSION', '2.0' );
  15. /**
  16. * Registers a REST API route.
  17. *
  18. * Note: Do not use before the {@see 'rest_api_init'} hook.
  19. *
  20. * @since 4.4.0
  21. * @since 5.1.0 Added a _doing_it_wrong() notice when not called on or after the rest_api_init hook.
  22. *
  23. * @param string $namespace The first URL segment after core prefix. Should be unique to your package/plugin.
  24. * @param string $route The base URL for route you are adding.
  25. * @param array $args Optional. Either an array of options for the endpoint, or an array of arrays for
  26. * multiple methods. Default empty array.
  27. * @param bool $override Optional. If the route already exists, should we override it? True overrides,
  28. * false merges (with newer overriding if duplicate keys exist). Default false.
  29. * @return bool True on success, false on error.
  30. */
  31. function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
  32. if ( empty( $namespace ) ) {
  33. /*
  34. * Non-namespaced routes are not allowed, with the exception of the main
  35. * and namespace indexes. If you really need to register a
  36. * non-namespaced route, call `WP_REST_Server::register_route` directly.
  37. */
  38. _doing_it_wrong( 'register_rest_route', __( 'Routes must be namespaced with plugin or theme name and version.' ), '4.4.0' );
  39. return false;
  40. } elseif ( empty( $route ) ) {
  41. _doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
  42. return false;
  43. }
  44. if ( ! did_action( 'rest_api_init' ) ) {
  45. _doing_it_wrong(
  46. 'register_rest_route',
  47. sprintf(
  48. /* translators: %s: rest_api_init */
  49. __( 'REST API routes must be registered on the %s action.' ),
  50. '<code>rest_api_init</code>'
  51. ),
  52. '5.1.0'
  53. );
  54. }
  55. if ( isset( $args['args'] ) ) {
  56. $common_args = $args['args'];
  57. unset( $args['args'] );
  58. } else {
  59. $common_args = array();
  60. }
  61. if ( isset( $args['callback'] ) ) {
  62. // Upgrade a single set to multiple.
  63. $args = array( $args );
  64. }
  65. $defaults = array(
  66. 'methods' => 'GET',
  67. 'callback' => null,
  68. 'args' => array(),
  69. );
  70. foreach ( $args as $key => &$arg_group ) {
  71. if ( ! is_numeric( $key ) ) {
  72. // Route option, skip here.
  73. continue;
  74. }
  75. $arg_group = array_merge( $defaults, $arg_group );
  76. $arg_group['args'] = array_merge( $common_args, $arg_group['args'] );
  77. }
  78. $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
  79. rest_get_server()->register_route( $namespace, $full_route, $args, $override );
  80. return true;
  81. }
  82. /**
  83. * Registers a new field on an existing WordPress object type.
  84. *
  85. * @since 4.7.0
  86. *
  87. * @global array $wp_rest_additional_fields Holds registered fields, organized
  88. * by object type.
  89. *
  90. * @param string|array $object_type Object(s) the field is being registered
  91. * to, "post"|"term"|"comment" etc.
  92. * @param string $attribute The attribute name.
  93. * @param array $args {
  94. * Optional. An array of arguments used to handle the registered field.
  95. *
  96. * @type callable|null $get_callback Optional. The callback function used to retrieve the field value. Default is
  97. * 'null', the field will not be returned in the response. The function will
  98. * be passed the prepared object data.
  99. * @type callable|null $update_callback Optional. The callback function used to set and update the field value. Default
  100. * is 'null', the value cannot be set or updated. The function will be passed
  101. * the model object, like WP_Post.
  102. * @type array|null $schema Optional. The callback function used to create the schema for this field.
  103. * Default is 'null', no schema entry will be returned.
  104. * }
  105. */
  106. function register_rest_field( $object_type, $attribute, $args = array() ) {
  107. $defaults = array(
  108. 'get_callback' => null,
  109. 'update_callback' => null,
  110. 'schema' => null,
  111. );
  112. $args = wp_parse_args( $args, $defaults );
  113. global $wp_rest_additional_fields;
  114. $object_types = (array) $object_type;
  115. foreach ( $object_types as $object_type ) {
  116. $wp_rest_additional_fields[ $object_type ][ $attribute ] = $args;
  117. }
  118. }
  119. /**
  120. * Registers rewrite rules for the API.
  121. *
  122. * @since 4.4.0
  123. *
  124. * @see rest_api_register_rewrites()
  125. * @global WP $wp Current WordPress environment instance.
  126. */
  127. function rest_api_init() {
  128. rest_api_register_rewrites();
  129. global $wp;
  130. $wp->add_query_var( 'rest_route' );
  131. }
  132. /**
  133. * Adds REST rewrite rules.
  134. *
  135. * @since 4.4.0
  136. *
  137. * @see add_rewrite_rule()
  138. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  139. */
  140. function rest_api_register_rewrites() {
  141. global $wp_rewrite;
  142. add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' );
  143. add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' );
  144. add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/?$', 'index.php?rest_route=/', 'top' );
  145. add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/(.*)?', 'index.php?rest_route=/$matches[1]', 'top' );
  146. }
  147. /**
  148. * Registers the default REST API filters.
  149. *
  150. * Attached to the {@see 'rest_api_init'} action
  151. * to make testing and disabling these filters easier.
  152. *
  153. * @since 4.4.0
  154. */
  155. function rest_api_default_filters() {
  156. // Deprecated reporting.
  157. add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 );
  158. add_filter( 'deprecated_function_trigger_error', '__return_false' );
  159. add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 );
  160. add_filter( 'deprecated_argument_trigger_error', '__return_false' );
  161. // Default serving.
  162. add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
  163. add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
  164. add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
  165. add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );
  166. }
  167. /**
  168. * Registers default REST API routes.
  169. *
  170. * @since 4.7.0
  171. */
  172. function create_initial_rest_routes() {
  173. foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
  174. $controller = $post_type->get_rest_controller();
  175. if ( ! $controller ) {
  176. continue;
  177. }
  178. $controller->register_routes();
  179. if ( post_type_supports( $post_type->name, 'revisions' ) ) {
  180. $revisions_controller = new WP_REST_Revisions_Controller( $post_type->name );
  181. $revisions_controller->register_routes();
  182. }
  183. if ( 'attachment' !== $post_type->name ) {
  184. $autosaves_controller = new WP_REST_Autosaves_Controller( $post_type->name );
  185. $autosaves_controller->register_routes();
  186. }
  187. }
  188. // Post types.
  189. $controller = new WP_REST_Post_Types_Controller;
  190. $controller->register_routes();
  191. // Post statuses.
  192. $controller = new WP_REST_Post_Statuses_Controller;
  193. $controller->register_routes();
  194. // Taxonomies.
  195. $controller = new WP_REST_Taxonomies_Controller;
  196. $controller->register_routes();
  197. // Terms.
  198. foreach ( get_taxonomies( array( 'show_in_rest' => true ), 'object' ) as $taxonomy ) {
  199. $class = ! empty( $taxonomy->rest_controller_class ) ? $taxonomy->rest_controller_class : 'WP_REST_Terms_Controller';
  200. if ( ! class_exists( $class ) ) {
  201. continue;
  202. }
  203. $controller = new $class( $taxonomy->name );
  204. if ( ! is_subclass_of( $controller, 'WP_REST_Controller' ) ) {
  205. continue;
  206. }
  207. $controller->register_routes();
  208. }
  209. // Users.
  210. $controller = new WP_REST_Users_Controller;
  211. $controller->register_routes();
  212. // Comments.
  213. $controller = new WP_REST_Comments_Controller;
  214. $controller->register_routes();
  215. /**
  216. * Filters the search handlers to use in the REST search controller.
  217. *
  218. * @since 5.0.0
  219. *
  220. * @param array $search_handlers List of search handlers to use in the controller. Each search
  221. * handler instance must extend the `WP_REST_Search_Handler` class.
  222. * Default is only a handler for posts.
  223. */
  224. $search_handlers = apply_filters( 'wp_rest_search_handlers', array( new WP_REST_Post_Search_Handler() ) );
  225. $controller = new WP_REST_Search_Controller( $search_handlers );
  226. $controller->register_routes();
  227. // Block Renderer.
  228. $controller = new WP_REST_Block_Renderer_Controller;
  229. $controller->register_routes();
  230. // Settings.
  231. $controller = new WP_REST_Settings_Controller;
  232. $controller->register_routes();
  233. // Themes.
  234. $controller = new WP_REST_Themes_Controller;
  235. $controller->register_routes();
  236. }
  237. /**
  238. * Loads the REST API.
  239. *
  240. * @since 4.4.0
  241. *
  242. * @global WP $wp Current WordPress environment instance.
  243. */
  244. function rest_api_loaded() {
  245. if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
  246. return;
  247. }
  248. /**
  249. * Whether this is a REST Request.
  250. *
  251. * @since 4.4.0
  252. * @var bool
  253. */
  254. define( 'REST_REQUEST', true );
  255. // Initialize the server.
  256. $server = rest_get_server();
  257. // Fire off the request.
  258. $route = untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] );
  259. if ( empty( $route ) ) {
  260. $route = '/';
  261. }
  262. $server->serve_request( $route );
  263. // We're done.
  264. die();
  265. }
  266. /**
  267. * Retrieves the URL prefix for any API resource.
  268. *
  269. * @since 4.4.0
  270. *
  271. * @return string Prefix.
  272. */
  273. function rest_get_url_prefix() {
  274. /**
  275. * Filters the REST URL prefix.
  276. *
  277. * @since 4.4.0
  278. *
  279. * @param string $prefix URL prefix. Default 'wp-json'.
  280. */
  281. return apply_filters( 'rest_url_prefix', 'wp-json' );
  282. }
  283. /**
  284. * Retrieves the URL to a REST endpoint on a site.
  285. *
  286. * Note: The returned URL is NOT escaped.
  287. *
  288. * @since 4.4.0
  289. *
  290. * @todo Check if this is even necessary
  291. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  292. *
  293. * @param int $blog_id Optional. Blog ID. Default of null returns URL for current blog.
  294. * @param string $path Optional. REST route. Default '/'.
  295. * @param string $scheme Optional. Sanitization scheme. Default 'rest'.
  296. * @return string Full URL to the endpoint.
  297. */
  298. function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
  299. if ( empty( $path ) ) {
  300. $path = '/';
  301. }
  302. $path = '/' . ltrim( $path, '/' );
  303. if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
  304. global $wp_rewrite;
  305. if ( $wp_rewrite->using_index_permalinks() ) {
  306. $url = get_home_url( $blog_id, $wp_rewrite->index . '/' . rest_get_url_prefix(), $scheme );
  307. } else {
  308. $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
  309. }
  310. $url .= $path;
  311. } else {
  312. $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
  313. // nginx only allows HTTP/1.0 methods when redirecting from / to /index.php
  314. // To work around this, we manually add index.php to the URL, avoiding the redirect.
  315. if ( 'index.php' !== substr( $url, 9 ) ) {
  316. $url .= 'index.php';
  317. }
  318. $url = add_query_arg( 'rest_route', $path, $url );
  319. }
  320. if ( is_ssl() && isset( $_SERVER['SERVER_NAME'] ) ) {
  321. // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
  322. if ( $_SERVER['SERVER_NAME'] === parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) ) {
  323. $url = set_url_scheme( $url, 'https' );
  324. }
  325. }
  326. if ( is_admin() && force_ssl_admin() ) {
  327. // In this situation the home URL may be http:, and `is_ssl()` may be
  328. // false, but the admin is served over https: (one way or another), so
  329. // REST API usage will be blocked by browsers unless it is also served
  330. // over HTTPS.
  331. $url = set_url_scheme( $url, 'https' );
  332. }
  333. /**
  334. * Filters the REST URL.
  335. *
  336. * Use this filter to adjust the url returned by the get_rest_url() function.
  337. *
  338. * @since 4.4.0
  339. *
  340. * @param string $url REST URL.
  341. * @param string $path REST route.
  342. * @param int $blog_id Blog ID.
  343. * @param string $scheme Sanitization scheme.
  344. */
  345. return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
  346. }
  347. /**
  348. * Retrieves the URL to a REST endpoint.
  349. *
  350. * Note: The returned URL is NOT escaped.
  351. *
  352. * @since 4.4.0
  353. *
  354. * @param string $path Optional. REST route. Default empty.
  355. * @param string $scheme Optional. Sanitization scheme. Default 'rest'.
  356. * @return string Full URL to the endpoint.
  357. */
  358. function rest_url( $path = '', $scheme = 'rest' ) {
  359. return get_rest_url( null, $path, $scheme );
  360. }
  361. /**
  362. * Do a REST request.
  363. *
  364. * Used primarily to route internal requests through WP_REST_Server.
  365. *
  366. * @since 4.4.0
  367. *
  368. * @param WP_REST_Request|string $request Request.
  369. * @return WP_REST_Response REST response.
  370. */
  371. function rest_do_request( $request ) {
  372. $request = rest_ensure_request( $request );
  373. return rest_get_server()->dispatch( $request );
  374. }
  375. /**
  376. * Retrieves the current REST server instance.
  377. *
  378. * Instantiates a new instance if none exists already.
  379. *
  380. * @since 4.5.0
  381. *
  382. * @global WP_REST_Server $wp_rest_server REST server instance.
  383. *
  384. * @return WP_REST_Server REST server instance.
  385. */
  386. function rest_get_server() {
  387. /* @var WP_REST_Server $wp_rest_server */
  388. global $wp_rest_server;
  389. if ( empty( $wp_rest_server ) ) {
  390. /**
  391. * Filters the REST Server Class.
  392. *
  393. * This filter allows you to adjust the server class used by the API, using a
  394. * different class to handle requests.
  395. *
  396. * @since 4.4.0
  397. *
  398. * @param string $class_name The name of the server class. Default 'WP_REST_Server'.
  399. */
  400. $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
  401. $wp_rest_server = new $wp_rest_server_class;
  402. /**
  403. * Fires when preparing to serve an API request.
  404. *
  405. * Endpoint objects should be created and register their hooks on this action rather
  406. * than another action to ensure they're only loaded when needed.
  407. *
  408. * @since 4.4.0
  409. *
  410. * @param WP_REST_Server $wp_rest_server Server object.
  411. */
  412. do_action( 'rest_api_init', $wp_rest_server );
  413. }
  414. return $wp_rest_server;
  415. }
  416. /**
  417. * Ensures request arguments are a request object (for consistency).
  418. *
  419. * @since 4.4.0
  420. * @since 5.3.0 Accept string argument for the request path.
  421. *
  422. * @param array|string|WP_REST_Request $request Request to check.
  423. * @return WP_REST_Request REST request instance.
  424. */
  425. function rest_ensure_request( $request ) {
  426. if ( $request instanceof WP_REST_Request ) {
  427. return $request;
  428. }
  429. if ( is_string( $request ) ) {
  430. return new WP_REST_Request( 'GET', $request );
  431. }
  432. return new WP_REST_Request( 'GET', '', $request );
  433. }
  434. /**
  435. * Ensures a REST response is a response object (for consistency).
  436. *
  437. * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
  438. * without needing to double-check the object. Will also allow WP_Error to indicate error
  439. * responses, so users should immediately check for this value.
  440. *
  441. * @since 4.4.0
  442. *
  443. * @param WP_Error|WP_HTTP_Response|mixed $response Response to check.
  444. * @return WP_REST_Response|mixed If response generated an error, WP_Error, if response
  445. * is already an instance, WP_HTTP_Response, otherwise
  446. * returns a new WP_REST_Response instance.
  447. */
  448. function rest_ensure_response( $response ) {
  449. if ( is_wp_error( $response ) ) {
  450. return $response;
  451. }
  452. if ( $response instanceof WP_HTTP_Response ) {
  453. return $response;
  454. }
  455. return new WP_REST_Response( $response );
  456. }
  457. /**
  458. * Handles _deprecated_function() errors.
  459. *
  460. * @since 4.4.0
  461. *
  462. * @param string $function The function that was called.
  463. * @param string $replacement The function that should have been called.
  464. * @param string $version Version.
  465. */
  466. function rest_handle_deprecated_function( $function, $replacement, $version ) {
  467. if ( ! WP_DEBUG || headers_sent() ) {
  468. return;
  469. }
  470. if ( ! empty( $replacement ) ) {
  471. /* translators: 1: Function name, 2: WordPress version number, 3: New function name. */
  472. $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
  473. } else {
  474. /* translators: 1: Function name, 2: WordPress version number. */
  475. $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
  476. }
  477. header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
  478. }
  479. /**
  480. * Handles _deprecated_argument() errors.
  481. *
  482. * @since 4.4.0
  483. *
  484. * @param string $function The function that was called.
  485. * @param string $message A message regarding the change.
  486. * @param string $version Version.
  487. */
  488. function rest_handle_deprecated_argument( $function, $message, $version ) {
  489. if ( ! WP_DEBUG || headers_sent() ) {
  490. return;
  491. }
  492. if ( ! empty( $message ) ) {
  493. /* translators: 1: Function name, 2: WordPress version number, 3: Error message. */
  494. $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $message );
  495. } else {
  496. /* translators: 1: Function name, 2: WordPress version number. */
  497. $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
  498. }
  499. header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
  500. }
  501. /**
  502. * Sends Cross-Origin Resource Sharing headers with API requests.
  503. *
  504. * @since 4.4.0
  505. *
  506. * @param mixed $value Response data.
  507. * @return mixed Response data.
  508. */
  509. function rest_send_cors_headers( $value ) {
  510. $origin = get_http_origin();
  511. if ( $origin ) {
  512. // Requests from file:// and data: URLs send "Origin: null"
  513. if ( 'null' !== $origin ) {
  514. $origin = esc_url_raw( $origin );
  515. }
  516. header( 'Access-Control-Allow-Origin: ' . $origin );
  517. header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
  518. header( 'Access-Control-Allow-Credentials: true' );
  519. header( 'Vary: Origin', false );
  520. } elseif ( ! headers_sent() && 'GET' === $_SERVER['REQUEST_METHOD'] && ! is_user_logged_in() ) {
  521. header( 'Vary: Origin', false );
  522. }
  523. return $value;
  524. }
  525. /**
  526. * Handles OPTIONS requests for the server.
  527. *
  528. * This is handled outside of the server code, as it doesn't obey normal route
  529. * mapping.
  530. *
  531. * @since 4.4.0
  532. *
  533. * @param mixed $response Current response, either response or `null` to indicate pass-through.
  534. * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
  535. * @param WP_REST_Request $request The request that was used to make current response.
  536. * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
  537. */
  538. function rest_handle_options_request( $response, $handler, $request ) {
  539. if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
  540. return $response;
  541. }
  542. $response = new WP_REST_Response();
  543. $data = array();
  544. foreach ( $handler->get_routes() as $route => $endpoints ) {
  545. $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $matches );
  546. if ( ! $match ) {
  547. continue;
  548. }
  549. $args = array();
  550. foreach ( $matches as $param => $value ) {
  551. if ( ! is_int( $param ) ) {
  552. $args[ $param ] = $value;
  553. }
  554. }
  555. foreach ( $endpoints as $endpoint ) {
  556. // Remove the redundant preg_match argument.
  557. unset( $args[0] );
  558. $request->set_url_params( $args );
  559. $request->set_attributes( $endpoint );
  560. }
  561. $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
  562. $response->set_matched_route( $route );
  563. break;
  564. }
  565. $response->set_data( $data );
  566. return $response;
  567. }
  568. /**
  569. * Sends the "Allow" header to state all methods that can be sent to the current route.
  570. *
  571. * @since 4.4.0
  572. *
  573. * @param WP_REST_Response $response Current response being served.
  574. * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
  575. * @param WP_REST_Request $request The request that was used to make current response.
  576. * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
  577. */
  578. function rest_send_allow_header( $response, $server, $request ) {
  579. $matched_route = $response->get_matched_route();
  580. if ( ! $matched_route ) {
  581. return $response;
  582. }
  583. $routes = $server->get_routes();
  584. $allowed_methods = array();
  585. // Get the allowed methods across the routes.
  586. foreach ( $routes[ $matched_route ] as $_handler ) {
  587. foreach ( $_handler['methods'] as $handler_method => $value ) {
  588. if ( ! empty( $_handler['permission_callback'] ) ) {
  589. $permission = call_user_func( $_handler['permission_callback'], $request );
  590. $allowed_methods[ $handler_method ] = true === $permission;
  591. } else {
  592. $allowed_methods[ $handler_method ] = true;
  593. }
  594. }
  595. }
  596. // Strip out all the methods that are not allowed (false values).
  597. $allowed_methods = array_filter( $allowed_methods );
  598. if ( $allowed_methods ) {
  599. $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
  600. }
  601. return $response;
  602. }
  603. /**
  604. * Recursively computes the intersection of arrays using keys for comparison.
  605. *
  606. * @param array $array1 The array with master keys to check.
  607. * @param array $array2 An array to compare keys against.
  608. *
  609. * @return array An associative array containing all the entries of array1 which have keys that are present in all arguments.
  610. */
  611. function _rest_array_intersect_key_recursive( $array1, $array2 ) {
  612. $array1 = array_intersect_key( $array1, $array2 );
  613. foreach ( $array1 as $key => $value ) {
  614. if ( is_array( $value ) && is_array( $array2[ $key ] ) ) {
  615. $array1[ $key ] = _rest_array_intersect_key_recursive( $value, $array2[ $key ] );
  616. }
  617. }
  618. return $array1;
  619. }
  620. /**
  621. * Filter the API response to include only a white-listed set of response object fields.
  622. *
  623. * @since 4.8.0
  624. *
  625. * @param WP_REST_Response $response Current response being served.
  626. * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
  627. * @param WP_REST_Request $request The request that was used to make current response.
  628. *
  629. * @return WP_REST_Response Response to be served, trimmed down to contain a subset of fields.
  630. */
  631. function rest_filter_response_fields( $response, $server, $request ) {
  632. if ( ! isset( $request['_fields'] ) || $response->is_error() ) {
  633. return $response;
  634. }
  635. $data = $response->get_data();
  636. $fields = wp_parse_list( $request['_fields'] );
  637. if ( 0 === count( $fields ) ) {
  638. return $response;
  639. }
  640. // Trim off outside whitespace from the comma delimited list.
  641. $fields = array_map( 'trim', $fields );
  642. // Create nested array of accepted field hierarchy.
  643. $fields_as_keyed = array();
  644. foreach ( $fields as $field ) {
  645. $parts = explode( '.', $field );
  646. $ref = &$fields_as_keyed;
  647. while ( count( $parts ) > 1 ) {
  648. $next = array_shift( $parts );
  649. if ( isset( $ref[ $next ] ) && true === $ref[ $next ] ) {
  650. // Skip any sub-properties if their parent prop is already marked for inclusion.
  651. break 2;
  652. }
  653. $ref[ $next ] = isset( $ref[ $next ] ) ? $ref[ $next ] : array();
  654. $ref = &$ref[ $next ];
  655. }
  656. $last = array_shift( $parts );
  657. $ref[ $last ] = true;
  658. }
  659. if ( wp_is_numeric_array( $data ) ) {
  660. $new_data = array();
  661. foreach ( $data as $item ) {
  662. $new_data[] = _rest_array_intersect_key_recursive( $item, $fields_as_keyed );
  663. }
  664. } else {
  665. $new_data = _rest_array_intersect_key_recursive( $data, $fields_as_keyed );
  666. }
  667. $response->set_data( $new_data );
  668. return $response;
  669. }
  670. /**
  671. * Given an array of fields to include in a response, some of which may be
  672. * `nested.fields`, determine whether the provided field should be included
  673. * in the response body.
  674. *
  675. * If a parent field is passed in, the presence of any nested field within
  676. * that parent will cause the method to return `true`. For example "title"
  677. * will return true if any of `title`, `title.raw` or `title.rendered` is
  678. * provided.
  679. *
  680. * @since 5.3.0
  681. *
  682. * @param string $field A field to test for inclusion in the response body.
  683. * @param array $fields An array of string fields supported by the endpoint.
  684. * @return bool Whether to include the field or not.
  685. */
  686. function rest_is_field_included( $field, $fields ) {
  687. if ( in_array( $field, $fields, true ) ) {
  688. return true;
  689. }
  690. foreach ( $fields as $accepted_field ) {
  691. // Check to see if $field is the parent of any item in $fields.
  692. // A field "parent" should be accepted if "parent.child" is accepted.
  693. if ( strpos( $accepted_field, "$field." ) === 0 ) {
  694. return true;
  695. }
  696. // Conversely, if "parent" is accepted, all "parent.child" fields should
  697. // also be accepted.
  698. if ( strpos( $field, "$accepted_field." ) === 0 ) {
  699. return true;
  700. }
  701. }
  702. return false;
  703. }
  704. /**
  705. * Adds the REST API URL to the WP RSD endpoint.
  706. *
  707. * @since 4.4.0
  708. *
  709. * @see get_rest_url()
  710. */
  711. function rest_output_rsd() {
  712. $api_root = get_rest_url();
  713. if ( empty( $api_root ) ) {
  714. return;
  715. }
  716. ?>
  717. <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
  718. <?php
  719. }
  720. /**
  721. * Outputs the REST API link tag into page header.
  722. *
  723. * @since 4.4.0
  724. *
  725. * @see get_rest_url()
  726. */
  727. function rest_output_link_wp_head() {
  728. $api_root = get_rest_url();
  729. if ( empty( $api_root ) ) {
  730. return;
  731. }
  732. echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
  733. }
  734. /**
  735. * Sends a Link header for the REST API.
  736. *
  737. * @since 4.4.0
  738. */
  739. function rest_output_link_header() {
  740. if ( headers_sent() ) {
  741. return;
  742. }
  743. $api_root = get_rest_url();
  744. if ( empty( $api_root ) ) {
  745. return;
  746. }
  747. header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
  748. }
  749. /**
  750. * Checks for errors when using cookie-based authentication.
  751. *
  752. * WordPress' built-in cookie authentication is always active
  753. * for logged in users. However, the API has to check nonces
  754. * for each request to ensure users are not vulnerable to CSRF.
  755. *
  756. * @since 4.4.0
  757. *
  758. * @global mixed $wp_rest_auth_cookie
  759. *
  760. * @param WP_Error|mixed $result Error from another authentication handler,
  761. * null if we should handle it, or another value
  762. * if not.
  763. * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
  764. */
  765. function rest_cookie_check_errors( $result ) {
  766. if ( ! empty( $result ) ) {
  767. return $result;
  768. }
  769. global $wp_rest_auth_cookie;
  770. /*
  771. * Is cookie authentication being used? (If we get an auth
  772. * error, but we're still logged in, another authentication
  773. * must have been used).
  774. */
  775. if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
  776. return $result;
  777. }
  778. // Determine if there is a nonce.
  779. $nonce = null;
  780. if ( isset( $_REQUEST['_wpnonce'] ) ) {
  781. $nonce = $_REQUEST['_wpnonce'];
  782. } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
  783. $nonce = $_SERVER['HTTP_X_WP_NONCE'];
  784. }
  785. if ( null === $nonce ) {
  786. // No nonce at all, so act as if it's an unauthenticated request.
  787. wp_set_current_user( 0 );
  788. return true;
  789. }
  790. // Check the nonce.
  791. $result = wp_verify_nonce( $nonce, 'wp_rest' );
  792. if ( ! $result ) {
  793. return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
  794. }
  795. // Send a refreshed nonce in header.
  796. rest_get_server()->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) );
  797. return true;
  798. }
  799. /**
  800. * Collects cookie authentication status.
  801. *
  802. * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
  803. *
  804. * @since 4.4.0
  805. *
  806. * @see current_action()
  807. * @global mixed $wp_rest_auth_cookie
  808. */
  809. function rest_cookie_collect_status() {
  810. global $wp_rest_auth_cookie;
  811. $status_type = current_action();
  812. if ( 'auth_cookie_valid' !== $status_type ) {
  813. $wp_rest_auth_cookie = substr( $status_type, 12 );
  814. return;
  815. }
  816. $wp_rest_auth_cookie = true;
  817. }
  818. /**
  819. * Parses an RFC3339 time into a Unix timestamp.
  820. *
  821. * @since 4.4.0
  822. *
  823. * @param string $date RFC3339 timestamp.
  824. * @param bool $force_utc Optional. Whether to force UTC timezone instead of using
  825. * the timestamp's timezone. Default false.
  826. * @return int Unix timestamp.
  827. */
  828. function rest_parse_date( $date, $force_utc = false ) {
  829. if ( $force_utc ) {
  830. $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
  831. }
  832. $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
  833. if ( ! preg_match( $regex, $date, $matches ) ) {
  834. return false;
  835. }
  836. return strtotime( $date );
  837. }
  838. /**
  839. * Parses a date into both its local and UTC equivalent, in MySQL datetime format.
  840. *
  841. * @since 4.4.0
  842. *
  843. * @see rest_parse_date()
  844. *
  845. * @param string $date RFC3339 timestamp.
  846. * @param bool $is_utc Whether the provided date should be interpreted as UTC. Default false.
  847. * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
  848. * null on failure.
  849. */
  850. function rest_get_date_with_gmt( $date, $is_utc = false ) {
  851. // Whether or not the original date actually has a timezone string
  852. // changes the way we need to do timezone conversion. Store this info
  853. // before parsing the date, and use it later.
  854. $has_timezone = preg_match( '#(Z|[+-]\d{2}(:\d{2})?)$#', $date );
  855. $date = rest_parse_date( $date );
  856. if ( empty( $date ) ) {
  857. return null;
  858. }
  859. // At this point $date could either be a local date (if we were passed a
  860. // *local* date without a timezone offset) or a UTC date (otherwise).
  861. // Timezone conversion needs to be handled differently between these two
  862. // cases.
  863. if ( ! $is_utc && ! $has_timezone ) {
  864. $local = gmdate( 'Y-m-d H:i:s', $date );
  865. $utc = get_gmt_from_date( $local );
  866. } else {
  867. $utc = gmdate( 'Y-m-d H:i:s', $date );
  868. $local = get_date_from_gmt( $utc );
  869. }
  870. return array( $local, $utc );
  871. }
  872. /**
  873. * Returns a contextual HTTP error code for authorization failure.
  874. *
  875. * @since 4.7.0
  876. *
  877. * @return integer 401 if the user is not logged in, 403 if the user is logged in.
  878. */
  879. function rest_authorization_required_code() {
  880. return is_user_logged_in() ? 403 : 401;
  881. }
  882. /**
  883. * Validate a request argument based on details registered to the route.
  884. *
  885. * @since 4.7.0
  886. *
  887. * @param mixed $value
  888. * @param WP_REST_Request $request
  889. * @param string $param
  890. * @return WP_Error|boolean
  891. */
  892. function rest_validate_request_arg( $value, $request, $param ) {
  893. $attributes = $request->get_attributes();
  894. if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
  895. return true;
  896. }
  897. $args = $attributes['args'][ $param ];
  898. return rest_validate_value_from_schema( $value, $args, $param );
  899. }
  900. /**
  901. * Sanitize a request argument based on details registered to the route.
  902. *
  903. * @since 4.7.0
  904. *
  905. * @param mixed $value
  906. * @param WP_REST_Request $request
  907. * @param string $param
  908. * @return mixed
  909. */
  910. function rest_sanitize_request_arg( $value, $request, $param ) {
  911. $attributes = $request->get_attributes();
  912. if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
  913. return $value;
  914. }
  915. $args = $attributes['args'][ $param ];
  916. return rest_sanitize_value_from_schema( $value, $args );
  917. }
  918. /**
  919. * Parse a request argument based on details registered to the route.
  920. *
  921. * Runs a validation check and sanitizes the value, primarily to be used via
  922. * the `sanitize_callback` arguments in the endpoint args registration.
  923. *
  924. * @since 4.7.0
  925. *
  926. * @param mixed $value
  927. * @param WP_REST_Request $request
  928. * @param string $param
  929. * @return mixed
  930. */
  931. function rest_parse_request_arg( $value, $request, $param ) {
  932. $is_valid = rest_validate_request_arg( $value, $request, $param );
  933. if ( is_wp_error( $is_valid ) ) {
  934. return $is_valid;
  935. }
  936. $value = rest_sanitize_request_arg( $value, $request, $param );
  937. return $value;
  938. }
  939. /**
  940. * Determines if an IP address is valid.
  941. *
  942. * Handles both IPv4 and IPv6 addresses.
  943. *
  944. * @since 4.7.0
  945. *
  946. * @param string $ip IP address.
  947. * @return string|false The valid IP address, otherwise false.
  948. */
  949. function rest_is_ip_address( $ip ) {
  950. $ipv4_pattern = '/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
  951. if ( ! preg_match( $ipv4_pattern, $ip ) && ! Requests_IPv6::check_ipv6( $ip ) ) {
  952. return false;
  953. }
  954. return $ip;
  955. }
  956. /**
  957. * Changes a boolean-like value into the proper boolean value.
  958. *
  959. * @since 4.7.0
  960. *
  961. * @param bool|string|int $value The value being evaluated.
  962. * @return boolean Returns the proper associated boolean value.
  963. */
  964. function rest_sanitize_boolean( $value ) {
  965. // String values are translated to `true`; make sure 'false' is false.
  966. if ( is_string( $value ) ) {
  967. $value = strtolower( $value );
  968. if ( in_array( $value, array( 'false', '0' ), true ) ) {
  969. $value = false;
  970. }
  971. }
  972. // Everything else will map nicely to boolean.
  973. return (bool) $value;
  974. }
  975. /**
  976. * Determines if a given value is boolean-like.
  977. *
  978. * @since 4.7.0
  979. *
  980. * @param bool|string $maybe_bool The value being evaluated.
  981. * @return boolean True if a boolean, otherwise false.
  982. */
  983. function rest_is_boolean( $maybe_bool ) {
  984. if ( is_bool( $maybe_bool ) ) {
  985. return true;
  986. }
  987. if ( is_string( $maybe_bool ) ) {
  988. $maybe_bool = strtolower( $maybe_bool );
  989. $valid_boolean_values = array(
  990. 'false',
  991. 'true',
  992. '0',
  993. '1',
  994. );
  995. return in_array( $maybe_bool, $valid_boolean_values, true );
  996. }
  997. if ( is_int( $maybe_bool ) ) {
  998. return in_array( $maybe_bool, array( 0, 1 ), true );
  999. }
  1000. return false;
  1001. }
  1002. /**
  1003. * Retrieves the avatar urls in various sizes.
  1004. *
  1005. * @since 4.7.0
  1006. *
  1007. * @see get_avatar_url()
  1008. *
  1009. * @param mixed $id_or_email The Gravatar to retrieve a URL for. Accepts a user_id, gravatar md5 hash,
  1010. * user email, WP_User object, WP_Post object, or WP_Comment object.
  1011. * @return array $urls Gravatar url for each size.
  1012. */
  1013. function rest_get_avatar_urls( $id_or_email ) {
  1014. $avatar_sizes = rest_get_avatar_sizes();
  1015. $urls = array();
  1016. foreach ( $avatar_sizes as $size ) {
  1017. $urls[ $size ] = get_avatar_url( $id_or_email, array( 'size' => $size ) );
  1018. }
  1019. return $urls;
  1020. }
  1021. /**
  1022. * Retrieves the pixel sizes for avatars.
  1023. *
  1024. * @since 4.7.0
  1025. *
  1026. * @return array List of pixel sizes for avatars. Default `[ 24, 48, 96 ]`.
  1027. */
  1028. function rest_get_avatar_sizes() {
  1029. /**
  1030. * Filters the REST avatar sizes.
  1031. *
  1032. * Use this filter to adjust the array of sizes returned by the
  1033. * `rest_get_avatar_sizes` function.
  1034. *
  1035. * @since 4.4.0
  1036. *
  1037. * @param array $sizes An array of int values that are the pixel sizes for avatars.
  1038. * Default `[ 24, 48, 96 ]`.
  1039. */
  1040. return apply_filters( 'rest_avatar_sizes', array( 24, 48, 96 ) );
  1041. }
  1042. /**
  1043. * Validate a value based on a schema.
  1044. *
  1045. * @since 4.7.0
  1046. *
  1047. * @param mixed $value The value to validate.
  1048. * @param array $args Schema array to use for validation.
  1049. * @param string $param The parameter name, used in error messages.
  1050. * @return true|WP_Error
  1051. */
  1052. function rest_validate_value_from_schema( $value, $args, $param = '' ) {
  1053. if ( is_array( $args['type'] ) ) {
  1054. foreach ( $args['type'] as $type ) {
  1055. $type_args = $args;
  1056. $type_args['type'] = $type;
  1057. if ( true === rest_validate_value_from_schema( $value, $type_args, $param ) ) {
  1058. return true;
  1059. }
  1060. }
  1061. /* translators: 1: Parameter, 2: List of types. */
  1062. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s' ), $param, implode( ',', $args['type'] ) ) );
  1063. }
  1064. if ( 'array' === $args['type'] ) {
  1065. if ( ! is_null( $value ) ) {
  1066. $value = wp_parse_list( $value );
  1067. }
  1068. if ( ! wp_is_numeric_array( $value ) ) {
  1069. /* translators: 1: Parameter, 2: Type name. */
  1070. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'array' ) );
  1071. }
  1072. foreach ( $value as $index => $v ) {
  1073. $is_valid = rest_validate_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' );
  1074. if ( is_wp_error( $is_valid ) ) {
  1075. return $is_valid;
  1076. }
  1077. }
  1078. }
  1079. if ( 'object' === $args['type'] ) {
  1080. if ( $value instanceof stdClass ) {
  1081. $value = (array) $value;
  1082. }
  1083. if ( $value instanceof JsonSerializable ) {
  1084. $value = $value->jsonSerialize();
  1085. }
  1086. if ( ! is_array( $value ) ) {
  1087. /* translators: 1: Parameter, 2: Type name. */
  1088. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'object' ) );
  1089. }
  1090. foreach ( $value as $property => $v ) {
  1091. if ( isset( $args['properties'][ $property ] ) ) {
  1092. $is_valid = rest_validate_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' );
  1093. if ( is_wp_error( $is_valid ) ) {
  1094. return $is_valid;
  1095. }
  1096. } elseif ( isset( $args['additionalProperties'] ) ) {
  1097. if ( false === $args['additionalProperties'] ) {
  1098. /* translators: %s: Property of an object. */
  1099. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not a valid property of Object.' ), $property ) );
  1100. }
  1101. if ( is_array( $args['additionalProperties'] ) ) {
  1102. $is_valid = rest_validate_value_from_schema( $v, $args['additionalProperties'], $param . '[' . $property . ']' );
  1103. if ( is_wp_error( $is_valid ) ) {
  1104. return $is_valid;
  1105. }
  1106. }
  1107. }
  1108. }
  1109. }
  1110. if ( 'null' === $args['type'] ) {
  1111. if ( null !== $value ) {
  1112. /* translators: 1: Parameter, 2: Type name. */
  1113. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'null' ) );
  1114. }
  1115. return true;
  1116. }
  1117. if ( ! empty( $args['enum'] ) ) {
  1118. if ( ! in_array( $value, $args['enum'], true ) ) {
  1119. /* translators: 1: Parameter, 2: List of valid values. */
  1120. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not one of %2$s.' ), $param, implode( ', ', $args['enum'] ) ) );
  1121. }
  1122. }
  1123. if ( in_array( $args['type'], array( 'integer', 'number' ) ) && ! is_numeric( $value ) ) {
  1124. /* translators: 1: Parameter, 2: Type name. */
  1125. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, $args['type'] ) );
  1126. }
  1127. if ( 'integer' === $args['type'] && round( floatval( $value ) ) !== floatval( $value ) ) {
  1128. /* translators: 1: Parameter, 2: Type name. */
  1129. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'integer' ) );
  1130. }
  1131. if ( 'boolean' === $args['type'] && ! rest_is_boolean( $value ) ) {
  1132. /* translators: 1: Parameter, 2: Type name. */
  1133. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'boolean' ) );
  1134. }
  1135. if ( 'string' === $args['type'] && ! is_string( $value ) ) {
  1136. /* translators: 1: Parameter, 2: Type name. */
  1137. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
  1138. }
  1139. if ( isset( $args['format'] ) ) {
  1140. switch ( $args['format'] ) {
  1141. case 'date-time':
  1142. if ( ! rest_parse_date( $value ) ) {
  1143. return new WP_Error( 'rest_invalid_date', __( 'Invalid date.' ) );
  1144. }
  1145. break;
  1146. case 'email':
  1147. if ( ! is_email( $value ) ) {
  1148. return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ) );
  1149. }
  1150. break;
  1151. case 'ip':
  1152. if ( ! rest_is_ip_address( $value ) ) {
  1153. /* translators: %s: IP address. */
  1154. return new WP_Error( 'rest_invalid_param', sprintf( __( '%s is not a valid IP address.' ), $param ) );
  1155. }
  1156. break;
  1157. }
  1158. }
  1159. if ( in_array( $args['type'], array( 'number', 'integer' ), true ) && ( isset( $args['minimum'] ) || isset( $args['maximum'] ) ) ) {
  1160. if ( isset( $args['minimum'] ) && ! isset( $args['maximum'] ) ) {
  1161. if ( ! empty( $args['exclusiveMinimum'] ) && $value <= $args['minimum'] ) {
  1162. /* translators: 1: Parameter, 2: Minimum number. */
  1163. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d' ), $param, $args['minimum'] ) );
  1164. } elseif ( empty( $args['exclusiveMinimum'] ) && $value < $args['minimum'] ) {
  1165. /* translators: 1: Parameter, 2: Minimum number. */
  1166. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than or equal to %2$d' ), $param, $args['minimum'] ) );
  1167. }
  1168. } elseif ( isset( $args['maximum'] ) && ! isset( $args['minimum'] ) ) {
  1169. if ( ! empty( $args['exclusiveMaximum'] ) && $value >= $args['maximum'] ) {
  1170. /* translators: 1: Parameter, 2: Maximum number. */
  1171. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d' ), $param, $args['maximum'] ) );
  1172. } elseif ( empty( $args['exclusiveMaximum'] ) && $value > $args['maximum'] ) {
  1173. /* translators: 1: Parameter, 2: Maximum number. */
  1174. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than or equal to %2$d' ), $param, $args['maximum'] ) );
  1175. }
  1176. } elseif ( isset( $args['maximum'] ) && isset( $args['minimum'] ) ) {
  1177. if ( ! empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
  1178. if ( $value >= $args['maximum'] || $value <= $args['minimum'] ) {
  1179. /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
  1180. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (exclusive) and %3$d (exclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
  1181. }
  1182. } elseif ( empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
  1183. if ( $value >= $args['maximum'] || $value < $args['minimum'] ) {
  1184. /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
  1185. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (inclusive) and %3$d (exclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
  1186. }
  1187. } elseif ( ! empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
  1188. if ( $value > $args['maximum'] || $value <= $args['minimum'] ) {
  1189. /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
  1190. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (exclusive) and %3$d (inclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
  1191. }
  1192. } elseif ( empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
  1193. if ( $value > $args['maximum'] || $value < $args['minimum'] ) {
  1194. /* translators: 1: Parameter, 2: Minimum number, 3: Maximum number. */
  1195. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (inclusive) and %3$d (inclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
  1196. }
  1197. }
  1198. }
  1199. }
  1200. return true;
  1201. }
  1202. /**
  1203. * Sanitize a value based on a schema.
  1204. *
  1205. * @since 4.7.0
  1206. *
  1207. * @param mixed $value The value to sanitize.
  1208. * @param array $args Schema array to use for sanitization.
  1209. * @return true|WP_Error
  1210. */
  1211. function rest_sanitize_value_from_schema( $value, $args ) {
  1212. if ( is_array( $args['type'] ) ) {
  1213. // Determine which type the value was validated against, and use that type when performing sanitization
  1214. $validated_type = '';
  1215. foreach ( $args['type'] as $type ) {
  1216. $type_args = $args;
  1217. $type_args['type'] = $type;
  1218. if ( ! is_wp_error( rest_validate_value_from_schema( $value, $type_args ) ) ) {
  1219. $validated_type = $type;
  1220. break;
  1221. }
  1222. }
  1223. if ( ! $validated_type ) {
  1224. return null;
  1225. }
  1226. $args['type'] = $validated_type;
  1227. }
  1228. if ( 'array' === $args['type'] ) {
  1229. if ( empty( $args['items'] ) ) {
  1230. return (array) $value;
  1231. }
  1232. $value = wp_parse_list( $value );
  1233. foreach ( $value as $index => $v ) {
  1234. $value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'] );
  1235. }
  1236. // Normalize to numeric array so nothing unexpected
  1237. // is in the keys.
  1238. $value = array_values( $value );
  1239. return $value;
  1240. }
  1241. if ( 'object' === $args['type'] ) {
  1242. if ( $value instanceof stdClass ) {
  1243. $value = (array) $value;
  1244. }
  1245. if ( $value instanceof JsonSerializable ) {
  1246. $value = $value->jsonSerialize();
  1247. }
  1248. if ( ! is_array( $value ) ) {
  1249. return array();
  1250. }
  1251. foreach ( $value as $property => $v ) {
  1252. if ( isset( $args['properties'][ $property ] ) ) {
  1253. $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['properties'][ $property ] );
  1254. } elseif ( isset( $args['additionalProperties'] ) ) {
  1255. if ( false === $args['additionalProperties'] ) {
  1256. unset( $value[ $property ] );
  1257. } elseif ( is_array( $args['additionalProperties'] ) ) {
  1258. $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['additionalProperties'] );
  1259. }
  1260. }
  1261. }
  1262. return $value;
  1263. }
  1264. if ( 'null' === $args['type'] ) {
  1265. return null;
  1266. }
  1267. if ( 'integer' === $args['type'] ) {
  1268. return (int) $value;
  1269. }
  1270. if ( 'number' === $args['type'] ) {
  1271. return (float) $value;
  1272. }
  1273. if ( 'boolean' === $args['type'] ) {
  1274. return rest_sanitize_boolean( $value );
  1275. }
  1276. if ( isset( $args['format'] ) ) {
  1277. switch ( $args['format'] ) {
  1278. case 'date-time':
  1279. return sanitize_text_field( $value );
  1280. case 'email':
  1281. /*
  1282. * sanitize_email() validates, which would be unexpected.
  1283. */
  1284. return sanitize_text_field( $value );
  1285. case 'uri':
  1286. return esc_url_raw( $value );
  1287. case 'ip':
  1288. return sanitize_text_field( $value );
  1289. }
  1290. }
  1291. if ( 'string' === $args['type'] ) {
  1292. return strval( $value );
  1293. }
  1294. return $value;
  1295. }
  1296. /**
  1297. * Append result of internal request to REST API for purpose of preloading data to be attached to a page.
  1298. * Expected to be called in the context of `array_reduce`.
  1299. *
  1300. * @since 5.0.0
  1301. *
  1302. * @param array $memo Reduce accumulator.
  1303. * @param string $path REST API path to preload.
  1304. * @return array Modified reduce accumulator.
  1305. */
  1306. function rest_preload_api_request( $memo, $path ) {
  1307. // array_reduce() doesn't support passing an array in PHP 5.2, so we need to make sure we start with one.
  1308. if ( ! is_array( $memo ) ) {
  1309. $memo = array();
  1310. }
  1311. if ( empty( $path ) ) {
  1312. return $memo;
  1313. }
  1314. $method = 'GET';
  1315. if ( is_array( $path ) && 2 === count( $path ) ) {
  1316. $method = end( $path );
  1317. $path = reset( $path );
  1318. if ( ! in_array( $method, array( 'GET', 'OPTIONS' ), true ) ) {
  1319. $method = 'GET';
  1320. }
  1321. }
  1322. $path_parts = parse_url( $path );
  1323. if ( false === $path_parts ) {
  1324. return $memo;
  1325. }
  1326. $request = new WP_REST_Request( $method, $path_parts['path'] );
  1327. if ( ! empty( $path_parts['query'] ) ) {
  1328. parse_str( $path_parts['query'], $query_params );
  1329. $request->set_query_params( $query_params );
  1330. }
  1331. $response = rest_do_request( $request );
  1332. if ( 200 === $response->status ) {
  1333. $server = rest_get_server();
  1334. $data = (array) $response->get_data();
  1335. $links = $server::get_compact_response_links( $response );
  1336. if ( ! empty( $links ) ) {
  1337. $data['_links'] = $links;
  1338. }
  1339. if ( 'OPTIONS' === $method ) {
  1340. $response = rest_send_allow_header( $response, $server, $request );
  1341. $memo[ $method ][ $path ] = array(
  1342. 'body' => $data,
  1343. 'headers' => $response->headers,
  1344. );
  1345. } else {
  1346. $memo[ $path ] = array(
  1347. 'body' => $data,
  1348. 'headers' => $response->headers,
  1349. );
  1350. }
  1351. }
  1352. return $memo;
  1353. }