PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/wp-includes/rest-api.php

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