Няма описание

class-wp-rest-request.php 25KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. <?php
  2. /**
  3. * REST API: WP_REST_Request class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.4.0
  8. */
  9. /**
  10. * Core class used to implement a REST request object.
  11. *
  12. * Contains data from the request, to be passed to the callback.
  13. *
  14. * Note: This implements ArrayAccess, and acts as an array of parameters when
  15. * used in that manner. It does not use ArrayObject (as we cannot rely on SPL),
  16. * so be aware it may have non-array behaviour in some cases.
  17. *
  18. * Note: When using features provided by ArrayAccess, be aware that WordPress deliberately
  19. * does not distinguish between arguments of the same name for different request methods.
  20. * For instance, in a request with `GET id=1` and `POST id=2`, `$request['id']` will equal
  21. * 2 (`POST`) not 1 (`GET`). For more precision between request methods, use
  22. * WP_REST_Request::get_body_params(), WP_REST_Request::get_url_params(), etc.
  23. *
  24. * @since 4.4.0
  25. *
  26. * @link https://www.php.net/manual/en/class.arrayaccess.php
  27. */
  28. class WP_REST_Request implements ArrayAccess {
  29. /**
  30. * HTTP method.
  31. *
  32. * @since 4.4.0
  33. * @var string
  34. */
  35. protected $method = '';
  36. /**
  37. * Parameters passed to the request.
  38. *
  39. * These typically come from the `$_GET`, `$_POST` and `$_FILES`
  40. * superglobals when being created from the global scope.
  41. *
  42. * @since 4.4.0
  43. * @var array Contains GET, POST and FILES keys mapping to arrays of data.
  44. */
  45. protected $params;
  46. /**
  47. * HTTP headers for the request.
  48. *
  49. * @since 4.4.0
  50. * @var array Map of key to value. Key is always lowercase, as per HTTP specification.
  51. */
  52. protected $headers = array();
  53. /**
  54. * Body data.
  55. *
  56. * @since 4.4.0
  57. * @var string Binary data from the request.
  58. */
  59. protected $body = null;
  60. /**
  61. * Route matched for the request.
  62. *
  63. * @since 4.4.0
  64. * @var string
  65. */
  66. protected $route;
  67. /**
  68. * Attributes (options) for the route that was matched.
  69. *
  70. * This is the options array used when the route was registered, typically
  71. * containing the callback as well as the valid methods for the route.
  72. *
  73. * @since 4.4.0
  74. * @var array Attributes for the request.
  75. */
  76. protected $attributes = array();
  77. /**
  78. * Used to determine if the JSON data has been parsed yet.
  79. *
  80. * Allows lazy-parsing of JSON data where possible.
  81. *
  82. * @since 4.4.0
  83. * @var bool
  84. */
  85. protected $parsed_json = false;
  86. /**
  87. * Used to determine if the body data has been parsed yet.
  88. *
  89. * @since 4.4.0
  90. * @var bool
  91. */
  92. protected $parsed_body = false;
  93. /**
  94. * Constructor.
  95. *
  96. * @since 4.4.0
  97. *
  98. * @param string $method Optional. Request method. Default empty.
  99. * @param string $route Optional. Request route. Default empty.
  100. * @param array $attributes Optional. Request attributes. Default empty array.
  101. */
  102. public function __construct( $method = '', $route = '', $attributes = array() ) {
  103. $this->params = array(
  104. 'URL' => array(),
  105. 'GET' => array(),
  106. 'POST' => array(),
  107. 'FILES' => array(),
  108. // See parse_json_params.
  109. 'JSON' => null,
  110. 'defaults' => array(),
  111. );
  112. $this->set_method( $method );
  113. $this->set_route( $route );
  114. $this->set_attributes( $attributes );
  115. }
  116. /**
  117. * Retrieves the HTTP method for the request.
  118. *
  119. * @since 4.4.0
  120. *
  121. * @return string HTTP method.
  122. */
  123. public function get_method() {
  124. return $this->method;
  125. }
  126. /**
  127. * Sets HTTP method for the request.
  128. *
  129. * @since 4.4.0
  130. *
  131. * @param string $method HTTP method.
  132. */
  133. public function set_method( $method ) {
  134. $this->method = strtoupper( $method );
  135. }
  136. /**
  137. * Retrieves all headers from the request.
  138. *
  139. * @since 4.4.0
  140. *
  141. * @return array Map of key to value. Key is always lowercase, as per HTTP specification.
  142. */
  143. public function get_headers() {
  144. return $this->headers;
  145. }
  146. /**
  147. * Canonicalizes the header name.
  148. *
  149. * Ensures that header names are always treated the same regardless of
  150. * source. Header names are always case insensitive.
  151. *
  152. * Note that we treat `-` (dashes) and `_` (underscores) as the same
  153. * character, as per header parsing rules in both Apache and nginx.
  154. *
  155. * @link https://stackoverflow.com/q/18185366
  156. * @link https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#missing-disappearing-http-headers
  157. * @link https://nginx.org/en/docs/http/ngx_http_core_module.html#underscores_in_headers
  158. *
  159. * @since 4.4.0
  160. *
  161. * @param string $key Header name.
  162. * @return string Canonicalized name.
  163. */
  164. public static function canonicalize_header_name( $key ) {
  165. $key = strtolower( $key );
  166. $key = str_replace( '-', '_', $key );
  167. return $key;
  168. }
  169. /**
  170. * Retrieves the given header from the request.
  171. *
  172. * If the header has multiple values, they will be concatenated with a comma
  173. * as per the HTTP specification. Be aware that some non-compliant headers
  174. * (notably cookie headers) cannot be joined this way.
  175. *
  176. * @since 4.4.0
  177. *
  178. * @param string $key Header name, will be canonicalized to lowercase.
  179. * @return string|null String value if set, null otherwise.
  180. */
  181. public function get_header( $key ) {
  182. $key = $this->canonicalize_header_name( $key );
  183. if ( ! isset( $this->headers[ $key ] ) ) {
  184. return null;
  185. }
  186. return implode( ',', $this->headers[ $key ] );
  187. }
  188. /**
  189. * Retrieves header values from the request.
  190. *
  191. * @since 4.4.0
  192. *
  193. * @param string $key Header name, will be canonicalized to lowercase.
  194. * @return array|null List of string values if set, null otherwise.
  195. */
  196. public function get_header_as_array( $key ) {
  197. $key = $this->canonicalize_header_name( $key );
  198. if ( ! isset( $this->headers[ $key ] ) ) {
  199. return null;
  200. }
  201. return $this->headers[ $key ];
  202. }
  203. /**
  204. * Sets the header on request.
  205. *
  206. * @since 4.4.0
  207. *
  208. * @param string $key Header name.
  209. * @param string $value Header value, or list of values.
  210. */
  211. public function set_header( $key, $value ) {
  212. $key = $this->canonicalize_header_name( $key );
  213. $value = (array) $value;
  214. $this->headers[ $key ] = $value;
  215. }
  216. /**
  217. * Appends a header value for the given header.
  218. *
  219. * @since 4.4.0
  220. *
  221. * @param string $key Header name.
  222. * @param string $value Header value, or list of values.
  223. */
  224. public function add_header( $key, $value ) {
  225. $key = $this->canonicalize_header_name( $key );
  226. $value = (array) $value;
  227. if ( ! isset( $this->headers[ $key ] ) ) {
  228. $this->headers[ $key ] = array();
  229. }
  230. $this->headers[ $key ] = array_merge( $this->headers[ $key ], $value );
  231. }
  232. /**
  233. * Removes all values for a header.
  234. *
  235. * @since 4.4.0
  236. *
  237. * @param string $key Header name.
  238. */
  239. public function remove_header( $key ) {
  240. $key = $this->canonicalize_header_name( $key );
  241. unset( $this->headers[ $key ] );
  242. }
  243. /**
  244. * Sets headers on the request.
  245. *
  246. * @since 4.4.0
  247. *
  248. * @param array $headers Map of header name to value.
  249. * @param bool $override If true, replace the request's headers. Otherwise, merge with existing.
  250. */
  251. public function set_headers( $headers, $override = true ) {
  252. if ( true === $override ) {
  253. $this->headers = array();
  254. }
  255. foreach ( $headers as $key => $value ) {
  256. $this->set_header( $key, $value );
  257. }
  258. }
  259. /**
  260. * Retrieves the content-type of the request.
  261. *
  262. * @since 4.4.0
  263. *
  264. * @return array|null Map containing 'value' and 'parameters' keys
  265. * or null when no valid content-type header was
  266. * available.
  267. */
  268. public function get_content_type() {
  269. $value = $this->get_header( 'content-type' );
  270. if ( empty( $value ) ) {
  271. return null;
  272. }
  273. $parameters = '';
  274. if ( strpos( $value, ';' ) ) {
  275. list( $value, $parameters ) = explode( ';', $value, 2 );
  276. }
  277. $value = strtolower( $value );
  278. if ( false === strpos( $value, '/' ) ) {
  279. return null;
  280. }
  281. // Parse type and subtype out.
  282. list( $type, $subtype ) = explode( '/', $value, 2 );
  283. $data = compact( 'value', 'type', 'subtype', 'parameters' );
  284. $data = array_map( 'trim', $data );
  285. return $data;
  286. }
  287. /**
  288. * Checks if the request has specified a JSON content-type.
  289. *
  290. * @since 5.6.0
  291. *
  292. * @return bool True if the content-type header is JSON.
  293. */
  294. public function is_json_content_type() {
  295. $content_type = $this->get_content_type();
  296. return isset( $content_type['value'] ) && wp_is_json_media_type( $content_type['value'] );
  297. }
  298. /**
  299. * Retrieves the parameter priority order.
  300. *
  301. * Used when checking parameters in WP_REST_Request::get_param().
  302. *
  303. * @since 4.4.0
  304. *
  305. * @return string[] Array of types to check, in order of priority.
  306. */
  307. protected function get_parameter_order() {
  308. $order = array();
  309. if ( $this->is_json_content_type() ) {
  310. $order[] = 'JSON';
  311. }
  312. $this->parse_json_params();
  313. // Ensure we parse the body data.
  314. $body = $this->get_body();
  315. if ( 'POST' !== $this->method && ! empty( $body ) ) {
  316. $this->parse_body_params();
  317. }
  318. $accepts_body_data = array( 'POST', 'PUT', 'PATCH', 'DELETE' );
  319. if ( in_array( $this->method, $accepts_body_data, true ) ) {
  320. $order[] = 'POST';
  321. }
  322. $order[] = 'GET';
  323. $order[] = 'URL';
  324. $order[] = 'defaults';
  325. /**
  326. * Filters the parameter priority order for a REST API request.
  327. *
  328. * The order affects which parameters are checked when using WP_REST_Request::get_param()
  329. * and family. This acts similarly to PHP's `request_order` setting.
  330. *
  331. * @since 4.4.0
  332. *
  333. * @param string[] $order Array of types to check, in order of priority.
  334. * @param WP_REST_Request $this The request object.
  335. */
  336. return apply_filters( 'rest_request_parameter_order', $order, $this );
  337. }
  338. /**
  339. * Retrieves a parameter from the request.
  340. *
  341. * @since 4.4.0
  342. *
  343. * @param string $key Parameter name.
  344. * @return mixed|null Value if set, null otherwise.
  345. */
  346. public function get_param( $key ) {
  347. $order = $this->get_parameter_order();
  348. foreach ( $order as $type ) {
  349. // Determine if we have the parameter for this type.
  350. if ( isset( $this->params[ $type ][ $key ] ) ) {
  351. return $this->params[ $type ][ $key ];
  352. }
  353. }
  354. return null;
  355. }
  356. /**
  357. * Checks if a parameter exists in the request.
  358. *
  359. * This allows distinguishing between an omitted parameter,
  360. * and a parameter specifically set to null.
  361. *
  362. * @since 5.3.0
  363. *
  364. * @param string $key Parameter name.
  365. * @return bool True if a param exists for the given key.
  366. */
  367. public function has_param( $key ) {
  368. $order = $this->get_parameter_order();
  369. foreach ( $order as $type ) {
  370. if ( is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
  371. return true;
  372. }
  373. }
  374. return false;
  375. }
  376. /**
  377. * Sets a parameter on the request.
  378. *
  379. * If the given parameter key exists in any parameter type an update will take place,
  380. * otherwise a new param will be created in the first parameter type (respecting
  381. * get_parameter_order()).
  382. *
  383. * @since 4.4.0
  384. *
  385. * @param string $key Parameter name.
  386. * @param mixed $value Parameter value.
  387. */
  388. public function set_param( $key, $value ) {
  389. $order = $this->get_parameter_order();
  390. $found_key = false;
  391. foreach ( $order as $type ) {
  392. if ( 'defaults' !== $type && is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
  393. $this->params[ $type ][ $key ] = $value;
  394. $found_key = true;
  395. }
  396. }
  397. if ( ! $found_key ) {
  398. $this->params[ $order[0] ][ $key ] = $value;
  399. }
  400. }
  401. /**
  402. * Retrieves merged parameters from the request.
  403. *
  404. * The equivalent of get_param(), but returns all parameters for the request.
  405. * Handles merging all the available values into a single array.
  406. *
  407. * @since 4.4.0
  408. *
  409. * @return array Map of key to value.
  410. */
  411. public function get_params() {
  412. $order = $this->get_parameter_order();
  413. $order = array_reverse( $order, true );
  414. $params = array();
  415. foreach ( $order as $type ) {
  416. // array_merge() / the "+" operator will mess up
  417. // numeric keys, so instead do a manual foreach.
  418. foreach ( (array) $this->params[ $type ] as $key => $value ) {
  419. $params[ $key ] = $value;
  420. }
  421. }
  422. return $params;
  423. }
  424. /**
  425. * Retrieves parameters from the route itself.
  426. *
  427. * These are parsed from the URL using the regex.
  428. *
  429. * @since 4.4.0
  430. *
  431. * @return array Parameter map of key to value.
  432. */
  433. public function get_url_params() {
  434. return $this->params['URL'];
  435. }
  436. /**
  437. * Sets parameters from the route.
  438. *
  439. * Typically, this is set after parsing the URL.
  440. *
  441. * @since 4.4.0
  442. *
  443. * @param array $params Parameter map of key to value.
  444. */
  445. public function set_url_params( $params ) {
  446. $this->params['URL'] = $params;
  447. }
  448. /**
  449. * Retrieves parameters from the query string.
  450. *
  451. * These are the parameters you'd typically find in `$_GET`.
  452. *
  453. * @since 4.4.0
  454. *
  455. * @return array Parameter map of key to value
  456. */
  457. public function get_query_params() {
  458. return $this->params['GET'];
  459. }
  460. /**
  461. * Sets parameters from the query string.
  462. *
  463. * Typically, this is set from `$_GET`.
  464. *
  465. * @since 4.4.0
  466. *
  467. * @param array $params Parameter map of key to value.
  468. */
  469. public function set_query_params( $params ) {
  470. $this->params['GET'] = $params;
  471. }
  472. /**
  473. * Retrieves parameters from the body.
  474. *
  475. * These are the parameters you'd typically find in `$_POST`.
  476. *
  477. * @since 4.4.0
  478. *
  479. * @return array Parameter map of key to value.
  480. */
  481. public function get_body_params() {
  482. return $this->params['POST'];
  483. }
  484. /**
  485. * Sets parameters from the body.
  486. *
  487. * Typically, this is set from `$_POST`.
  488. *
  489. * @since 4.4.0
  490. *
  491. * @param array $params Parameter map of key to value.
  492. */
  493. public function set_body_params( $params ) {
  494. $this->params['POST'] = $params;
  495. }
  496. /**
  497. * Retrieves multipart file parameters from the body.
  498. *
  499. * These are the parameters you'd typically find in `$_FILES`.
  500. *
  501. * @since 4.4.0
  502. *
  503. * @return array Parameter map of key to value
  504. */
  505. public function get_file_params() {
  506. return $this->params['FILES'];
  507. }
  508. /**
  509. * Sets multipart file parameters from the body.
  510. *
  511. * Typically, this is set from `$_FILES`.
  512. *
  513. * @since 4.4.0
  514. *
  515. * @param array $params Parameter map of key to value.
  516. */
  517. public function set_file_params( $params ) {
  518. $this->params['FILES'] = $params;
  519. }
  520. /**
  521. * Retrieves the default parameters.
  522. *
  523. * These are the parameters set in the route registration.
  524. *
  525. * @since 4.4.0
  526. *
  527. * @return array Parameter map of key to value
  528. */
  529. public function get_default_params() {
  530. return $this->params['defaults'];
  531. }
  532. /**
  533. * Sets default parameters.
  534. *
  535. * These are the parameters set in the route registration.
  536. *
  537. * @since 4.4.0
  538. *
  539. * @param array $params Parameter map of key to value.
  540. */
  541. public function set_default_params( $params ) {
  542. $this->params['defaults'] = $params;
  543. }
  544. /**
  545. * Retrieves the request body content.
  546. *
  547. * @since 4.4.0
  548. *
  549. * @return string Binary data from the request body.
  550. */
  551. public function get_body() {
  552. return $this->body;
  553. }
  554. /**
  555. * Sets body content.
  556. *
  557. * @since 4.4.0
  558. *
  559. * @param string $data Binary data from the request body.
  560. */
  561. public function set_body( $data ) {
  562. $this->body = $data;
  563. // Enable lazy parsing.
  564. $this->parsed_json = false;
  565. $this->parsed_body = false;
  566. $this->params['JSON'] = null;
  567. }
  568. /**
  569. * Retrieves the parameters from a JSON-formatted body.
  570. *
  571. * @since 4.4.0
  572. *
  573. * @return array Parameter map of key to value.
  574. */
  575. public function get_json_params() {
  576. // Ensure the parameters have been parsed out.
  577. $this->parse_json_params();
  578. return $this->params['JSON'];
  579. }
  580. /**
  581. * Parses the JSON parameters.
  582. *
  583. * Avoids parsing the JSON data until we need to access it.
  584. *
  585. * @since 4.4.0
  586. * @since 4.7.0 Returns error instance if value cannot be decoded.
  587. * @return true|WP_Error True if the JSON data was passed or no JSON data was provided, WP_Error if invalid JSON was passed.
  588. */
  589. protected function parse_json_params() {
  590. if ( $this->parsed_json ) {
  591. return true;
  592. }
  593. $this->parsed_json = true;
  594. // Check that we actually got JSON.
  595. if ( ! $this->is_json_content_type() ) {
  596. return true;
  597. }
  598. $body = $this->get_body();
  599. if ( empty( $body ) ) {
  600. return true;
  601. }
  602. $params = json_decode( $body, true );
  603. /*
  604. * Check for a parsing error.
  605. */
  606. if ( null === $params && JSON_ERROR_NONE !== json_last_error() ) {
  607. // Ensure subsequent calls receive error instance.
  608. $this->parsed_json = false;
  609. $error_data = array(
  610. 'status' => WP_Http::BAD_REQUEST,
  611. 'json_error_code' => json_last_error(),
  612. 'json_error_message' => json_last_error_msg(),
  613. );
  614. return new WP_Error( 'rest_invalid_json', __( 'Invalid JSON body passed.' ), $error_data );
  615. }
  616. $this->params['JSON'] = $params;
  617. return true;
  618. }
  619. /**
  620. * Parses the request body parameters.
  621. *
  622. * Parses out URL-encoded bodies for request methods that aren't supported
  623. * natively by PHP. In PHP 5.x, only POST has these parsed automatically.
  624. *
  625. * @since 4.4.0
  626. */
  627. protected function parse_body_params() {
  628. if ( $this->parsed_body ) {
  629. return;
  630. }
  631. $this->parsed_body = true;
  632. /*
  633. * Check that we got URL-encoded. Treat a missing content-type as
  634. * URL-encoded for maximum compatibility.
  635. */
  636. $content_type = $this->get_content_type();
  637. if ( ! empty( $content_type ) && 'application/x-www-form-urlencoded' !== $content_type['value'] ) {
  638. return;
  639. }
  640. parse_str( $this->get_body(), $params );
  641. /*
  642. * Add to the POST parameters stored internally. If a user has already
  643. * set these manually (via `set_body_params`), don't override them.
  644. */
  645. $this->params['POST'] = array_merge( $params, $this->params['POST'] );
  646. }
  647. /**
  648. * Retrieves the route that matched the request.
  649. *
  650. * @since 4.4.0
  651. *
  652. * @return string Route matching regex.
  653. */
  654. public function get_route() {
  655. return $this->route;
  656. }
  657. /**
  658. * Sets the route that matched the request.
  659. *
  660. * @since 4.4.0
  661. *
  662. * @param string $route Route matching regex.
  663. */
  664. public function set_route( $route ) {
  665. $this->route = $route;
  666. }
  667. /**
  668. * Retrieves the attributes for the request.
  669. *
  670. * These are the options for the route that was matched.
  671. *
  672. * @since 4.4.0
  673. *
  674. * @return array Attributes for the request.
  675. */
  676. public function get_attributes() {
  677. return $this->attributes;
  678. }
  679. /**
  680. * Sets the attributes for the request.
  681. *
  682. * @since 4.4.0
  683. *
  684. * @param array $attributes Attributes for the request.
  685. */
  686. public function set_attributes( $attributes ) {
  687. $this->attributes = $attributes;
  688. }
  689. /**
  690. * Sanitizes (where possible) the params on the request.
  691. *
  692. * This is primarily based off the sanitize_callback param on each registered
  693. * argument.
  694. *
  695. * @since 4.4.0
  696. *
  697. * @return true|WP_Error True if parameters were sanitized, WP_Error if an error occurred during sanitization.
  698. */
  699. public function sanitize_params() {
  700. $attributes = $this->get_attributes();
  701. // No arguments set, skip sanitizing.
  702. if ( empty( $attributes['args'] ) ) {
  703. return true;
  704. }
  705. $order = $this->get_parameter_order();
  706. $invalid_params = array();
  707. $invalid_details = array();
  708. foreach ( $order as $type ) {
  709. if ( empty( $this->params[ $type ] ) ) {
  710. continue;
  711. }
  712. foreach ( $this->params[ $type ] as $key => $value ) {
  713. if ( ! isset( $attributes['args'][ $key ] ) ) {
  714. continue;
  715. }
  716. $param_args = $attributes['args'][ $key ];
  717. // If the arg has a type but no sanitize_callback attribute, default to rest_parse_request_arg.
  718. if ( ! array_key_exists( 'sanitize_callback', $param_args ) && ! empty( $param_args['type'] ) ) {
  719. $param_args['sanitize_callback'] = 'rest_parse_request_arg';
  720. }
  721. // If there's still no sanitize_callback, nothing to do here.
  722. if ( empty( $param_args['sanitize_callback'] ) ) {
  723. continue;
  724. }
  725. /** @var mixed|WP_Error $sanitized_value */
  726. $sanitized_value = call_user_func( $param_args['sanitize_callback'], $value, $this, $key );
  727. if ( is_wp_error( $sanitized_value ) ) {
  728. $invalid_params[ $key ] = implode( ' ', $sanitized_value->get_error_messages() );
  729. $invalid_details[ $key ] = rest_convert_error_to_response( $sanitized_value )->get_data();
  730. } else {
  731. $this->params[ $type ][ $key ] = $sanitized_value;
  732. }
  733. }
  734. }
  735. if ( $invalid_params ) {
  736. return new WP_Error(
  737. 'rest_invalid_param',
  738. /* translators: %s: List of invalid parameters. */
  739. sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
  740. array(
  741. 'status' => 400,
  742. 'params' => $invalid_params,
  743. 'details' => $invalid_details,
  744. )
  745. );
  746. }
  747. return true;
  748. }
  749. /**
  750. * Checks whether this request is valid according to its attributes.
  751. *
  752. * @since 4.4.0
  753. *
  754. * @return true|WP_Error True if there are no parameters to validate or if all pass validation,
  755. * WP_Error if required parameters are missing.
  756. */
  757. public function has_valid_params() {
  758. // If JSON data was passed, check for errors.
  759. $json_error = $this->parse_json_params();
  760. if ( is_wp_error( $json_error ) ) {
  761. return $json_error;
  762. }
  763. $attributes = $this->get_attributes();
  764. $required = array();
  765. $args = empty( $attributes['args'] ) ? array() : $attributes['args'];
  766. foreach ( $args as $key => $arg ) {
  767. $param = $this->get_param( $key );
  768. if ( isset( $arg['required'] ) && true === $arg['required'] && null === $param ) {
  769. $required[] = $key;
  770. }
  771. }
  772. if ( ! empty( $required ) ) {
  773. return new WP_Error(
  774. 'rest_missing_callback_param',
  775. /* translators: %s: List of required parameters. */
  776. sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ),
  777. array(
  778. 'status' => 400,
  779. 'params' => $required,
  780. )
  781. );
  782. }
  783. /*
  784. * Check the validation callbacks for each registered arg.
  785. *
  786. * This is done after required checking as required checking is cheaper.
  787. */
  788. $invalid_params = array();
  789. $invalid_details = array();
  790. foreach ( $args as $key => $arg ) {
  791. $param = $this->get_param( $key );
  792. if ( null !== $param && ! empty( $arg['validate_callback'] ) ) {
  793. /** @var bool|\WP_Error $valid_check */
  794. $valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );
  795. if ( false === $valid_check ) {
  796. $invalid_params[ $key ] = __( 'Invalid parameter.' );
  797. }
  798. if ( is_wp_error( $valid_check ) ) {
  799. $invalid_params[ $key ] = implode( ' ', $valid_check->get_error_messages() );
  800. $invalid_details[ $key ] = rest_convert_error_to_response( $valid_check )->get_data();
  801. }
  802. }
  803. }
  804. if ( $invalid_params ) {
  805. return new WP_Error(
  806. 'rest_invalid_param',
  807. /* translators: %s: List of invalid parameters. */
  808. sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
  809. array(
  810. 'status' => 400,
  811. 'params' => $invalid_params,
  812. 'details' => $invalid_details,
  813. )
  814. );
  815. }
  816. if ( isset( $attributes['validate_callback'] ) ) {
  817. $valid_check = call_user_func( $attributes['validate_callback'], $this );
  818. if ( is_wp_error( $valid_check ) ) {
  819. return $valid_check;
  820. }
  821. if ( false === $valid_check ) {
  822. // A WP_Error instance is preferred, but false is supported for parity with the per-arg validate_callback.
  823. return new WP_Error( 'rest_invalid_params', __( 'Invalid parameters.' ), array( 'status' => 400 ) );
  824. }
  825. }
  826. return true;
  827. }
  828. /**
  829. * Checks if a parameter is set.
  830. *
  831. * @since 4.4.0
  832. *
  833. * @param string $offset Parameter name.
  834. * @return bool Whether the parameter is set.
  835. */
  836. public function offsetExists( $offset ) {
  837. $order = $this->get_parameter_order();
  838. foreach ( $order as $type ) {
  839. if ( isset( $this->params[ $type ][ $offset ] ) ) {
  840. return true;
  841. }
  842. }
  843. return false;
  844. }
  845. /**
  846. * Retrieves a parameter from the request.
  847. *
  848. * @since 4.4.0
  849. *
  850. * @param string $offset Parameter name.
  851. * @return mixed|null Value if set, null otherwise.
  852. */
  853. public function offsetGet( $offset ) {
  854. return $this->get_param( $offset );
  855. }
  856. /**
  857. * Sets a parameter on the request.
  858. *
  859. * @since 4.4.0
  860. *
  861. * @param string $offset Parameter name.
  862. * @param mixed $value Parameter value.
  863. */
  864. public function offsetSet( $offset, $value ) {
  865. $this->set_param( $offset, $value );
  866. }
  867. /**
  868. * Removes a parameter from the request.
  869. *
  870. * @since 4.4.0
  871. *
  872. * @param string $offset Parameter name.
  873. */
  874. public function offsetUnset( $offset ) {
  875. $order = $this->get_parameter_order();
  876. // Remove the offset from every group.
  877. foreach ( $order as $type ) {
  878. unset( $this->params[ $type ][ $offset ] );
  879. }
  880. }
  881. /**
  882. * Retrieves a WP_REST_Request object from a full URL.
  883. *
  884. * @since 4.5.0
  885. *
  886. * @param string $url URL with protocol, domain, path and query args.
  887. * @return WP_REST_Request|false WP_REST_Request object on success, false on failure.
  888. */
  889. public static function from_url( $url ) {
  890. $bits = parse_url( $url );
  891. $query_params = array();
  892. if ( ! empty( $bits['query'] ) ) {
  893. wp_parse_str( $bits['query'], $query_params );
  894. }
  895. $api_root = rest_url();
  896. if ( get_option( 'permalink_structure' ) && 0 === strpos( $url, $api_root ) ) {
  897. // Pretty permalinks on, and URL is under the API root.
  898. $api_url_part = substr( $url, strlen( untrailingslashit( $api_root ) ) );
  899. $route = parse_url( $api_url_part, PHP_URL_PATH );
  900. } elseif ( ! empty( $query_params['rest_route'] ) ) {
  901. // ?rest_route=... set directly.
  902. $route = $query_params['rest_route'];
  903. unset( $query_params['rest_route'] );
  904. }
  905. $request = false;
  906. if ( ! empty( $route ) ) {
  907. $request = new WP_REST_Request( 'GET', $route );
  908. $request->set_query_params( $query_params );
  909. }
  910. /**
  911. * Filters the REST API request generated from a URL.
  912. *
  913. * @since 4.5.0
  914. *
  915. * @param WP_REST_Request|false $request Generated request object, or false if URL
  916. * could not be parsed.
  917. * @param string $url URL the request was generated from.
  918. */
  919. return apply_filters( 'rest_request_from_url', $request, $url );
  920. }
  921. }