rest-api.php 38 KB

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