rest-api.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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' );
  484. }
  485. return $value;
  486. }
  487. /**
  488. * Handles OPTIONS requests for the server.
  489. *
  490. * This is handled outside of the server code, as it doesn't obey normal route
  491. * mapping.
  492. *
  493. * @since 4.4.0
  494. *
  495. * @param mixed $response Current response, either response or `null` to indicate pass-through.
  496. * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
  497. * @param WP_REST_Request $request The request that was used to make current response.
  498. * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
  499. */
  500. function rest_handle_options_request( $response, $handler, $request ) {
  501. if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
  502. return $response;
  503. }
  504. $response = new WP_REST_Response();
  505. $data = array();
  506. foreach ( $handler->get_routes() as $route => $endpoints ) {
  507. $match = preg_match( '@^' . $route . '$@i', $request->get_route() );
  508. if ( ! $match ) {
  509. continue;
  510. }
  511. $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
  512. $response->set_matched_route( $route );
  513. break;
  514. }
  515. $response->set_data( $data );
  516. return $response;
  517. }
  518. /**
  519. * Sends the "Allow" header to state all methods that can be sent to the current route.
  520. *
  521. * @since 4.4.0
  522. *
  523. * @param WP_REST_Response $response Current response being served.
  524. * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
  525. * @param WP_REST_Request $request The request that was used to make current response.
  526. * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
  527. */
  528. function rest_send_allow_header( $response, $server, $request ) {
  529. $matched_route = $response->get_matched_route();
  530. if ( ! $matched_route ) {
  531. return $response;
  532. }
  533. $routes = $server->get_routes();
  534. $allowed_methods = array();
  535. // Get the allowed methods across the routes.
  536. foreach ( $routes[ $matched_route ] as $_handler ) {
  537. foreach ( $_handler['methods'] as $handler_method => $value ) {
  538. if ( ! empty( $_handler['permission_callback'] ) ) {
  539. $permission = call_user_func( $_handler['permission_callback'], $request );
  540. $allowed_methods[ $handler_method ] = true === $permission;
  541. } else {
  542. $allowed_methods[ $handler_method ] = true;
  543. }
  544. }
  545. }
  546. // Strip out all the methods that are not allowed (false values).
  547. $allowed_methods = array_filter( $allowed_methods );
  548. if ( $allowed_methods ) {
  549. $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
  550. }
  551. return $response;
  552. }
  553. /**
  554. * Filter the API response to include only a white-listed set of response object fields.
  555. *
  556. * @since 4.8.0
  557. *
  558. * @param WP_REST_Response $response Current response being served.
  559. * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
  560. * @param WP_REST_Request $request The request that was used to make current response.
  561. *
  562. * @return WP_REST_Response Response to be served, trimmed down to contain a subset of fields.
  563. */
  564. function rest_filter_response_fields( $response, $server, $request ) {
  565. if ( ! isset( $request['_fields'] ) || $response->is_error() ) {
  566. return $response;
  567. }
  568. $data = $response->get_data();
  569. $fields = is_array( $request['_fields'] ) ? $request['_fields'] : preg_split( '/[\s,]+/', $request['_fields'] );
  570. if ( 0 === count( $fields ) ) {
  571. return $response;
  572. }
  573. // Trim off outside whitespace from the comma delimited list.
  574. $fields = array_map( 'trim', $fields );
  575. $fields_as_keyed = array_combine( $fields, array_fill( 0, count( $fields ), true ) );
  576. if ( wp_is_numeric_array( $data ) ) {
  577. $new_data = array();
  578. foreach ( $data as $item ) {
  579. $new_data[] = array_intersect_key( $item, $fields_as_keyed );
  580. }
  581. } else {
  582. $new_data = array_intersect_key( $data, $fields_as_keyed );
  583. }
  584. $response->set_data( $new_data );
  585. return $response;
  586. }
  587. /**
  588. * Adds the REST API URL to the WP RSD endpoint.
  589. *
  590. * @since 4.4.0
  591. *
  592. * @see get_rest_url()
  593. */
  594. function rest_output_rsd() {
  595. $api_root = get_rest_url();
  596. if ( empty( $api_root ) ) {
  597. return;
  598. }
  599. ?>
  600. <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
  601. <?php
  602. }
  603. /**
  604. * Outputs the REST API link tag into page header.
  605. *
  606. * @since 4.4.0
  607. *
  608. * @see get_rest_url()
  609. */
  610. function rest_output_link_wp_head() {
  611. $api_root = get_rest_url();
  612. if ( empty( $api_root ) ) {
  613. return;
  614. }
  615. echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
  616. }
  617. /**
  618. * Sends a Link header for the REST API.
  619. *
  620. * @since 4.4.0
  621. */
  622. function rest_output_link_header() {
  623. if ( headers_sent() ) {
  624. return;
  625. }
  626. $api_root = get_rest_url();
  627. if ( empty( $api_root ) ) {
  628. return;
  629. }
  630. header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
  631. }
  632. /**
  633. * Checks for errors when using cookie-based authentication.
  634. *
  635. * WordPress' built-in cookie authentication is always active
  636. * for logged in users. However, the API has to check nonces
  637. * for each request to ensure users are not vulnerable to CSRF.
  638. *
  639. * @since 4.4.0
  640. *
  641. * @global mixed $wp_rest_auth_cookie
  642. *
  643. * @param WP_Error|mixed $result Error from another authentication handler,
  644. * null if we should handle it, or another value
  645. * if not.
  646. * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
  647. */
  648. function rest_cookie_check_errors( $result ) {
  649. if ( ! empty( $result ) ) {
  650. return $result;
  651. }
  652. global $wp_rest_auth_cookie;
  653. /*
  654. * Is cookie authentication being used? (If we get an auth
  655. * error, but we're still logged in, another authentication
  656. * must have been used).
  657. */
  658. if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
  659. return $result;
  660. }
  661. // Determine if there is a nonce.
  662. $nonce = null;
  663. if ( isset( $_REQUEST['_wpnonce'] ) ) {
  664. $nonce = $_REQUEST['_wpnonce'];
  665. } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
  666. $nonce = $_SERVER['HTTP_X_WP_NONCE'];
  667. }
  668. if ( null === $nonce ) {
  669. // No nonce at all, so act as if it's an unauthenticated request.
  670. wp_set_current_user( 0 );
  671. return true;
  672. }
  673. // Check the nonce.
  674. $result = wp_verify_nonce( $nonce, 'wp_rest' );
  675. if ( ! $result ) {
  676. return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
  677. }
  678. // Send a refreshed nonce in header.
  679. rest_get_server()->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) );
  680. return true;
  681. }
  682. /**
  683. * Collects cookie authentication status.
  684. *
  685. * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
  686. *
  687. * @since 4.4.0
  688. *
  689. * @see current_action()
  690. * @global mixed $wp_rest_auth_cookie
  691. */
  692. function rest_cookie_collect_status() {
  693. global $wp_rest_auth_cookie;
  694. $status_type = current_action();
  695. if ( 'auth_cookie_valid' !== $status_type ) {
  696. $wp_rest_auth_cookie = substr( $status_type, 12 );
  697. return;
  698. }
  699. $wp_rest_auth_cookie = true;
  700. }
  701. /**
  702. * Parses an RFC3339 time into a Unix timestamp.
  703. *
  704. * @since 4.4.0
  705. *
  706. * @param string $date RFC3339 timestamp.
  707. * @param bool $force_utc Optional. Whether to force UTC timezone instead of using
  708. * the timestamp's timezone. Default false.
  709. * @return int Unix timestamp.
  710. */
  711. function rest_parse_date( $date, $force_utc = false ) {
  712. if ( $force_utc ) {
  713. $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
  714. }
  715. $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
  716. if ( ! preg_match( $regex, $date, $matches ) ) {
  717. return false;
  718. }
  719. return strtotime( $date );
  720. }
  721. /**
  722. * Parses a date into both its local and UTC equivalent, in MySQL datetime format.
  723. *
  724. * @since 4.4.0
  725. *
  726. * @see rest_parse_date()
  727. *
  728. * @param string $date RFC3339 timestamp.
  729. * @param bool $is_utc Whether the provided date should be interpreted as UTC. Default false.
  730. * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
  731. * null on failure.
  732. */
  733. function rest_get_date_with_gmt( $date, $is_utc = false ) {
  734. // Whether or not the original date actually has a timezone string
  735. // changes the way we need to do timezone conversion. Store this info
  736. // before parsing the date, and use it later.
  737. $has_timezone = preg_match( '#(Z|[+-]\d{2}(:\d{2})?)$#', $date );
  738. $date = rest_parse_date( $date );
  739. if ( empty( $date ) ) {
  740. return null;
  741. }
  742. // At this point $date could either be a local date (if we were passed a
  743. // *local* date without a timezone offset) or a UTC date (otherwise).
  744. // Timezone conversion needs to be handled differently between these two
  745. // cases.
  746. if ( ! $is_utc && ! $has_timezone ) {
  747. $local = date( 'Y-m-d H:i:s', $date );
  748. $utc = get_gmt_from_date( $local );
  749. } else {
  750. $utc = date( 'Y-m-d H:i:s', $date );
  751. $local = get_date_from_gmt( $utc );
  752. }
  753. return array( $local, $utc );
  754. }
  755. /**
  756. * Returns a contextual HTTP error code for authorization failure.
  757. *
  758. * @since 4.7.0
  759. *
  760. * @return integer 401 if the user is not logged in, 403 if the user is logged in.
  761. */
  762. function rest_authorization_required_code() {
  763. return is_user_logged_in() ? 403 : 401;
  764. }
  765. /**
  766. * Validate a request argument based on details registered to the route.
  767. *
  768. * @since 4.7.0
  769. *
  770. * @param mixed $value
  771. * @param WP_REST_Request $request
  772. * @param string $param
  773. * @return WP_Error|boolean
  774. */
  775. function rest_validate_request_arg( $value, $request, $param ) {
  776. $attributes = $request->get_attributes();
  777. if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
  778. return true;
  779. }
  780. $args = $attributes['args'][ $param ];
  781. return rest_validate_value_from_schema( $value, $args, $param );
  782. }
  783. /**
  784. * Sanitize a request argument based on details registered to the route.
  785. *
  786. * @since 4.7.0
  787. *
  788. * @param mixed $value
  789. * @param WP_REST_Request $request
  790. * @param string $param
  791. * @return mixed
  792. */
  793. function rest_sanitize_request_arg( $value, $request, $param ) {
  794. $attributes = $request->get_attributes();
  795. if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
  796. return $value;
  797. }
  798. $args = $attributes['args'][ $param ];
  799. return rest_sanitize_value_from_schema( $value, $args );
  800. }
  801. /**
  802. * Parse a request argument based on details registered to the route.
  803. *
  804. * Runs a validation check and sanitizes the value, primarily to be used via
  805. * the `sanitize_callback` arguments in the endpoint args registration.
  806. *
  807. * @since 4.7.0
  808. *
  809. * @param mixed $value
  810. * @param WP_REST_Request $request
  811. * @param string $param
  812. * @return mixed
  813. */
  814. function rest_parse_request_arg( $value, $request, $param ) {
  815. $is_valid = rest_validate_request_arg( $value, $request, $param );
  816. if ( is_wp_error( $is_valid ) ) {
  817. return $is_valid;
  818. }
  819. $value = rest_sanitize_request_arg( $value, $request, $param );
  820. return $value;
  821. }
  822. /**
  823. * Determines if an IP address is valid.
  824. *
  825. * Handles both IPv4 and IPv6 addresses.
  826. *
  827. * @since 4.7.0
  828. *
  829. * @param string $ip IP address.
  830. * @return string|false The valid IP address, otherwise false.
  831. */
  832. function rest_is_ip_address( $ip ) {
  833. $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]?)$/';
  834. if ( ! preg_match( $ipv4_pattern, $ip ) && ! Requests_IPv6::check_ipv6( $ip ) ) {
  835. return false;
  836. }
  837. return $ip;
  838. }
  839. /**
  840. * Changes a boolean-like value into the proper boolean value.
  841. *
  842. * @since 4.7.0
  843. *
  844. * @param bool|string|int $value The value being evaluated.
  845. * @return boolean Returns the proper associated boolean value.
  846. */
  847. function rest_sanitize_boolean( $value ) {
  848. // String values are translated to `true`; make sure 'false' is false.
  849. if ( is_string( $value ) ) {
  850. $value = strtolower( $value );
  851. if ( in_array( $value, array( 'false', '0' ), true ) ) {
  852. $value = false;
  853. }
  854. }
  855. // Everything else will map nicely to boolean.
  856. return (boolean) $value;
  857. }
  858. /**
  859. * Determines if a given value is boolean-like.
  860. *
  861. * @since 4.7.0
  862. *
  863. * @param bool|string $maybe_bool The value being evaluated.
  864. * @return boolean True if a boolean, otherwise false.
  865. */
  866. function rest_is_boolean( $maybe_bool ) {
  867. if ( is_bool( $maybe_bool ) ) {
  868. return true;
  869. }
  870. if ( is_string( $maybe_bool ) ) {
  871. $maybe_bool = strtolower( $maybe_bool );
  872. $valid_boolean_values = array(
  873. 'false',
  874. 'true',
  875. '0',
  876. '1',
  877. );
  878. return in_array( $maybe_bool, $valid_boolean_values, true );
  879. }
  880. if ( is_int( $maybe_bool ) ) {
  881. return in_array( $maybe_bool, array( 0, 1 ), true );
  882. }
  883. return false;
  884. }
  885. /**
  886. * Retrieves the avatar urls in various sizes based on a given email address.
  887. *
  888. * @since 4.7.0
  889. *
  890. * @see get_avatar_url()
  891. *
  892. * @param string $email Email address.
  893. * @return array $urls Gravatar url for each size.
  894. */
  895. function rest_get_avatar_urls( $email ) {
  896. $avatar_sizes = rest_get_avatar_sizes();
  897. $urls = array();
  898. foreach ( $avatar_sizes as $size ) {
  899. $urls[ $size ] = get_avatar_url( $email, array( 'size' => $size ) );
  900. }
  901. return $urls;
  902. }
  903. /**
  904. * Retrieves the pixel sizes for avatars.
  905. *
  906. * @since 4.7.0
  907. *
  908. * @return array List of pixel sizes for avatars. Default `[ 24, 48, 96 ]`.
  909. */
  910. function rest_get_avatar_sizes() {
  911. /**
  912. * Filters the REST avatar sizes.
  913. *
  914. * Use this filter to adjust the array of sizes returned by the
  915. * `rest_get_avatar_sizes` function.
  916. *
  917. * @since 4.4.0
  918. *
  919. * @param array $sizes An array of int values that are the pixel sizes for avatars.
  920. * Default `[ 24, 48, 96 ]`.
  921. */
  922. return apply_filters( 'rest_avatar_sizes', array( 24, 48, 96 ) );
  923. }
  924. /**
  925. * Validate a value based on a schema.
  926. *
  927. * @since 4.7.0
  928. *
  929. * @param mixed $value The value to validate.
  930. * @param array $args Schema array to use for validation.
  931. * @param string $param The parameter name, used in error messages.
  932. * @return true|WP_Error
  933. */
  934. function rest_validate_value_from_schema( $value, $args, $param = '' ) {
  935. if ( 'array' === $args['type'] ) {
  936. if ( ! is_array( $value ) ) {
  937. $value = preg_split( '/[\s,]+/', $value );
  938. }
  939. if ( ! wp_is_numeric_array( $value ) ) {
  940. /* translators: 1: parameter, 2: type name */
  941. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'array' ) );
  942. }
  943. foreach ( $value as $index => $v ) {
  944. $is_valid = rest_validate_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' );
  945. if ( is_wp_error( $is_valid ) ) {
  946. return $is_valid;
  947. }
  948. }
  949. }
  950. if ( 'object' === $args['type'] ) {
  951. if ( $value instanceof stdClass ) {
  952. $value = (array) $value;
  953. }
  954. if ( ! is_array( $value ) ) {
  955. /* translators: 1: parameter, 2: type name */
  956. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'object' ) );
  957. }
  958. foreach ( $value as $property => $v ) {
  959. if ( isset( $args['properties'][ $property ] ) ) {
  960. $is_valid = rest_validate_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' );
  961. if ( is_wp_error( $is_valid ) ) {
  962. return $is_valid;
  963. }
  964. } elseif ( isset( $args['additionalProperties'] ) && false === $args['additionalProperties'] ) {
  965. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not a valid property of Object.' ), $property ) );
  966. }
  967. }
  968. }
  969. if ( ! empty( $args['enum'] ) ) {
  970. if ( ! in_array( $value, $args['enum'], true ) ) {
  971. /* translators: 1: parameter, 2: list of valid values */
  972. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not one of %2$s.' ), $param, implode( ', ', $args['enum'] ) ) );
  973. }
  974. }
  975. if ( in_array( $args['type'], array( 'integer', 'number' ) ) && ! is_numeric( $value ) ) {
  976. /* translators: 1: parameter, 2: type name */
  977. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, $args['type'] ) );
  978. }
  979. if ( 'integer' === $args['type'] && round( floatval( $value ) ) !== floatval( $value ) ) {
  980. /* translators: 1: parameter, 2: type name */
  981. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'integer' ) );
  982. }
  983. if ( 'boolean' === $args['type'] && ! rest_is_boolean( $value ) ) {
  984. /* translators: 1: parameter, 2: type name */
  985. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $value, 'boolean' ) );
  986. }
  987. if ( 'string' === $args['type'] && ! is_string( $value ) ) {
  988. /* translators: 1: parameter, 2: type name */
  989. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
  990. }
  991. if ( isset( $args['format'] ) ) {
  992. switch ( $args['format'] ) {
  993. case 'date-time' :
  994. if ( ! rest_parse_date( $value ) ) {
  995. return new WP_Error( 'rest_invalid_date', __( 'Invalid date.' ) );
  996. }
  997. break;
  998. case 'email' :
  999. if ( ! is_email( $value ) ) {
  1000. return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ) );
  1001. }
  1002. break;
  1003. case 'ip' :
  1004. if ( ! rest_is_ip_address( $value ) ) {
  1005. /* translators: %s: IP address */
  1006. return new WP_Error( 'rest_invalid_param', sprintf( __( '%s is not a valid IP address.' ), $value ) );
  1007. }
  1008. break;
  1009. }
  1010. }
  1011. if ( in_array( $args['type'], array( 'number', 'integer' ), true ) && ( isset( $args['minimum'] ) || isset( $args['maximum'] ) ) ) {
  1012. if ( isset( $args['minimum'] ) && ! isset( $args['maximum'] ) ) {
  1013. if ( ! empty( $args['exclusiveMinimum'] ) && $value <= $args['minimum'] ) {
  1014. /* translators: 1: parameter, 2: minimum number */
  1015. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d' ), $param, $args['minimum'] ) );
  1016. } elseif ( empty( $args['exclusiveMinimum'] ) && $value < $args['minimum'] ) {
  1017. /* translators: 1: parameter, 2: minimum number */
  1018. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than or equal to %2$d' ), $param, $args['minimum'] ) );
  1019. }
  1020. } elseif ( isset( $args['maximum'] ) && ! isset( $args['minimum'] ) ) {
  1021. if ( ! empty( $args['exclusiveMaximum'] ) && $value >= $args['maximum'] ) {
  1022. /* translators: 1: parameter, 2: maximum number */
  1023. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d' ), $param, $args['maximum'] ) );
  1024. } elseif ( empty( $args['exclusiveMaximum'] ) && $value > $args['maximum'] ) {
  1025. /* translators: 1: parameter, 2: maximum number */
  1026. return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than or equal to %2$d' ), $param, $args['maximum'] ) );
  1027. }
  1028. } elseif ( isset( $args['maximum'] ) && isset( $args['minimum'] ) ) {
  1029. if ( ! empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
  1030. if ( $value >= $args['maximum'] || $value <= $args['minimum'] ) {
  1031. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  1032. 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'] ) );
  1033. }
  1034. } elseif ( empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
  1035. if ( $value >= $args['maximum'] || $value < $args['minimum'] ) {
  1036. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  1037. 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'] ) );
  1038. }
  1039. } elseif ( ! empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
  1040. if ( $value > $args['maximum'] || $value <= $args['minimum'] ) {
  1041. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  1042. 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'] ) );
  1043. }
  1044. } elseif ( empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
  1045. if ( $value > $args['maximum'] || $value < $args['minimum'] ) {
  1046. /* translators: 1: parameter, 2: minimum number, 3: maximum number */
  1047. 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'] ) );
  1048. }
  1049. }
  1050. }
  1051. }
  1052. return true;
  1053. }
  1054. /**
  1055. * Sanitize a value based on a schema.
  1056. *
  1057. * @since 4.7.0
  1058. *
  1059. * @param mixed $value The value to sanitize.
  1060. * @param array $args Schema array to use for sanitization.
  1061. * @return true|WP_Error
  1062. */
  1063. function rest_sanitize_value_from_schema( $value, $args ) {
  1064. if ( 'array' === $args['type'] ) {
  1065. if ( empty( $args['items'] ) ) {
  1066. return (array) $value;
  1067. }
  1068. if ( ! is_array( $value ) ) {
  1069. $value = preg_split( '/[\s,]+/', $value );
  1070. }
  1071. foreach ( $value as $index => $v ) {
  1072. $value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'] );
  1073. }
  1074. // Normalize to numeric array so nothing unexpected
  1075. // is in the keys.
  1076. $value = array_values( $value );
  1077. return $value;
  1078. }
  1079. if ( 'object' === $args['type'] ) {
  1080. if ( $value instanceof stdClass ) {
  1081. $value = (array) $value;
  1082. }
  1083. if ( ! is_array( $value ) ) {
  1084. return array();
  1085. }
  1086. foreach ( $value as $property => $v ) {
  1087. if ( isset( $args['properties'][ $property ] ) ) {
  1088. $value[ $property ] = rest_sanitize_value_from_schema( $v, $args['properties'][ $property ] );
  1089. } elseif ( isset( $args['additionalProperties'] ) && false === $args['additionalProperties'] ) {
  1090. unset( $value[ $property ] );
  1091. }
  1092. }
  1093. return $value;
  1094. }
  1095. if ( 'integer' === $args['type'] ) {
  1096. return (int) $value;
  1097. }
  1098. if ( 'number' === $args['type'] ) {
  1099. return (float) $value;
  1100. }
  1101. if ( 'boolean' === $args['type'] ) {
  1102. return rest_sanitize_boolean( $value );
  1103. }
  1104. if ( isset( $args['format'] ) ) {
  1105. switch ( $args['format'] ) {
  1106. case 'date-time' :
  1107. return sanitize_text_field( $value );
  1108. case 'email' :
  1109. /*
  1110. * sanitize_email() validates, which would be unexpected.
  1111. */
  1112. return sanitize_text_field( $value );
  1113. case 'uri' :
  1114. return esc_url_raw( $value );
  1115. case 'ip' :
  1116. return sanitize_text_field( $value );
  1117. }
  1118. }
  1119. if ( 'string' === $args['type'] ) {
  1120. return strval( $value );
  1121. }
  1122. return $value;
  1123. }