You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1196 lines
35 KiB

  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. * @since 4.4.0
  19. *
  20. * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
  21. *
  22. * @param string $namespace The first URL segment after core prefix. Should be unique to your package/plugin.
  23. * @param string $route The base URL for route you are adding.
  24. * @param array $args Optional. Either an array of options for the endpoint, or an array of arrays for
  25. * multiple methods. Default empty array.
  26. * @param bool $override Optional. If the route already exists, should we override it? True overrides,
  27. * false merges (with newer overriding if duplicate keys exist). Default false.
  28. * @return bool True on success, false on error.
  29. */
  30. function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
  31. /** @var WP_REST_Server $wp_rest_server */
  32. global $wp_rest_server;
  33. if ( empty( $namespace ) ) {
  34. /*
  35. * Non-namespaced routes are not allowed, with the exception of the main
  36. * and namespace indexes. If you really need to register a
  37. * non-namespaced route, call `WP_REST_Server::register_route` directly.
  38. */
  39. _doing_it_wrong( 'register_rest_route', __( 'Routes must be namespaced with plugin or theme name and version.' ), '4.4.0' );
  40. return false;
  41. } else if ( empty( $route ) ) {
  42. _doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
  43. return false;
  44. }
  45. if ( isset( $args['args'] ) ) {
  46. $common_args = $args['args'];
  47. unset( $args['args'] );
  48. } else {
  49. $common_args = array();
  50. }
  51. if ( isset( $args['callback'] ) ) {
  52. // Upgrade a single set to multiple.
  53. $args = array( $args );
  54. }
  55. $defaults = array(
  56. 'methods' => 'GET',
  57. 'callback' => null,
  58. 'args' => array(),
  59. );
  60. foreach ( $args as $key => &$arg_group ) {
  61. if ( ! is_numeric( $key ) ) {
  62. // Route option, skip here.
  63. continue;
  64. }
  65. $arg_group = array_merge( $defaults, $arg_group );
  66. $arg_group['args'] = array_merge( $common_args, $arg_group['args'] );
  67. }
  68. $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
  69. $wp_rest_server->register_route( $namespace, $full_route, $args, $override );
  70. return true;
  71. }
  72. /**
  73. * Registers a new field on an existing WordPress object type.
  74. *
  75. * @since 4.7.0
  76. *
  77. * @global array $wp_rest_additional_fields Holds registered fields, organized
  78. * by object type.
  79. *
  80. * @param string|array $object_type Object(s) the field is being registered
  81. * to, "post"|"term"|"comment" etc.
  82. * @param string $attribute The attribute name.
  83. * @param array $args {
  84. * Optional. An array of arguments used to handle the registered field.
  85. *
  86. * @type string|array|null $get_callback Optional. The callback function used to retrieve the field
  87. * value. Default is 'null', the field will not be returned in
  88. * the response.
  89. * @type string|array|null $update_callback Optional. The callback function used to set and update the
  90. * field value. Default is 'null', the value cannot be set or
  91. * updated.
  92. * @type string|array|null $schema Optional. The callback function used to create the schema for
  93. * this field. Default is 'null', no schema entry will be returned.
  94. * }
  95. */
  96. function register_rest_field( $object_type, $attribute, $args = array() ) {
  97. $defaults = array(
  98. 'get_callback' => null,
  99. 'update_callback' => null,
  100. 'schema' => null,
  101. );
  102. $args = wp_parse_args( $args, $defaults );
  103. global $wp_rest_additional_fields;
  104. $object_types = (array) $object_type;
  105. foreach ( $object_types as $object_type ) {
  106. $wp_rest_additional_fields[ $object_type ][ $attribute ] = $args;
  107. }
  108. }
  109. /**
  110. * Registers rewrite rules for the API.
  111. *
  112. * @since 4.4.0
  113. *
  114. * @see rest_api_register_rewrites()
  115. * @global WP $wp Current WordPress environment instance.
  116. */
  117. function rest_api_init() {
  118. rest_api_register_rewrites();
  119. global $wp;
  120. $wp->add_query_var( 'rest_route' );
  121. }
  122. /**
  123. * Adds REST rewrite rules.
  124. *
  125. * @since 4.4.0
  126. *
  127. * @see add_rewrite_rule()
  128. * @global WP_Rewrite $wp_rewrite
  129. */
  130. function rest_api_register_rewrites() {
  131. global $wp_rewrite;
  132. add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$','index.php?rest_route=/','top' );
  133. add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?','index.php?rest_route=/$matches[1]','top' );
  134. add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/?$','index.php?rest_route=/','top' );
  135. add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/(.*)?','index.php?rest_route=/$matches[1]','top' );
  136. }
  137. /**
  138. * Registers the default REST API filters.
  139. *
  140. * Attached to the {@see 'rest_api_init'} action
  141. * to make testing and disabling these filters easier.
  142. *
  143. * @since 4.4.0
  144. */
  145. function rest_api_default_filters() {
  146. // Deprecated reporting.
  147. add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 );
  148. add_filter( 'deprecated_function_trigger_error', '__return_false' );
  149. add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 );
  150. add_filter( 'deprecated_argument_trigger_error', '__return_false' );
  151. // Default serving.
  152. add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
  153. add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
  154. add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );
  155. }
  156. /**
  157. * Registers default REST API routes.
  158. *
  159. * @since 4.7.0
  160. */
  161. function create_initial_rest_routes() {
  162. foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
  163. $class = ! empty( $post_type->rest_controller_class ) ? $post_type->rest_controller_class : 'WP_REST_Posts_Controller';
  164. if ( ! class_exists( $class ) ) {
  165. continue;
  166. }
  167. $controller = new $class( $post_type->name );
  168. if ( ! is_subclass_of( $controller, 'WP_REST_Controller' ) ) {
  169. continue;
  170. }
  171. $controller->register_routes();
  172. if ( post_type_supports( $post_type->name, 'revisions' ) ) {
  173. $revisions_controller = new WP_REST_Revisions_Controller( $post_type->name );
  174. $revisions_controller->register_routes();
  175. }
  176. }
  177. // Post types.
  178. $controller = new WP_REST_Post_Types_Controller;
  179. $controller->register_routes();
  180. // Post statuses.
  181. $controller = new WP_REST_Post_Statuses_Controller;
  182. $controller->register_routes();
  183. // Taxonomies.
  184. $controller = new WP_REST_Taxonomies_Controller;
  185. $controller->register_routes();
  186. // Terms.
  187. foreach ( get_taxonomies( array( 'show_in_rest' => true ), 'object' ) as $taxonomy ) {
  188. $class = ! empty( $taxonomy->rest_controller_class ) ? $taxonomy->rest_controller_class : 'WP_REST_Terms_Controller';
  189. if ( ! class_exists( $class ) ) {
  190. continue;
  191. }
  192. $controller = new $class( $taxonomy->name );
  193. if ( ! is_subclass_of( $controller, 'WP_REST_Controller' ) ) {
  194. continue;
  195. }
  196. $controller->register_routes();
  197. }
  198. // Users.
  199. $controller = new WP_REST_Users_Controller;
  200. $controller->register_routes();
  201. // Comments.
  202. $controller = new WP_REST_Comments_Controller;
  203. $controller->register_routes();
  204. // Settings.
  205. $controller = new WP_REST_Settings_Controller;
  206. $controller->register_routes();
  207. }
  208. /**
  209. * Loads the REST API.
  210. *
  211. * @since 4.4.0
  212. *
  213. * @global WP $wp Current WordPress environment instance.
  214. * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
  215. */
  216. function rest_api_loaded() {
  217. if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
  218. return;
  219. }
  220. /**
  221. * Whether this is a REST Request.
  222. *
  223. * @since 4.4.0
  224. * @var bool
  225. */
  226. define( 'REST_REQUEST', true );
  227. // Initialize the server.
  228. $server = rest_get_server();
  229. // Fire off the request.
  230. $route = untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] );
  231. if ( empty( $route ) ) {
  232. $route = '/';
  233. }
  234. $server->serve_request( $route );
  235. // We're done.
  236. die();
  237. }
  238. /**
  239. * Retrieves the URL prefix for any API resource.
  240. *
  241. * @since 4.4.0
  242. *
  243. * @return string Prefix.
  244. */
  245. function rest_get_url_prefix() {
  246. /**
  247. * Filters the REST URL prefix.
  248. *
  249. * @since 4.4.0
  250. *
  251. * @param string $prefix URL prefix. Default 'wp-json'.
  252. */
  253. return apply_filters( 'rest_url_prefix', 'wp-json' );
  254. }
  255. /**
  256. * Retrieves the URL to a REST endpoint on a site.
  257. *
  258. * Note: The returned URL is NOT escaped.
  259. *
  260. * @since 4.4.0
  261. *
  262. * @todo Check if this is even necessary
  263. * @global WP_Rewrite $wp_rewrite
  264. *
  265. * @param int $blog_id Optional. Blog ID. Default of null returns URL for current blog.
  266. * @param string $path Optional. REST route. Default '/'.
  267. * @param string $scheme Optional. Sanitization scheme. Default 'rest'.
  268. * @return string Full URL to the endpoint.
  269. */
  270. function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
  271. if ( empty( $path ) ) {
  272. $path = '/';
  273. }
  274. if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
  275. global $wp_rewrite;
  276. if ( $wp_rewrite->using_index_permalinks() ) {
  277. $url = get_home_url( $blog_id, $wp_rewrite->index . '/' . rest_get_url_prefix(), $scheme );
  278. } else {
  279. $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
  280. }
  281. $url .= '/' . ltrim( $path, '/' );
  282. } else {
  283. $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
  284. $path = '/' . ltrim( $path, '/' );
  285. $url = add_query_arg( 'rest_route', $path, $url );
  286. }
  287. if ( is_ssl() ) {
  288. // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
  289. if ( $_SERVER['SERVER_NAME'] === parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) ) {
  290. $url = set_url_scheme( $url, 'https' );
  291. }
  292. }
  293. /**
  294. * Filters the REST URL.
  295. *
  296. * Use this filter to adjust the url returned by the get_rest_url() function.
  297. *
  298. * @since 4.4.0
  299. *
  300. * @param string $url REST URL.
  301. * @param string $path REST route.
  302. * @param int $blog_id Blog ID.
  303. * @param string $scheme Sanitization scheme.
  304. */
  305. return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
  306. }
  307. /**
  308. * Retrieves the URL to a REST endpoint.
  309. *
  310. * Note: The returned URL is NOT escaped.
  311. *
  312. * @since 4.4.0
  313. *
  314. * @param string $path Optional. REST route. Default empty.
  315. * @param string $scheme Optional. Sanitization scheme. Default 'json'.
  316. * @return string Full URL to the endpoint.
  317. */
  318. function rest_url( $path = '', $scheme = 'json' ) {
  319. return get_rest_url( null, $path, $scheme );
  320. }
  321. /**
  322. * Do a REST request.
  323. *
  324. * Used primarily to route internal requests through WP_REST_Server.
  325. *
  326. * @since 4.4.0
  327. *
  328. * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
  329. *
  330. * @param WP_REST_Request|string $request Request.
  331. * @return WP_REST_Response REST response.
  332. */
  333. function rest_do_request( $request ) {
  334. $request = rest_ensure_request( $request );
  335. return rest_get_server()->dispatch( $request );
  336. }
  337. /**
  338. * Retrieves the current REST server instance.
  339. *
  340. * Instantiates a new instance if none exists already.
  341. *
  342. * @since 4.5.0
  343. *
  344. * @global WP_REST_Server $wp_rest_server REST server instance.
  345. *
  346. * @return WP_REST_Server REST server instance.
  347. */
  348. function rest_get_server() {
  349. /* @var WP_REST_Server $wp_rest_server */
  350. global $wp_rest_server;
  351. if ( empty( $wp_rest_server ) ) {
  352. /**
  353. * Filters the REST Server Class.
  354. *
  355. * This filter allows you to adjust the server class used by the API, using a
  356. * different class to handle requests.
  357. *
  358. * @since 4.4.0
  359. *
  360. * @param string $class_name The name of the server class. Default 'WP_REST_Server'.
  361. */
  362. $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
  363. $wp_rest_server = new $wp_rest_server_class;
  364. /**
  365. * Fires when preparing to serve an API request.
  366. *
  367. * Endpoint objects should be created and register their hooks on this action rather
  368. * than another action to ensure they're only loaded when needed.
  369. *
  370. * @since 4.4.0
  371. *
  372. * @param WP_REST_Server $wp_rest_server Server object.
  373. */
  374. do_action( 'rest_api_init', $wp_rest_server );
  375. }
  376. return $wp_rest_server;
  377. }
  378. /**
  379. * Ensures request arguments are a request object (for consistency).
  380. *
  381. * @since 4.4.0
  382. *
  383. * @param array|WP_REST_Request $request Request to check.
  384. * @return WP_REST_Request REST request instance.
  385. */
  386. function rest_ensure_request( $request ) {
  387. if ( $request instanceof WP_REST_Request ) {
  388. return $request;
  389. }
  390. return new WP_REST_Request( 'GET', '', $request );
  391. }
  392. /**
  393. * Ensures a REST response is a response object (for consistency).
  394. *
  395. * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
  396. * without needing to double-check the object. Will also allow WP_Error to indicate error
  397. * responses, so users should immediately check for this value.
  398. *
  399. * @since 4.4.0
  400. *
  401. * @param WP_Error|WP_HTTP_Response|mixed $response Response to check.
  402. * @return WP_REST_Response|mixed If response generated an error, WP_Error, if response
  403. * is already an instance, WP_HTTP_Response, otherwise
  404. * returns a new WP_REST_Response instance.
  405. */
  406. function rest_ensure_response( $response ) {
  407. if ( is_wp_error( $response ) ) {
  408. return $response;
  409. }
  410. if ( $response instanceof WP_HTTP_Response ) {
  411. return $response;
  412. }
  413. return new WP_REST_Response( $response );
  414. }
  415. /**
  416. * Handles _deprecated_function() errors.
  417. *
  418. * @since 4.4.0
  419. *
  420. * @param string $function The function that was called.
  421. * @param string $replacement The function that should have been called.
  422. * @param string $version Version.
  423. */
  424. function rest_handle_deprecated_function( $function, $replacement, $version ) {
  425. if ( ! empty( $replacement ) ) {
  426. /* translators: 1: function name, 2: WordPress version number, 3: new function name */
  427. $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
  428. } else {
  429. /* translators: 1: function name, 2: WordPress version number */
  430. $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
  431. }
  432. header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
  433. }
  434. /**
  435. * Handles _deprecated_argument() errors.
  436. *
  437. * @since 4.4.0
  438. *
  439. * @param string $function The function that was called.
  440. * @param string $message A message regarding the change.
  441. * @param string $version Version.
  442. */
  443. function rest_handle_deprecated_argument( $function, $message, $version ) {
  444. if ( ! empty( $message ) ) {
  445. /* translators: 1: function name, 2: WordPress version number, 3: error message */
  446. $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $message );
  447. } else {
  448. /* translators: 1: function name, 2: WordPress version number */
  449. $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
  450. }
  451. header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
  452. }
  453. /**
  454. * Sends Cross-Origin Resource Sharing headers with API requests.
  455. *
  456. * @since 4.4.0
  457. *
  458. * @param mixed $value Response data.
  459. * @return mixed Response data.
  460. */
  461. function rest_send_cors_headers( $value ) {
  462. $origin = get_http_origin();
  463. if ( $origin ) {
  464. header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
  465. header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
  466. header( 'Access-Control-Allow-Credentials: true' );
  467. header( 'Vary: Origin' );
  468. }
  469. return $value;
  470. }
  471. /**
  472. * Handles OPTIONS requests for the server.
  473. *
  474. * This is handled outside of the server code, as it doesn't obey normal route
  475. * mapping.
  476. *
  477. * @since 4.4.0
  478. *
  479. * @param mixed $response Current response, either response or `null` to indicate pass-through.
  480. * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
  481. * @param WP_REST_Request $request The request that was used to make current response.
  482. * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
  483. */
  484. function rest_handle_options_request( $response, $handler, $request ) {
  485. if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
  486. return $response;
  487. }
  488. $response = new WP_REST_Response();
  489. $data = array();
  490. foreach ( $handler->get_routes() as $route => $endpoints ) {
  491. $match = preg_match( '@^' . $route . '$@i', $request->get_route() );
  492. if ( ! $match ) {
  493. continue;
  494. }
  495. $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
  496. $response->set_matched_route( $route );
  497. break;
  498. }
  499. $response->set_data( $data );
  500. return $response;
  501. }
  502. /**
  503. * Sends the "Allow" header to state all methods that can be sent to the current route.
  504. *
  505. * @since 4.4.0
  506. *
  507. * @param WP_REST_Response $response Current response being served.
  508. * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
  509. * @param WP_REST_Request $request The request that was used to make current response.
  510. * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
  511. */
  512. function rest_send_allow_header( $response, $server, $request ) {
  513. $matched_route = $response->get_matched_route();
  514. if ( ! $matched_route ) {
  515. return $response;
  516. }
  517. $routes = $server->get_routes();
  518. $allowed_methods = array();
  519. // Get the allowed methods across the routes.
  520. foreach ( $routes[ $matched_route ] as $_handler ) {
  521. foreach ( $_handler['methods'] as $handler_method => $value ) {
  522. if ( ! empty( $_handler['permission_callback'] ) ) {
  523. $permission = call_user_func( $_handler['permission_callback'], $request );
  524. $allowed_methods[ $handler_method ] = true === $permission;
  525. } else {
  526. $allowed_methods[ $handler_method ] = true;
  527. }
  528. }
  529. }
  530. // Strip out all the methods that are not allowed (false values).
  531. $allowed_methods = array_filter( $allowed_methods );
  532. if ( $allowed_methods ) {
  533. $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
  534. }
  535. return $response;
  536. }
  537. /**
  538. * Adds the REST API URL to the WP RSD endpoint.
  539. *
  540. * @since 4.4.0
  541. *
  542. * @see get_rest_url()
  543. */
  544. function rest_output_rsd() {
  545. $api_root = get_rest_url();
  546. if ( empty( $api_root ) ) {
  547. return;
  548. }
  549. ?>
  550. <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
  551. <?php
  552. }
  553. /**
  554. * Outputs the REST API link tag into page header.
  555. *
  556. * @since 4.4.0
  557. *
  558. * @see get_rest_url()
  559. */
  560. function rest_output_link_wp_head() {
  561. $api_root = get_rest_url();
  562. if ( empty( $api_root ) ) {
  563. return;
  564. }
  565. echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
  566. }
  567. /**
  568. * Sends a Link header for the REST API.
  569. *
  570. * @since 4.4.0
  571. */
  572. function rest_output_link_header() {
  573. if ( headers_sent() ) {
  574. return;
  575. }
  576. $api_root = get_rest_url();
  577. if ( empty( $api_root ) ) {
  578. return;
  579. }
  580. header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
  581. }
  582. /**
  583. * Checks for errors when using cookie-based authentication.
  584. *
  585. * WordPress' built-in cookie authentication is always active
  586. * for logged in users. However, the API has to check nonces
  587. * for each request to ensure users are not vulnerable to CSRF.
  588. *
  589. * @since 4.4.0
  590. *
  591. * @global mixed $wp_rest_auth_cookie
  592. * @global WP_REST_Server $wp_rest_server REST server instance.
  593. *
  594. * @param WP_Error|mixed $result Error from another authentication handler,
  595. * null if we should handle it, or another value
  596. * if not.
  597. * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
  598. */
  599. function rest_cookie_check_errors( $result ) {
  600. if ( ! empty( $result ) ) {
  601. return $result;
  602. }
  603. global $wp_rest_auth_cookie, $wp_rest_server;
  604. /*
  605. * Is cookie authentication being used? (If we get an auth
  606. * error, but we're still logged in, another authentication
  607. * must have been used).
  608. */
  609. if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
  610. return $result;
  611. }
  612. // Determine if there is a nonce.
  613. $nonce = null;
  614. if ( isset( $_REQUEST['_wpnonce'] ) ) {
  615. $nonce = $_REQUEST['_wpnonce'];
  616. } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
  617. $nonce = $_SERVER['HTTP_X_WP_NONCE'];
  618. }
  619. if ( null === $nonce ) {
  620. // No nonce at all, so act as if it's an unauthenticated request.
  621. wp_set_current_user( 0 );
  622. return true;
  623. }
  624. // Check the nonce.
  625. $result = wp_verify_nonce( $nonce, 'wp_rest' );
  626. if ( ! $result ) {
  627. return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
  628. }
  629. // Send a refreshed nonce in header.
  630. $wp_rest_server->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) );
  631. return true;
  632. }
  633. /**
  634. * Collects cookie authentication status.
  635. *
  636. * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
  637. *
  638. * @since 4.4.0
  639. *
  640. * @see current_action()
  641. * @global mixed $wp_rest_auth_cookie
  642. */
  643. function rest_cookie_collect_status() {
  644. global $wp_rest_auth_cookie;
  645. $status_type = current_action();
  646. if ( 'auth_cookie_valid' !== $status_type ) {
  647. $wp_rest_auth_cookie = substr( $status_type, 12 );
  648. return;
  649. }
  650. $wp_rest_auth_cookie = true;
  651. }
  652. /**
  653. * Parses an RFC3339 time into a Unix timestamp.
  654. *
  655. * @since 4.4.0
  656. *
  657. * @param string $date RFC3339 timestamp.
  658. * @param bool $force_utc Optional. Whether to force UTC timezone instead of using
  659. * the timestamp's timezone. Default false.
  660. * @return int Unix timestamp.
  661. */
  662. function rest_parse_date( $date, $force_utc = false ) {
  663. if ( $force_utc ) {
  664. $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
  665. }
  666. $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
  667. if ( ! preg_match( $regex, $date, $matches ) ) {
  668. return false;
  669. }
  670. return strtotime( $date );
  671. }
  672. /**
  673. * Parses a date into both its local and UTC equivalent, in MySQL datetime format.
  674. *
  675. * @since 4.4.0
  676. *
  677. * @see rest_parse_date()
  678. *
  679. * @param string $date RFC3339 timestamp.
  680. * @param bool $is_utc Whether the provided date should be interpreted as UTC. Default false.
  681. * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
  682. * null on failure.
  683. */
  684. function rest_get_date_with_gmt( $date, $is_utc = false ) {
  685. // Whether or not the original date actually has a timezone string
  686. // changes the way we need to do timezone conversion. Store this info
  687. // before parsing the date, and use it later.
  688. $has_timezone = preg_match( '#(Z|[+-]\d{2}(:\d{2})?)$#', $date );
  689. $date = rest_parse_date( $date );
  690. if ( empty( $date ) ) {
  691. return null;
  692. }
  693. // At this point $date could either be a local date (if we were passed a
  694. // *local* date without a timezone offset) or a UTC date (otherwise).
  695. // Timezone conversion needs to be handled differently between these two
  696. // cases.
  697. if ( ! $is_utc && ! $has_timezone ) {
  698. $local = date( 'Y-m-d H:i:s', $date );
  699. $utc = get_gmt_from_date( $local );
  700. } else {
  701. $utc = date( 'Y-m-d H:i:s', $date );
  702. $local = get_date_from_gmt( $utc );
  703. }
  704. return array( $local, $utc );
  705. }
  706. /**
  707. * Returns a contextual HTTP error code for authorization failure.
  708. *
  709. * @since 4.7.0
  710. *
  711. * @return integer 401 if the user is not logged in, 403 if the user is logged in.
  712. */
  713. function rest_authorization_required_code() {
  714. return is_user_logged_in() ? 403 : 401;
  715. }
  716. /**
  717. * Validate a request argument based on details registered to the route.
  718. *
  719. * @since 4.7.0
  720. *
  721. * @param mixed $value
  722. * @param WP_REST_Request $request
  723. * @param string $param
  724. * @return WP_Error|boolean
  725. */
  726. function rest_validate_request_arg( $value, $request, $param ) {
  727. $attributes = $request->get_attributes();
  728. if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
  729. return true;
  730. }
  731. $args = $attributes['args'][ $param ];
  732. return rest_validate_value_from_schema( $value, $args, $param );
  733. }
  734. /**
  735. * Sanitize a request argument based on details registered to the route.
  736. *
  737. * @since 4.7.0
  738. *
  739. * @param mixed $value
  740. * @param WP_REST_Request $request
  741. * @param string $param
  742. * @return mixed
  743. */
  744. function rest_sanitize_request_arg( $value, $request, $param ) {
  745. $attributes = $request->get_attributes();
  746. if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
  747. return $value;
  748. }
  749. $args = $attributes['args'][ $param ];
  750. return rest_sanitize_value_from_schema( $value, $args );
  751. }
  752. /**
  753. * Parse a request argument based on details registered to the route.
  754. *
  755. * Runs a validation check and sanitizes the value, primarily to be used via
  756. * the `sanitize_callback` arguments in the endpoint args registration.
  757. *
  758. * @since 4.7.0
  759. *
  760. * @param mixed $value
  761. * @param WP_REST_Request $request
  762. * @param string $param
  763. * @return mixed
  764. */
  765. function rest_parse_request_arg( $value, $request, $param ) {
  766. $is_valid = rest_validate_request_arg( $value, $request, $param );
  767. if ( is_wp_error( $is_valid ) ) {
  768. return $is_valid;
  769. }
  770. $value = rest_sanitize_request_arg( $value, $request, $param );
  771. return $value;
  772. }
  773. /**
  774. * Determines if an IP address is valid.
  775. *
  776. * Handles both IPv4 and IPv6 addresses.
  777. *
  778. * @since 4.7.0
  779. *
  780. * @param string $ip IP address.
  781. * @return string|false The valid IP address, otherwise false.
  782. */
  783. function rest_is_ip_address( $ip ) {
  784. $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]?)$/';
  785. if ( ! preg_match( $ipv4_pattern, $ip ) && ! Requests_IPv6::check_ipv6( $ip ) ) {
  786. return false;
  787. }
  788. return $ip;
  789. }
  790. /**
  791. * Changes a boolean-like value into the proper boolean value.
  792. *
  793. * @since 4.7.0
  794. *
  795. * @param bool|string|int $value The value being evaluated.
  796. * @return boolean Returns the proper associated boolean value.
  797. */
  798. function rest_sanitize_boolean( $value ) {
  799. // String values are translated to `true`; make sure 'false' is false.
  800. if ( is_string( $value ) ) {
  801. $value = strtolower( $value );
  802. if ( in_array( $value, array( 'false', '0' ), true ) ) {
  803. $value = false;
  804. }
  805. }
  806. // Everything else will map nicely to boolean.
  807. return (boolean) $value;
  808. }
  809. /**
  810. * Determines if a given value is boolean-like.
  811. *
  812. * @since 4.7.0
  813. *
  814. * @param bool|string $maybe_bool The value being evaluated.
  815. * @return boolean True if a boolean, otherwise false.
  816. */
  817. function rest_is_boolean( $maybe_bool ) {
  818. if ( is_bool( $maybe_bool ) ) {
  819. return true;
  820. }
  821. if ( is_string( $maybe_bool ) ) {
  822. $maybe_bool = strtolower( $maybe_bool );
  823. $valid_boolean_values = array(
  824. 'false',
  825. 'true',
  826. '0',
  827. '1',
  828. );
  829. return in_array( $maybe_bool, $valid_boolean_values, true );
  830. }
  831. if ( is_int( $maybe_bool ) ) {
  832. return in_array( $maybe_bool, array( 0, 1 ), true );
  833. }
  834. return false;
  835. }
  836. /**
  837. * Retrieves the avatar urls in various sizes based on a given email address.
  838. *
  839. * @since 4.7.0
  840. *
  841. * @see get_avatar_url()
  842. *
  843. * @param string $email Email address.
  844. * @return array $urls Gravatar url for each size.
  845. */
  846. function rest_get_avatar_urls( $email ) {
  847. $avatar_sizes = rest_get_avatar_sizes();
  848. $urls = array();
  849. foreach ( $avatar_sizes as $size ) {
  850. $urls[ $size ] = get_avatar_url( $email, array( 'size' => $size ) );
  851. }
  852. return $urls;
  853. }
  854. /**
  855. * Retrieves the pixel sizes for avatars.
  856. *
  857. * @since 4.7.0
  858. *
  859. * @return array List of pixel sizes for avatars. Default `[ 24, 48, 96 ]`.
  860. */
  861. function rest_get_avatar_sizes() {
  862. /**
  863. * Filter the REST avatar sizes.
  864. *
  865. * Use this filter to adjust the array of sizes returned by the
  866. * `rest_get_avatar_sizes` function.
  867. *
  868. * @since 4.4.0
  869. *
  870. * @param array $sizes An array of int values that are the pixel sizes for avatars.
  871. * Default `[ 24, 48, 96 ]`.
  872. */
  873. return apply_filters( 'rest_avatar_sizes', array( 24, 48, 96 ) );
  874. }
  875. /**
  876. * Validate a value based on a schema.
  877. *
  878. * @param mixed $value The value to validate.
  879. * @param array $args Schema array to use for validation.
  880. * @param string $param The parameter name, used in error messages.
  881. * @return true|WP_Error
  882. */
  883. function rest_validate_value_from_schema( $value, $args, $param = '' ) {
  884. if ( 'array' === $args['type'] ) {
  885. if ( ! is_array( $value ) ) {
  886. $value = preg_split( '/[\s,]+/', $value );
  887. }
  888. if ( ! wp_is_numeric_array( $value ) ) {
  889. /* translators: 1: parameter, 2: type name */
  890. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'array' ) );
  891. }
  892. foreach ( $value as $index => $v ) {
  893. $is_valid = rest_validate_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' );
  894. if ( is_wp_error( $is_valid ) ) {
  895. return $is_valid;
  896. }
  897. }
  898. }
  899. if ( ! empty( $args['enum'] ) ) {
  900. if ( ! in_array( $value, $args['enum'], true ) ) {
  901. /* translators: 1: parameter, 2: list of valid values */
  902. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not one of %2$s.' ), $param, implode( ', ', $args['enum'] ) ) );
  903. }
  904. }
  905. if ( in_array( $args['type'], array( 'integer', 'number' ) ) && ! is_numeric( $value ) ) {
  906. /* translators: 1: parameter, 2: type name */
  907. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, $args['type'] ) );
  908. }
  909. if ( 'integer' === $args['type'] && round( floatval( $value ) ) !== floatval( $value ) ) {
  910. /* translators: 1: parameter, 2: type name */
  911. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'integer' ) );
  912. }
  913. if ( 'boolean' === $args['type'] && ! rest_is_boolean( $value ) ) {
  914. /* translators: 1: parameter, 2: type name */
  915. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $value, 'boolean' ) );
  916. }
  917. if ( 'string' === $args['type'] && ! is_string( $value ) ) {
  918. /* translators: 1: parameter, 2: type name */
  919. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
  920. }
  921. if ( isset( $args['format'] ) ) {
  922. switch ( $args['format'] ) {
  923. case 'date-time' :
  924. if ( ! rest_parse_date( $value ) ) {
  925. return new WP_Error( 'rest_invalid_date', __( 'Invalid date.' ) );
  926. }
  927. break;
  928. case 'email' :
  929. // is_email() checks for 3 characters (a@b), but
  930. // wp_handle_comment_submission() requires 6 characters (a@b.co)
  931. //
  932. // https://core.trac.wordpress.org/ticket/38506
  933. if ( ! is_email( $value ) || strlen( $value ) < 6 ) {
  934. return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ) );
  935. }
  936. break;
  937. case 'ip' :
  938. if ( ! rest_is_ip_address( $value ) ) {
  939. /* translators: %s: IP address */
  940. return new WP_Error( 'rest_invalid_param', sprintf( __( '%s is not a valid IP address.' ), $value ) );
  941. }
  942. break;
  943. }
  944. }
  945. if ( in_array( $args['type'], array( 'number', 'integer' ), true ) && ( isset( $args['minimum'] ) || isset( $args['maximum'] ) ) ) {
  946. if ( isset( $args['minimum'] ) && ! isset( $args['maximum'] ) ) {
  947. if ( ! empty( $args['exclusiveMinimum'] ) && $value <= $args['minimum'] ) {
  948. /* translators: 1: parameter, 2: minimum number */
  949. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d (exclusive)' ), $param, $args['minimum'] ) );
  950. } elseif ( empty( $args['exclusiveMinimum'] ) && $value < $args['minimum'] ) {
  951. /* translators: 1: parameter, 2: minimum number */
  952. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d (inclusive)' ), $param, $args['minimum'] ) );
  953. }
  954. } elseif ( isset( $args['maximum'] ) && ! isset( $args['minimum'] ) ) {
  955. if ( ! empty( $args['exclusiveMaximum'] ) && $value >= $args['maximum'] ) {
  956. /* translators: 1: parameter, 2: maximum number */
  957. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d (exclusive)' ), $param, $args['maximum'] ) );
  958. } elseif ( empty( $args['exclusiveMaximum'] ) && $value > $args['maximum'] ) {
  959. /* translators: 1: parameter, 2: maximum number */
  960. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d (inclusive)' ), $param, $args['maximum'] ) );
  961. }
  962. } elseif ( isset( $args['maximum'] ) && isset( $args['minimum'] ) ) {
  963. if ( ! empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
  964. if ( $value >= $args['maximum'] || $value <= $args['minimum'] ) {
  965. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  966. 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'] ) );
  967. }
  968. } elseif ( empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
  969. if ( $value >= $args['maximum'] || $value < $args['minimum'] ) {
  970. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  971. 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'] ) );
  972. }
  973. } elseif ( ! empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
  974. if ( $value > $args['maximum'] || $value <= $args['minimum'] ) {
  975. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  976. 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'] ) );
  977. }
  978. } elseif ( empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
  979. if ( $value > $args['maximum'] || $value < $args['minimum'] ) {
  980. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  981. 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'] ) );
  982. }
  983. }
  984. }
  985. }
  986. return true;
  987. }
  988. /**
  989. * Sanitize a value based on a schema.
  990. *
  991. * @param mixed $value The value to sanitize.
  992. * @param array $args Schema array to use for sanitization.
  993. * @return true|WP_Error
  994. */
  995. function rest_sanitize_value_from_schema( $value, $args ) {
  996. if ( 'array' === $args['type'] ) {
  997. if ( empty( $args['items'] ) ) {
  998. return (array) $value;
  999. }
  1000. if ( ! is_array( $value ) ) {
  1001. $value = preg_split( '/[\s,]+/', $value );
  1002. }
  1003. foreach ( $value as $index => $v ) {
  1004. $value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'] );
  1005. }
  1006. // Normalize to numeric array so nothing unexpected
  1007. // is in the keys.
  1008. $value = array_values( $value );
  1009. return $value;
  1010. }
  1011. if ( 'integer' === $args['type'] ) {
  1012. return (int) $value;
  1013. }
  1014. if ( 'number' === $args['type'] ) {
  1015. return (float) $value;
  1016. }
  1017. if ( 'boolean' === $args['type'] ) {
  1018. return rest_sanitize_boolean( $value );
  1019. }
  1020. if ( isset( $args['format'] ) ) {
  1021. switch ( $args['format'] ) {
  1022. case 'date-time' :
  1023. return sanitize_text_field( $value );
  1024. case 'email' :
  1025. /*
  1026. * sanitize_email() validates, which would be unexpected.
  1027. */
  1028. return sanitize_text_field( $value );
  1029. case 'uri' :
  1030. return esc_url_raw( $value );
  1031. case 'ip' :
  1032. return sanitize_text_field( $value );
  1033. }
  1034. }
  1035. if ( 'string' === $args['type'] ) {
  1036. return strval( $value );
  1037. }
  1038. return $value;
  1039. }