3 * REST API: WP_REST_Request class
11 * Core class used to implement a REST request object.
13 * Contains data from the request, to be passed to the callback.
15 * Note: This implements ArrayAccess, and acts as an array of parameters when
16 * used in that manner. It does not use ArrayObject (as we cannot rely on SPL),
17 * so be aware it may have non-array behaviour in some cases.
23 class WP_REST_Request implements ArrayAccess {
32 protected $method = '';
35 * Parameters passed to the request.
37 * These typically come from the `$_GET`, `$_POST` and `$_FILES`
38 * superglobals when being created from the global scope.
42 * @var array Contains GET, POST and FILES keys mapping to arrays of data.
47 * HTTP headers for the request.
51 * @var array Map of key to value. Key is always lowercase, as per HTTP specification.
53 protected $headers = array();
60 * @var string Binary data from the request.
62 protected $body = null;
65 * Route matched for the request.
74 * Attributes (options) for the route that was matched.
76 * This is the options array used when the route was registered, typically
77 * containing the callback as well as the valid methods for the route.
81 * @var array Attributes for the request.
83 protected $attributes = array();
86 * Used to determine if the JSON data has been parsed yet.
88 * Allows lazy-parsing of JSON data where possible.
94 protected $parsed_json = false;
97 * Used to determine if the body data has been parsed yet.
103 protected $parsed_body = false;
111 * @param string $method Optional. Request method. Default empty.
112 * @param string $route Optional. Request route. Default empty.
113 * @param array $attributes Optional. Request attributes. Default empty array.
115 public function __construct( $method = '', $route = '', $attributes = array() ) {
116 $this->params = array(
122 // See parse_json_params.
125 'defaults' => array(),
128 $this->set_method( $method );
129 $this->set_route( $route );
130 $this->set_attributes( $attributes );
134 * Retrieves the HTTP method for the request.
139 * @return string HTTP method.
141 public function get_method() {
142 return $this->method;
146 * Sets HTTP method for the request.
151 * @param string $method HTTP method.
153 public function set_method( $method ) {
154 $this->method = strtoupper( $method );
158 * Retrieves all headers from the request.
163 * @return array Map of key to value. Key is always lowercase, as per HTTP specification.
165 public function get_headers() {
166 return $this->headers;
170 * Canonicalizes the header name.
172 * Ensures that header names are always treated the same regardless of
173 * source. Header names are always case insensitive.
175 * Note that we treat `-` (dashes) and `_` (underscores) as the same
176 * character, as per header parsing rules in both Apache and nginx.
178 * @link http://stackoverflow.com/q/18185366
179 * @link http://wiki.nginx.org/Pitfalls#Missing_.28disappearing.29_HTTP_headers
180 * @link http://nginx.org/en/docs/http/ngx_http_core_module.html#underscores_in_headers
186 * @param string $key Header name.
187 * @return string Canonicalized name.
189 public static function canonicalize_header_name( $key ) {
190 $key = strtolower( $key );
191 $key = str_replace( '-', '_', $key );
197 * Retrieves the given header from the request.
199 * If the header has multiple values, they will be concatenated with a comma
200 * as per the HTTP specification. Be aware that some non-compliant headers
201 * (notably cookie headers) cannot be joined this way.
206 * @param string $key Header name, will be canonicalized to lowercase.
207 * @return string|null String value if set, null otherwise.
209 public function get_header( $key ) {
210 $key = $this->canonicalize_header_name( $key );
212 if ( ! isset( $this->headers[ $key ] ) ) {
216 return implode( ',', $this->headers[ $key ] );
220 * Retrieves header values from the request.
225 * @param string $key Header name, will be canonicalized to lowercase.
226 * @return array|null List of string values if set, null otherwise.
228 public function get_header_as_array( $key ) {
229 $key = $this->canonicalize_header_name( $key );
231 if ( ! isset( $this->headers[ $key ] ) ) {
235 return $this->headers[ $key ];
239 * Sets the header on request.
244 * @param string $key Header name.
245 * @param string $value Header value, or list of values.
247 public function set_header( $key, $value ) {
248 $key = $this->canonicalize_header_name( $key );
249 $value = (array) $value;
251 $this->headers[ $key ] = $value;
255 * Appends a header value for the given header.
260 * @param string $key Header name.
261 * @param string $value Header value, or list of values.
263 public function add_header( $key, $value ) {
264 $key = $this->canonicalize_header_name( $key );
265 $value = (array) $value;
267 if ( ! isset( $this->headers[ $key ] ) ) {
268 $this->headers[ $key ] = array();
271 $this->headers[ $key ] = array_merge( $this->headers[ $key ], $value );
275 * Removes all values for a header.
280 * @param string $key Header name.
282 public function remove_header( $key ) {
283 unset( $this->headers[ $key ] );
287 * Sets headers on the request.
292 * @param array $headers Map of header name to value.
293 * @param bool $override If true, replace the request's headers. Otherwise, merge with existing.
295 public function set_headers( $headers, $override = true ) {
296 if ( true === $override ) {
297 $this->headers = array();
300 foreach ( $headers as $key => $value ) {
301 $this->set_header( $key, $value );
306 * Retrieves the content-type of the request.
311 * @return array Map containing 'value' and 'parameters' keys.
313 public function get_content_type() {
314 $value = $this->get_header( 'content-type' );
315 if ( empty( $value ) ) {
320 if ( strpos( $value, ';' ) ) {
321 list( $value, $parameters ) = explode( ';', $value, 2 );
324 $value = strtolower( $value );
325 if ( strpos( $value, '/' ) === false ) {
329 // Parse type and subtype out.
330 list( $type, $subtype ) = explode( '/', $value, 2 );
332 $data = compact( 'value', 'type', 'subtype', 'parameters' );
333 $data = array_map( 'trim', $data );
339 * Retrieves the parameter priority order.
341 * Used when checking parameters in get_param().
346 * @return array List of types to check, in order of priority.
348 protected function get_parameter_order() {
352 $this->parse_json_params();
354 // Ensure we parse the body data.
355 $body = $this->get_body();
356 if ( $this->method !== 'POST' && ! empty( $body ) ) {
357 $this->parse_body_params();
360 $accepts_body_data = array( 'POST', 'PUT', 'PATCH' );
361 if ( in_array( $this->method, $accepts_body_data ) ) {
367 $order[] = 'defaults';
370 * Filter the parameter order.
372 * The order affects which parameters are checked when using get_param() and family.
373 * This acts similarly to PHP's `request_order` setting.
377 * @param array $order {
378 * An array of types to check, in order of priority.
380 * @param string $type The type to check.
382 * @param WP_REST_Request $this The request object.
384 return apply_filters( 'rest_request_parameter_order', $order, $this );
388 * Retrieves a parameter from the request.
393 * @param string $key Parameter name.
394 * @return mixed|null Value if set, null otherwise.
396 public function get_param( $key ) {
397 $order = $this->get_parameter_order();
399 foreach ( $order as $type ) {
400 // Determine if we have the parameter for this type.
401 if ( isset( $this->params[ $type ][ $key ] ) ) {
402 return $this->params[ $type ][ $key ];
410 * Sets a parameter on the request.
415 * @param string $key Parameter name.
416 * @param mixed $value Parameter value.
418 public function set_param( $key, $value ) {
419 switch ( $this->method ) {
421 $this->params['POST'][ $key ] = $value;
425 $this->params['GET'][ $key ] = $value;
431 * Retrieves merged parameters from the request.
433 * The equivalent of get_param(), but returns all parameters for the request.
434 * Handles merging all the available values into a single array.
439 * @return array Map of key to value.
441 public function get_params() {
442 $order = $this->get_parameter_order();
443 $order = array_reverse( $order, true );
446 foreach ( $order as $type ) {
447 $params = array_merge( $params, (array) $this->params[ $type ] );
454 * Retrieves parameters from the route itself.
456 * These are parsed from the URL using the regex.
461 * @return array Parameter map of key to value.
463 public function get_url_params() {
464 return $this->params['URL'];
468 * Sets parameters from the route.
470 * Typically, this is set after parsing the URL.
475 * @param array $params Parameter map of key to value.
477 public function set_url_params( $params ) {
478 $this->params['URL'] = $params;
482 * Retrieves parameters from the query string.
484 * These are the parameters you'd typically find in `$_GET`.
489 * @return array Parameter map of key to value
491 public function get_query_params() {
492 return $this->params['GET'];
496 * Sets parameters from the query string.
498 * Typically, this is set from `$_GET`.
503 * @param array $params Parameter map of key to value.
505 public function set_query_params( $params ) {
506 $this->params['GET'] = $params;
510 * Retrieves parameters from the body.
512 * These are the parameters you'd typically find in `$_POST`.
517 * @return array Parameter map of key to value.
519 public function get_body_params() {
520 return $this->params['POST'];
524 * Sets parameters from the body.
526 * Typically, this is set from `$_POST`.
531 * @param array $params Parameter map of key to value.
533 public function set_body_params( $params ) {
534 $this->params['POST'] = $params;
538 * Retrieves multipart file parameters from the body.
540 * These are the parameters you'd typically find in `$_FILES`.
545 * @return array Parameter map of key to value
547 public function get_file_params() {
548 return $this->params['FILES'];
552 * Sets multipart file parameters from the body.
554 * Typically, this is set from `$_FILES`.
559 * @param array $params Parameter map of key to value.
561 public function set_file_params( $params ) {
562 $this->params['FILES'] = $params;
566 * Retrieves the default parameters.
568 * These are the parameters set in the route registration.
573 * @return array Parameter map of key to value
575 public function get_default_params() {
576 return $this->params['defaults'];
580 * Sets default parameters.
582 * These are the parameters set in the route registration.
587 * @param array $params Parameter map of key to value.
589 public function set_default_params( $params ) {
590 $this->params['defaults'] = $params;
594 * Retrieves the request body content.
599 * @return string Binary data from the request body.
601 public function get_body() {
611 * @param string $data Binary data from the request body.
613 public function set_body( $data ) {
616 // Enable lazy parsing.
617 $this->parsed_json = false;
618 $this->parsed_body = false;
619 $this->params['JSON'] = null;
623 * Retrieves the parameters from a JSON-formatted body.
628 * @return array Parameter map of key to value.
630 public function get_json_params() {
631 // Ensure the parameters have been parsed out.
632 $this->parse_json_params();
634 return $this->params['JSON'];
638 * Parses the JSON parameters.
640 * Avoids parsing the JSON data until we need to access it.
645 protected function parse_json_params() {
646 if ( $this->parsed_json ) {
650 $this->parsed_json = true;
652 // Check that we actually got JSON.
653 $content_type = $this->get_content_type();
655 if ( empty( $content_type ) || 'application/json' !== $content_type['value'] ) {
659 $params = json_decode( $this->get_body(), true );
662 * Check for a parsing error.
664 * Note that due to WP's JSON compatibility functions, json_last_error
665 * might not be defined: https://core.trac.wordpress.org/ticket/27799
667 if ( null === $params && ( ! function_exists( 'json_last_error' ) || JSON_ERROR_NONE !== json_last_error() ) ) {
671 $this->params['JSON'] = $params;
675 * Parses the request body parameters.
677 * Parses out URL-encoded bodies for request methods that aren't supported
678 * natively by PHP. In PHP 5.x, only POST has these parsed automatically.
683 protected function parse_body_params() {
684 if ( $this->parsed_body ) {
688 $this->parsed_body = true;
691 * Check that we got URL-encoded. Treat a missing content-type as
692 * URL-encoded for maximum compatibility.
694 $content_type = $this->get_content_type();
696 if ( ! empty( $content_type ) && 'application/x-www-form-urlencoded' !== $content_type['value'] ) {
700 parse_str( $this->get_body(), $params );
703 * Amazingly, parse_str follows magic quote rules. Sigh.
705 * NOTE: Do not refactor to use `wp_unslash`.
707 if ( get_magic_quotes_gpc() ) {
708 $params = stripslashes_deep( $params );
712 * Add to the POST parameters stored internally. If a user has already
713 * set these manually (via `set_body_params`), don't override them.
715 $this->params['POST'] = array_merge( $params, $this->params['POST'] );
719 * Retrieves the route that matched the request.
724 * @return string Route matching regex.
726 public function get_route() {
731 * Sets the route that matched the request.
736 * @param string $route Route matching regex.
738 public function set_route( $route ) {
739 $this->route = $route;
743 * Retrieves the attributes for the request.
745 * These are the options for the route that was matched.
750 * @return array Attributes for the request.
752 public function get_attributes() {
753 return $this->attributes;
757 * Sets the attributes for the request.
762 * @param array $attributes Attributes for the request.
764 public function set_attributes( $attributes ) {
765 $this->attributes = $attributes;
769 * Sanitizes (where possible) the params on the request.
771 * This is primarily based off the sanitize_callback param on each registered
777 * @return true|null True if there are no parameters to sanitize, null otherwise.
779 public function sanitize_params() {
781 $attributes = $this->get_attributes();
783 // No arguments set, skip sanitizing.
784 if ( empty( $attributes['args'] ) ) {
788 $order = $this->get_parameter_order();
790 foreach ( $order as $type ) {
791 if ( empty( $this->params[ $type ] ) ) {
794 foreach ( $this->params[ $type ] as $key => $value ) {
795 // Check if this param has a sanitize_callback added.
796 if ( isset( $attributes['args'][ $key ] ) && ! empty( $attributes['args'][ $key ]['sanitize_callback'] ) ) {
797 $this->params[ $type ][ $key ] = call_user_func( $attributes['args'][ $key ]['sanitize_callback'], $value, $this, $key );
805 * Checks whether this request is valid according to its attributes.
810 * @return bool|WP_Error True if there are no parameters to validate or if all pass validation,
811 * WP_Error if required parameters are missing.
813 public function has_valid_params() {
815 $attributes = $this->get_attributes();
818 // No arguments set, skip validation.
819 if ( empty( $attributes['args'] ) ) {
823 foreach ( $attributes['args'] as $key => $arg ) {
825 $param = $this->get_param( $key );
826 if ( isset( $arg['required'] ) && true === $arg['required'] && null === $param ) {
831 if ( ! empty( $required ) ) {
832 return new WP_Error( 'rest_missing_callback_param', sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ), array( 'status' => 400, 'params' => $required ) );
836 * Check the validation callbacks for each registered arg.
838 * This is done after required checking as required checking is cheaper.
840 $invalid_params = array();
842 foreach ( $attributes['args'] as $key => $arg ) {
844 $param = $this->get_param( $key );
846 if ( null !== $param && ! empty( $arg['validate_callback'] ) ) {
847 $valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );
849 if ( false === $valid_check ) {
850 $invalid_params[ $key ] = __( 'Invalid parameter.' );
853 if ( is_wp_error( $valid_check ) ) {
854 $invalid_params[] = sprintf( '%s (%s)', $key, $valid_check->get_error_message() );
859 if ( $invalid_params ) {
860 return new WP_Error( 'rest_invalid_param', sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', $invalid_params ) ), array( 'status' => 400, 'params' => $invalid_params ) );
868 * Checks if a parameter is set.
873 * @param string $offset Parameter name.
874 * @return bool Whether the parameter is set.
876 public function offsetExists( $offset ) {
877 $order = $this->get_parameter_order();
879 foreach ( $order as $type ) {
880 if ( isset( $this->params[ $type ][ $offset ] ) ) {
889 * Retrieves a parameter from the request.
894 * @param string $offset Parameter name.
895 * @return mixed|null Value if set, null otherwise.
897 public function offsetGet( $offset ) {
898 return $this->get_param( $offset );
902 * Sets a parameter on the request.
907 * @param string $offset Parameter name.
908 * @param mixed $value Parameter value.
910 public function offsetSet( $offset, $value ) {
911 $this->set_param( $offset, $value );
915 * Removes a parameter from the request.
920 * @param string $offset Parameter name.
922 public function offsetUnset( $offset ) {
923 $order = $this->get_parameter_order();
925 // Remove the offset from every group.
926 foreach ( $order as $type ) {
927 unset( $this->params[ $type ][ $offset ] );