class-wp-rest-request.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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://secure.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 ( strpos( $value, '/' ) === false ) {
  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. * Retrieves the parameter priority order.
  289. *
  290. * Used when checking parameters in get_param().
  291. *
  292. * @since 4.4.0
  293. *
  294. * @return array List of types to check, in order of priority.
  295. */
  296. protected function get_parameter_order() {
  297. $order = array();
  298. $content_type = $this->get_content_type();
  299. if ( isset( $content_type['value'] ) && 'application/json' === $content_type['value'] ) {
  300. $order[] = 'JSON';
  301. }
  302. $this->parse_json_params();
  303. // Ensure we parse the body data.
  304. $body = $this->get_body();
  305. if ( 'POST' !== $this->method && ! empty( $body ) ) {
  306. $this->parse_body_params();
  307. }
  308. $accepts_body_data = array( 'POST', 'PUT', 'PATCH', 'DELETE' );
  309. if ( in_array( $this->method, $accepts_body_data ) ) {
  310. $order[] = 'POST';
  311. }
  312. $order[] = 'GET';
  313. $order[] = 'URL';
  314. $order[] = 'defaults';
  315. /**
  316. * Filters the parameter order.
  317. *
  318. * The order affects which parameters are checked when using get_param() and family.
  319. * This acts similarly to PHP's `request_order` setting.
  320. *
  321. * @since 4.4.0
  322. *
  323. * @param array $order {
  324. * An array of types to check, in order of priority.
  325. *
  326. * @param string $type The type to check.
  327. * }
  328. * @param WP_REST_Request $this The request object.
  329. */
  330. return apply_filters( 'rest_request_parameter_order', $order, $this );
  331. }
  332. /**
  333. * Retrieves a parameter from the request.
  334. *
  335. * @since 4.4.0
  336. *
  337. * @param string $key Parameter name.
  338. * @return mixed|null Value if set, null otherwise.
  339. */
  340. public function get_param( $key ) {
  341. $order = $this->get_parameter_order();
  342. foreach ( $order as $type ) {
  343. // Determine if we have the parameter for this type.
  344. if ( isset( $this->params[ $type ][ $key ] ) ) {
  345. return $this->params[ $type ][ $key ];
  346. }
  347. }
  348. return null;
  349. }
  350. /**
  351. * Checks if a parameter exists in the request.
  352. *
  353. * This allows distinguishing between an omitted parameter,
  354. * and a parameter specifically set to null.
  355. *
  356. * @since 5.3.0
  357. *
  358. * @param string $key Parameter name.
  359. *
  360. * @return bool True if a param exists for the given key.
  361. */
  362. public function has_param( $key ) {
  363. $order = $this->get_parameter_order();
  364. foreach ( $order as $type ) {
  365. if ( array_key_exists( $key, $this->params[ $type ] ) ) {
  366. return true;
  367. }
  368. }
  369. return false;
  370. }
  371. /**
  372. * Sets a parameter on the request.
  373. *
  374. * @since 4.4.0
  375. *
  376. * @param string $key Parameter name.
  377. * @param mixed $value Parameter value.
  378. */
  379. public function set_param( $key, $value ) {
  380. $order = $this->get_parameter_order();
  381. $this->params[ $order[0] ][ $key ] = $value;
  382. }
  383. /**
  384. * Retrieves merged parameters from the request.
  385. *
  386. * The equivalent of get_param(), but returns all parameters for the request.
  387. * Handles merging all the available values into a single array.
  388. *
  389. * @since 4.4.0
  390. *
  391. * @return array Map of key to value.
  392. */
  393. public function get_params() {
  394. $order = $this->get_parameter_order();
  395. $order = array_reverse( $order, true );
  396. $params = array();
  397. foreach ( $order as $type ) {
  398. // array_merge / the "+" operator will mess up
  399. // numeric keys, so instead do a manual foreach.
  400. foreach ( (array) $this->params[ $type ] as $key => $value ) {
  401. $params[ $key ] = $value;
  402. }
  403. }
  404. return $params;
  405. }
  406. /**
  407. * Retrieves parameters from the route itself.
  408. *
  409. * These are parsed from the URL using the regex.
  410. *
  411. * @since 4.4.0
  412. *
  413. * @return array Parameter map of key to value.
  414. */
  415. public function get_url_params() {
  416. return $this->params['URL'];
  417. }
  418. /**
  419. * Sets parameters from the route.
  420. *
  421. * Typically, this is set after parsing the URL.
  422. *
  423. * @since 4.4.0
  424. *
  425. * @param array $params Parameter map of key to value.
  426. */
  427. public function set_url_params( $params ) {
  428. $this->params['URL'] = $params;
  429. }
  430. /**
  431. * Retrieves parameters from the query string.
  432. *
  433. * These are the parameters you'd typically find in `$_GET`.
  434. *
  435. * @since 4.4.0
  436. *
  437. * @return array Parameter map of key to value
  438. */
  439. public function get_query_params() {
  440. return $this->params['GET'];
  441. }
  442. /**
  443. * Sets parameters from the query string.
  444. *
  445. * Typically, this is set from `$_GET`.
  446. *
  447. * @since 4.4.0
  448. *
  449. * @param array $params Parameter map of key to value.
  450. */
  451. public function set_query_params( $params ) {
  452. $this->params['GET'] = $params;
  453. }
  454. /**
  455. * Retrieves parameters from the body.
  456. *
  457. * These are the parameters you'd typically find in `$_POST`.
  458. *
  459. * @since 4.4.0
  460. *
  461. * @return array Parameter map of key to value.
  462. */
  463. public function get_body_params() {
  464. return $this->params['POST'];
  465. }
  466. /**
  467. * Sets parameters from the body.
  468. *
  469. * Typically, this is set from `$_POST`.
  470. *
  471. * @since 4.4.0
  472. *
  473. * @param array $params Parameter map of key to value.
  474. */
  475. public function set_body_params( $params ) {
  476. $this->params['POST'] = $params;
  477. }
  478. /**
  479. * Retrieves multipart file parameters from the body.
  480. *
  481. * These are the parameters you'd typically find in `$_FILES`.
  482. *
  483. * @since 4.4.0
  484. *
  485. * @return array Parameter map of key to value
  486. */
  487. public function get_file_params() {
  488. return $this->params['FILES'];
  489. }
  490. /**
  491. * Sets multipart file parameters from the body.
  492. *
  493. * Typically, this is set from `$_FILES`.
  494. *
  495. * @since 4.4.0
  496. *
  497. * @param array $params Parameter map of key to value.
  498. */
  499. public function set_file_params( $params ) {
  500. $this->params['FILES'] = $params;
  501. }
  502. /**
  503. * Retrieves the default parameters.
  504. *
  505. * These are the parameters set in the route registration.
  506. *
  507. * @since 4.4.0
  508. *
  509. * @return array Parameter map of key to value
  510. */
  511. public function get_default_params() {
  512. return $this->params['defaults'];
  513. }
  514. /**
  515. * Sets default parameters.
  516. *
  517. * These are the parameters set in the route registration.
  518. *
  519. * @since 4.4.0
  520. *
  521. * @param array $params Parameter map of key to value.
  522. */
  523. public function set_default_params( $params ) {
  524. $this->params['defaults'] = $params;
  525. }
  526. /**
  527. * Retrieves the request body content.
  528. *
  529. * @since 4.4.0
  530. *
  531. * @return string Binary data from the request body.
  532. */
  533. public function get_body() {
  534. return $this->body;
  535. }
  536. /**
  537. * Sets body content.
  538. *
  539. * @since 4.4.0
  540. *
  541. * @param string $data Binary data from the request body.
  542. */
  543. public function set_body( $data ) {
  544. $this->body = $data;
  545. // Enable lazy parsing.
  546. $this->parsed_json = false;
  547. $this->parsed_body = false;
  548. $this->params['JSON'] = null;
  549. }
  550. /**
  551. * Retrieves the parameters from a JSON-formatted body.
  552. *
  553. * @since 4.4.0
  554. *
  555. * @return array Parameter map of key to value.
  556. */
  557. public function get_json_params() {
  558. // Ensure the parameters have been parsed out.
  559. $this->parse_json_params();
  560. return $this->params['JSON'];
  561. }
  562. /**
  563. * Parses the JSON parameters.
  564. *
  565. * Avoids parsing the JSON data until we need to access it.
  566. *
  567. * @since 4.4.0
  568. * @since 4.7.0 Returns error instance if value cannot be decoded.
  569. * @return true|WP_Error True if the JSON data was passed or no JSON data was provided, WP_Error if invalid JSON was passed.
  570. */
  571. protected function parse_json_params() {
  572. if ( $this->parsed_json ) {
  573. return true;
  574. }
  575. $this->parsed_json = true;
  576. // Check that we actually got JSON.
  577. $content_type = $this->get_content_type();
  578. if ( empty( $content_type ) || 'application/json' !== $content_type['value'] ) {
  579. return true;
  580. }
  581. $body = $this->get_body();
  582. if ( empty( $body ) ) {
  583. return true;
  584. }
  585. $params = json_decode( $body, true );
  586. /*
  587. * Check for a parsing error.
  588. */
  589. if ( null === $params && JSON_ERROR_NONE !== json_last_error() ) {
  590. // Ensure subsequent calls receive error instance.
  591. $this->parsed_json = false;
  592. $error_data = array(
  593. 'status' => WP_Http::BAD_REQUEST,
  594. 'json_error_code' => json_last_error(),
  595. 'json_error_message' => json_last_error_msg(),
  596. );
  597. return new WP_Error( 'rest_invalid_json', __( 'Invalid JSON body passed.' ), $error_data );
  598. }
  599. $this->params['JSON'] = $params;
  600. return true;
  601. }
  602. /**
  603. * Parses the request body parameters.
  604. *
  605. * Parses out URL-encoded bodies for request methods that aren't supported
  606. * natively by PHP. In PHP 5.x, only POST has these parsed automatically.
  607. *
  608. * @since 4.4.0
  609. */
  610. protected function parse_body_params() {
  611. if ( $this->parsed_body ) {
  612. return;
  613. }
  614. $this->parsed_body = true;
  615. /*
  616. * Check that we got URL-encoded. Treat a missing content-type as
  617. * URL-encoded for maximum compatibility.
  618. */
  619. $content_type = $this->get_content_type();
  620. if ( ! empty( $content_type ) && 'application/x-www-form-urlencoded' !== $content_type['value'] ) {
  621. return;
  622. }
  623. parse_str( $this->get_body(), $params );
  624. /*
  625. * Add to the POST parameters stored internally. If a user has already
  626. * set these manually (via `set_body_params`), don't override them.
  627. */
  628. $this->params['POST'] = array_merge( $params, $this->params['POST'] );
  629. }
  630. /**
  631. * Retrieves the route that matched the request.
  632. *
  633. * @since 4.4.0
  634. *
  635. * @return string Route matching regex.
  636. */
  637. public function get_route() {
  638. return $this->route;
  639. }
  640. /**
  641. * Sets the route that matched the request.
  642. *
  643. * @since 4.4.0
  644. *
  645. * @param string $route Route matching regex.
  646. */
  647. public function set_route( $route ) {
  648. $this->route = $route;
  649. }
  650. /**
  651. * Retrieves the attributes for the request.
  652. *
  653. * These are the options for the route that was matched.
  654. *
  655. * @since 4.4.0
  656. *
  657. * @return array Attributes for the request.
  658. */
  659. public function get_attributes() {
  660. return $this->attributes;
  661. }
  662. /**
  663. * Sets the attributes for the request.
  664. *
  665. * @since 4.4.0
  666. *
  667. * @param array $attributes Attributes for the request.
  668. */
  669. public function set_attributes( $attributes ) {
  670. $this->attributes = $attributes;
  671. }
  672. /**
  673. * Sanitizes (where possible) the params on the request.
  674. *
  675. * This is primarily based off the sanitize_callback param on each registered
  676. * argument.
  677. *
  678. * @since 4.4.0
  679. *
  680. * @return true|WP_Error True if parameters were sanitized, WP_Error if an error occurred during sanitization.
  681. */
  682. public function sanitize_params() {
  683. $attributes = $this->get_attributes();
  684. // No arguments set, skip sanitizing.
  685. if ( empty( $attributes['args'] ) ) {
  686. return true;
  687. }
  688. $order = $this->get_parameter_order();
  689. $invalid_params = array();
  690. foreach ( $order as $type ) {
  691. if ( empty( $this->params[ $type ] ) ) {
  692. continue;
  693. }
  694. foreach ( $this->params[ $type ] as $key => $value ) {
  695. if ( ! isset( $attributes['args'][ $key ] ) ) {
  696. continue;
  697. }
  698. $param_args = $attributes['args'][ $key ];
  699. // If the arg has a type but no sanitize_callback attribute, default to rest_parse_request_arg.
  700. if ( ! array_key_exists( 'sanitize_callback', $param_args ) && ! empty( $param_args['type'] ) ) {
  701. $param_args['sanitize_callback'] = 'rest_parse_request_arg';
  702. }
  703. // If there's still no sanitize_callback, nothing to do here.
  704. if ( empty( $param_args['sanitize_callback'] ) ) {
  705. continue;
  706. }
  707. $sanitized_value = call_user_func( $param_args['sanitize_callback'], $value, $this, $key );
  708. if ( is_wp_error( $sanitized_value ) ) {
  709. $invalid_params[ $key ] = $sanitized_value->get_error_message();
  710. } else {
  711. $this->params[ $type ][ $key ] = $sanitized_value;
  712. }
  713. }
  714. }
  715. if ( $invalid_params ) {
  716. return new WP_Error(
  717. 'rest_invalid_param',
  718. /* translators: %s: List of invalid parameters. */
  719. sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
  720. array(
  721. 'status' => 400,
  722. 'params' => $invalid_params,
  723. )
  724. );
  725. }
  726. return true;
  727. }
  728. /**
  729. * Checks whether this request is valid according to its attributes.
  730. *
  731. * @since 4.4.0
  732. *
  733. * @return bool|WP_Error True if there are no parameters to validate or if all pass validation,
  734. * WP_Error if required parameters are missing.
  735. */
  736. public function has_valid_params() {
  737. // If JSON data was passed, check for errors.
  738. $json_error = $this->parse_json_params();
  739. if ( is_wp_error( $json_error ) ) {
  740. return $json_error;
  741. }
  742. $attributes = $this->get_attributes();
  743. $required = array();
  744. // No arguments set, skip validation.
  745. if ( empty( $attributes['args'] ) ) {
  746. return true;
  747. }
  748. foreach ( $attributes['args'] as $key => $arg ) {
  749. $param = $this->get_param( $key );
  750. if ( isset( $arg['required'] ) && true === $arg['required'] && null === $param ) {
  751. $required[] = $key;
  752. }
  753. }
  754. if ( ! empty( $required ) ) {
  755. return new WP_Error(
  756. 'rest_missing_callback_param',
  757. /* translators: %s: List of required parameters. */
  758. sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ),
  759. array(
  760. 'status' => 400,
  761. 'params' => $required,
  762. )
  763. );
  764. }
  765. /*
  766. * Check the validation callbacks for each registered arg.
  767. *
  768. * This is done after required checking as required checking is cheaper.
  769. */
  770. $invalid_params = array();
  771. foreach ( $attributes['args'] as $key => $arg ) {
  772. $param = $this->get_param( $key );
  773. if ( null !== $param && ! empty( $arg['validate_callback'] ) ) {
  774. $valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );
  775. if ( false === $valid_check ) {
  776. $invalid_params[ $key ] = __( 'Invalid parameter.' );
  777. }
  778. if ( is_wp_error( $valid_check ) ) {
  779. $invalid_params[ $key ] = $valid_check->get_error_message();
  780. }
  781. }
  782. }
  783. if ( $invalid_params ) {
  784. return new WP_Error(
  785. 'rest_invalid_param',
  786. /* translators: %s: List of invalid parameters. */
  787. sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
  788. array(
  789. 'status' => 400,
  790. 'params' => $invalid_params,
  791. )
  792. );
  793. }
  794. return true;
  795. }
  796. /**
  797. * Checks if a parameter is set.
  798. *
  799. * @since 4.4.0
  800. *
  801. * @param string $offset Parameter name.
  802. * @return bool Whether the parameter is set.
  803. */
  804. public function offsetExists( $offset ) {
  805. $order = $this->get_parameter_order();
  806. foreach ( $order as $type ) {
  807. if ( isset( $this->params[ $type ][ $offset ] ) ) {
  808. return true;
  809. }
  810. }
  811. return false;
  812. }
  813. /**
  814. * Retrieves a parameter from the request.
  815. *
  816. * @since 4.4.0
  817. *
  818. * @param string $offset Parameter name.
  819. * @return mixed|null Value if set, null otherwise.
  820. */
  821. public function offsetGet( $offset ) {
  822. return $this->get_param( $offset );
  823. }
  824. /**
  825. * Sets a parameter on the request.
  826. *
  827. * @since 4.4.0
  828. *
  829. * @param string $offset Parameter name.
  830. * @param mixed $value Parameter value.
  831. */
  832. public function offsetSet( $offset, $value ) {
  833. $this->set_param( $offset, $value );
  834. }
  835. /**
  836. * Removes a parameter from the request.
  837. *
  838. * @since 4.4.0
  839. *
  840. * @param string $offset Parameter name.
  841. */
  842. public function offsetUnset( $offset ) {
  843. $order = $this->get_parameter_order();
  844. // Remove the offset from every group.
  845. foreach ( $order as $type ) {
  846. unset( $this->params[ $type ][ $offset ] );
  847. }
  848. }
  849. /**
  850. * Retrieves a WP_REST_Request object from a full URL.
  851. *
  852. * @since 4.5.0
  853. *
  854. * @param string $url URL with protocol, domain, path and query args.
  855. * @return WP_REST_Request|false WP_REST_Request object on success, false on failure.
  856. */
  857. public static function from_url( $url ) {
  858. $bits = parse_url( $url );
  859. $query_params = array();
  860. if ( ! empty( $bits['query'] ) ) {
  861. wp_parse_str( $bits['query'], $query_params );
  862. }
  863. $api_root = rest_url();
  864. if ( get_option( 'permalink_structure' ) && 0 === strpos( $url, $api_root ) ) {
  865. // Pretty permalinks on, and URL is under the API root.
  866. $api_url_part = substr( $url, strlen( untrailingslashit( $api_root ) ) );
  867. $route = parse_url( $api_url_part, PHP_URL_PATH );
  868. } elseif ( ! empty( $query_params['rest_route'] ) ) {
  869. // ?rest_route=... set directly
  870. $route = $query_params['rest_route'];
  871. unset( $query_params['rest_route'] );
  872. }
  873. $request = false;
  874. if ( ! empty( $route ) ) {
  875. $request = new WP_REST_Request( 'GET', $route );
  876. $request->set_query_params( $query_params );
  877. }
  878. /**
  879. * Filters the request generated from a URL.
  880. *
  881. * @since 4.5.0
  882. *
  883. * @param WP_REST_Request|false $request Generated request object, or false if URL
  884. * could not be parsed.
  885. * @param string $url URL the request was generated from.
  886. */
  887. return apply_filters( 'rest_request_from_url', $request, $url );
  888. }
  889. }