From b39211475d7c7fe7c56acd878dc1a18afa4dab3f Mon Sep 17 00:00:00 2001 From: Ryan McCue Date: Thu, 8 Oct 2015 02:30:18 +0000 Subject: [PATCH] REST API: Introduce baby API to the world. Baby API was born at 2.8KLOC on October 8th at 2:30 UTC. API has lots of growing to do, so wish it the best of luck. Thanks to everyone who helped along the way: Props rmccue, rachelbaker, danielbachhuber, joehoyle, drewapicture, adamsilverstein, netweb, tlovett1, shelob9, kadamwhite, pento, westonruter, nikv, tobych, redsweater, alecuf, pollyplummer, hurtige, bpetty, oso96_2000, ericlewis, wonderboymusic, joshkadis, mordauk, jdgrimes, johnbillion, jeremyfelt, thiago-negri, jdolan, pkevan, iseulde, thenbrent, maxcutler, kwight, markoheijnen, phh, natewr, jjeaton, shprink, mattheu, quasel, jmusal, codebykat, hubdotcom, tapsboy, QWp6t, pushred, jaredcobb, justinsainton, japh, matrixik, jorbin, frozzare, codfish, michael-arestad, kellbot, ironpaperweight, simonlampen, alisspers, eliorivero, davidbhayes, JohnDittmar, dimadin, traversal, cmmarslender, Toddses, kokarn, welcher, and ericpedia. Fixes #33982. git-svn-id: https://develop.svn.wordpress.org/trunk@34928 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/default-filters.php | 16 + src/wp-includes/rest-api.php | 26 + .../rest-api/class-wp-http-response.php | 165 +++ .../rest-api/class-wp-rest-request.php | 930 +++++++++++++ .../rest-api/class-wp-rest-response.php | 255 ++++ .../rest-api/class-wp-rest-server.php | 1188 +++++++++++++++++ src/wp-includes/rest-api/rest-functions.php | 666 +++++++++ src/wp-settings.php | 1 + tests/phpunit/includes/bootstrap.php | 2 + tests/phpunit/includes/spy-rest-server.php | 23 + tests/phpunit/includes/testcase-rest-api.php | 19 + tests/phpunit/tests/rest-api.php | 255 ++++ tests/phpunit/tests/rest-api/rest-request.php | 394 ++++++ tests/phpunit/tests/rest-api/rest-server.php | 582 ++++++++ 14 files changed, 4522 insertions(+) create mode 100644 src/wp-includes/rest-api.php create mode 100644 src/wp-includes/rest-api/class-wp-http-response.php create mode 100644 src/wp-includes/rest-api/class-wp-rest-request.php create mode 100644 src/wp-includes/rest-api/class-wp-rest-response.php create mode 100644 src/wp-includes/rest-api/class-wp-rest-server.php create mode 100644 src/wp-includes/rest-api/rest-functions.php create mode 100644 tests/phpunit/includes/spy-rest-server.php create mode 100644 tests/phpunit/includes/testcase-rest-api.php create mode 100644 tests/phpunit/tests/rest-api.php create mode 100644 tests/phpunit/tests/rest-api/rest-request.php create mode 100644 tests/phpunit/tests/rest-api/rest-server.php diff --git a/src/wp-includes/default-filters.php b/src/wp-includes/default-filters.php index 20dbaeab91..cfdd7099cf 100644 --- a/src/wp-includes/default-filters.php +++ b/src/wp-includes/default-filters.php @@ -204,6 +204,17 @@ add_filter( 'title_save_pre', 'trim' ); add_filter( 'http_request_host_is_external', 'allowed_http_request_hosts', 10, 2 ); +// REST API filters. +add_action( 'xmlrpc_rsd_apis', 'rest_output_rsd' ); +add_action( 'wp_head', 'rest_output_link_wp_head', 10, 0 ); +add_action( 'template_redirect', 'rest_output_link_header', 11, 0 ); +add_action( 'auth_cookie_malformed', 'rest_cookie_collect_status' ); +add_action( 'auth_cookie_expired', 'rest_cookie_collect_status' ); +add_action( 'auth_cookie_bad_username', 'rest_cookie_collect_status' ); +add_action( 'auth_cookie_bad_hash', 'rest_cookie_collect_status' ); +add_action( 'auth_cookie_valid', 'rest_cookie_collect_status' ); +add_filter( 'rest_authentication_errors', 'rest_cookie_check_errors', 100 ); + // Actions add_action( 'wp_head', '_wp_render_title_tag', 1 ); add_action( 'wp_head', 'wp_enqueue_scripts', 1 ); @@ -347,6 +358,11 @@ add_action( 'after_password_reset', 'wp_password_change_notification' ); add_action( 'register_new_user', 'wp_send_new_user_notifications' ); add_action( 'edit_user_created_user', 'wp_send_new_user_notifications' ); +// REST API actions. +add_action( 'init', 'rest_api_init' ); +add_action( 'rest_api_init', 'rest_api_default_filters', 10, 1 ); +add_action( 'parse_request', 'rest_api_loaded' ); + /** * Filters formerly mixed into wp-includes */ diff --git a/src/wp-includes/rest-api.php b/src/wp-includes/rest-api.php new file mode 100644 index 0000000000..dc880d6304 --- /dev/null +++ b/src/wp-includes/rest-api.php @@ -0,0 +1,26 @@ +data = $data; + $this->set_status( $status ); + $this->set_headers( $headers ); + } + + /** + * Retrieves headers associated with the response. + * + * @since 4.4.0 + * @access public + * + * @return array Map of header name to header value. + */ + public function get_headers() { + return $this->headers; + } + + /** + * Sets all header values. + * + * @since 4.4.0 + * @access public + * + * @param array $headers Map of header name to header value. + */ + public function set_headers( $headers ) { + $this->headers = $headers; + } + + /** + * Sets a single HTTP header. + * + * @since 4.4.0 + * @access public + * + * @param string $key Header name. + * @param string $value Header value. + * @param bool $replace Optional. Whether to replace an existing header of the same name. + * Default true. + */ + public function header( $key, $value, $replace = true ) { + if ( $replace || ! isset( $this->headers[ $key ] ) ) { + $this->headers[ $key ] = $value; + } else { + $this->headers[ $key ] .= ', ' . $value; + } + } + + /** + * Retrieves the HTTP return code for the response. + * + * @since 4.4.0 + * @access public + * + * @return int The 3-digit HTTP status code. + */ + public function get_status() { + return $this->status; + } + + /** + * Sets the 3-digit HTTP status code. + * + * @since 4.4.0 + * @access public + * + * @param int $code HTTP status. + */ + public function set_status( $code ) { + $this->status = absint( $code ); + } + + /** + * Retrieves the response data. + * + * @since 4.4.0 + * @access public + * + * @return mixed Response data. + */ + public function get_data() { + return $this->data; + } + + /** + * Sets the response data. + * + * @since 4.4.0 + * @access public + * + * @param mixed $data Response data. + */ + public function set_data( $data ) { + $this->data = $data; + } + + /** + * Retrieves the response data for JSON serialization. + * + * It is expected that in most implementations, this will return the same as get_data(), + * however this may be different if you want to do custom JSON data handling. + * + * @since 4.4.0 + * @access public + * + * @return mixed Any JSON-serializable value. + */ + public function jsonSerialize() { + return $this->get_data(); + } +} diff --git a/src/wp-includes/rest-api/class-wp-rest-request.php b/src/wp-includes/rest-api/class-wp-rest-request.php new file mode 100644 index 0000000000..2f6aa8aab3 --- /dev/null +++ b/src/wp-includes/rest-api/class-wp-rest-request.php @@ -0,0 +1,930 @@ +params = array( + 'URL' => array(), + 'GET' => array(), + 'POST' => array(), + 'FILES' => array(), + + // See parse_json_params. + 'JSON' => null, + + 'defaults' => array(), + ); + + $this->set_method( $method ); + $this->set_route( $route ); + $this->set_attributes( $attributes ); + } + + /** + * Retrieves the HTTP method for the request. + * + * @since 4.4.0 + * @access public + * + * @return string HTTP method. + */ + public function get_method() { + return $this->method; + } + + /** + * Sets HTTP method for the request. + * + * @since 4.4.0 + * @access public + * + * @param string $method HTTP method. + */ + public function set_method( $method ) { + $this->method = strtoupper( $method ); + } + + /** + * Retrieves all headers from the request. + * + * @since 4.4.0 + * @access public + * + * @return array Map of key to value. Key is always lowercase, as per HTTP specification. + */ + public function get_headers() { + return $this->headers; + } + + /** + * Canonicalizes the header name. + * + * Ensures that header names are always treated the same regardless of + * source. Header names are always case insensitive. + * + * Note that we treat `-` (dashes) and `_` (underscores) as the same + * character, as per header parsing rules in both Apache and nginx. + * + * @link http://stackoverflow.com/q/18185366 + * @link http://wiki.nginx.org/Pitfalls#Missing_.28disappearing.29_HTTP_headers + * @link http://nginx.org/en/docs/http/ngx_http_core_module.html#underscores_in_headers + * + * @since 4.4.0 + * @access public + * @static + * + * @param string $key Header name. + * @return string Canonicalized name. + */ + public static function canonicalize_header_name( $key ) { + $key = strtolower( $key ); + $key = str_replace( '-', '_', $key ); + + return $key; + } + + /** + * Retrieves the given header from the request. + * + * If the header has multiple values, they will be concatenated with a comma + * as per the HTTP specification. Be aware that some non-compliant headers + * (notably cookie headers) cannot be joined this way. + * + * @since 4.4.0 + * @access public + * + * @param string $key Header name, will be canonicalized to lowercase. + * @return string|null String value if set, null otherwise. + */ + public function get_header( $key ) { + $key = $this->canonicalize_header_name( $key ); + + if ( ! isset( $this->headers[ $key ] ) ) { + return null; + } + + return implode( ',', $this->headers[ $key ] ); + } + + /** + * Retrieves header values from the request. + * + * @since 4.4.0 + * @access public + * + * @param string $key Header name, will be canonicalized to lowercase. + * @return array|null List of string values if set, null otherwise. + */ + public function get_header_as_array( $key ) { + $key = $this->canonicalize_header_name( $key ); + + if ( ! isset( $this->headers[ $key ] ) ) { + return null; + } + + return $this->headers[ $key ]; + } + + /** + * Sets the header on request. + * + * @since 4.4.0 + * @access public + * + * @param string $key Header name. + * @param string $value Header value, or list of values. + */ + public function set_header( $key, $value ) { + $key = $this->canonicalize_header_name( $key ); + $value = (array) $value; + + $this->headers[ $key ] = $value; + } + + /** + * Appends a header value for the given header. + * + * @since 4.4.0 + * @access public + * + * @param string $key Header name. + * @param string $value Header value, or list of values. + */ + public function add_header( $key, $value ) { + $key = $this->canonicalize_header_name( $key ); + $value = (array) $value; + + if ( ! isset( $this->headers[ $key ] ) ) { + $this->headers[ $key ] = array(); + } + + $this->headers[ $key ] = array_merge( $this->headers[ $key ], $value ); + } + + /** + * Removes all values for a header. + * + * @since 4.4.0 + * @access public + * + * @param string $key Header name. + */ + public function remove_header( $key ) { + unset( $this->headers[ $key ] ); + } + + /** + * Sets headers on the request. + * + * @since 4.4.0 + * @access public + * + * @param array $headers Map of header name to value. + * @param bool $override If true, replace the request's headers. Otherwise, merge with existing. + */ + public function set_headers( $headers, $override = true ) { + if ( true === $override ) { + $this->headers = array(); + } + + foreach ( $headers as $key => $value ) { + $this->set_header( $key, $value ); + } + } + + /** + * Retrieves the content-type of the request. + * + * @since 4.4.0 + * @access public + * + * @return array Map containing 'value' and 'parameters' keys. + */ + public function get_content_type() { + $value = $this->get_header( 'content-type' ); + if ( empty( $value ) ) { + return null; + } + + $parameters = ''; + if ( strpos( $value, ';' ) ) { + list( $value, $parameters ) = explode( ';', $value, 2 ); + } + + $value = strtolower( $value ); + if ( strpos( $value, '/' ) === false ) { + return null; + } + + // Parse type and subtype out. + list( $type, $subtype ) = explode( '/', $value, 2 ); + + $data = compact( 'value', 'type', 'subtype', 'parameters' ); + $data = array_map( 'trim', $data ); + + return $data; + } + + /** + * Retrieves the parameter priority order. + * + * Used when checking parameters in get_param(). + * + * @since 4.4.0 + * @access public + * + * @return array List of types to check, in order of priority. + */ + protected function get_parameter_order() { + $order = array(); + $order[] = 'JSON'; + + $this->parse_json_params(); + + // Ensure we parse the body data. + $body = $this->get_body(); + if ( $this->method !== 'POST' && ! empty( $body ) ) { + $this->parse_body_params(); + } + + $accepts_body_data = array( 'POST', 'PUT', 'PATCH' ); + if ( in_array( $this->method, $accepts_body_data ) ) { + $order[] = 'POST'; + } + + $order[] = 'GET'; + $order[] = 'URL'; + $order[] = 'defaults'; + + /** + * Filter the parameter order. + * + * The order affects which parameters are checked when using get_param() and family. + * This acts similarly to PHP's `request_order` setting. + * + * @since 4.4.0 + * + * @param array $order { + * An array of types to check, in order of priority. + * + * @param string $type The type to check. + * } + * @param WP_REST_Request $this The request object. + */ + return apply_filters( 'rest_request_parameter_order', $order, $this ); + } + + /** + * Retrieves a parameter from the request. + * + * @since 4.4.0 + * @access public + * + * @param string $key Parameter name. + * @return mixed|null Value if set, null otherwise. + */ + public function get_param( $key ) { + $order = $this->get_parameter_order(); + + foreach ( $order as $type ) { + // Determine if we have the parameter for this type. + if ( isset( $this->params[ $type ][ $key ] ) ) { + return $this->params[ $type ][ $key ]; + } + } + + return null; + } + + /** + * Sets a parameter on the request. + * + * @since 4.4.0 + * @access public + * + * @param string $key Parameter name. + * @param mixed $value Parameter value. + */ + public function set_param( $key, $value ) { + switch ( $this->method ) { + case 'POST': + $this->params['POST'][ $key ] = $value; + break; + + default: + $this->params['GET'][ $key ] = $value; + break; + } + } + + /** + * Retrieves merged parameters from the request. + * + * The equivalent of get_param(), but returns all parameters for the request. + * Handles merging all the available values into a single array. + * + * @since 4.4.0 + * @access public + * + * @return array Map of key to value. + */ + public function get_params() { + $order = $this->get_parameter_order(); + $order = array_reverse( $order, true ); + + $params = array(); + foreach ( $order as $type ) { + $params = array_merge( $params, (array) $this->params[ $type ] ); + } + + return $params; + } + + /** + * Retrieves parameters from the route itself. + * + * These are parsed from the URL using the regex. + * + * @since 4.4.0 + * @access public + * + * @return array Parameter map of key to value. + */ + public function get_url_params() { + return $this->params['URL']; + } + + /** + * Sets parameters from the route. + * + * Typically, this is set after parsing the URL. + * + * @since 4.4.0 + * @access public + * + * @param array $params Parameter map of key to value. + */ + public function set_url_params( $params ) { + $this->params['URL'] = $params; + } + + /** + * Retrieves parameters from the query string. + * + * These are the parameters you'd typically find in `$_GET`. + * + * @since 4.4.0 + * @access public + * + * @return array Parameter map of key to value + */ + public function get_query_params() { + return $this->params['GET']; + } + + /** + * Sets parameters from the query string. + * + * Typically, this is set from `$_GET`. + * + * @since 4.4.0 + * @access public + * + * @param array $params Parameter map of key to value. + */ + public function set_query_params( $params ) { + $this->params['GET'] = $params; + } + + /** + * Retrieves parameters from the body. + * + * These are the parameters you'd typically find in `$_POST`. + * + * @since 4.4.0 + * @access public + * + * @return array Parameter map of key to value. + */ + public function get_body_params() { + return $this->params['POST']; + } + + /** + * Sets parameters from the body. + * + * Typically, this is set from `$_POST`. + * + * @since 4.4.0 + * @access public + * + * @param array $params Parameter map of key to value. + */ + public function set_body_params( $params ) { + $this->params['POST'] = $params; + } + + /** + * Retrieves multipart file parameters from the body. + * + * These are the parameters you'd typically find in `$_FILES`. + * + * @since 4.4.0 + * @access public + * + * @return array Parameter map of key to value + */ + public function get_file_params() { + return $this->params['FILES']; + } + + /** + * Sets multipart file parameters from the body. + * + * Typically, this is set from `$_FILES`. + * + * @since 4.4.0 + * @access public + * + * @param array $params Parameter map of key to value. + */ + public function set_file_params( $params ) { + $this->params['FILES'] = $params; + } + + /** + * Retrieves the default parameters. + * + * These are the parameters set in the route registration. + * + * @since 4.4.0 + * @access public + * + * @return array Parameter map of key to value + */ + public function get_default_params() { + return $this->params['defaults']; + } + + /** + * Sets default parameters. + * + * These are the parameters set in the route registration. + * + * @since 4.4.0 + * @access public + * + * @param array $params Parameter map of key to value. + */ + public function set_default_params( $params ) { + $this->params['defaults'] = $params; + } + + /** + * Retrieves the request body content. + * + * @since 4.4.0 + * @access public + * + * @return string Binary data from the request body. + */ + public function get_body() { + return $this->body; + } + + /** + * Sets body content. + * + * @since 4.4.0 + * @access public + * + * @param string $data Binary data from the request body. + */ + public function set_body( $data ) { + $this->body = $data; + + // Enable lazy parsing. + $this->parsed_json = false; + $this->parsed_body = false; + $this->params['JSON'] = null; + } + + /** + * Retrieves the parameters from a JSON-formatted body. + * + * @since 4.4.0 + * @access public + * + * @return array Parameter map of key to value. + */ + public function get_json_params() { + // Ensure the parameters have been parsed out. + $this->parse_json_params(); + + return $this->params['JSON']; + } + + /** + * Parses the JSON parameters. + * + * Avoids parsing the JSON data until we need to access it. + * + * @since 4.4.0 + * @access protected + */ + protected function parse_json_params() { + if ( $this->parsed_json ) { + return; + } + + $this->parsed_json = true; + + // Check that we actually got JSON. + $content_type = $this->get_content_type(); + + if ( empty( $content_type ) || 'application/json' !== $content_type['value'] ) { + return; + } + + $params = json_decode( $this->get_body(), true ); + + /* + * Check for a parsing error. + * + * Note that due to WP's JSON compatibility functions, json_last_error + * might not be defined: https://core.trac.wordpress.org/ticket/27799 + */ + if ( null === $params && ( ! function_exists( 'json_last_error' ) || JSON_ERROR_NONE !== json_last_error() ) ) { + return; + } + + $this->params['JSON'] = $params; + } + + /** + * Parses the request body parameters. + * + * Parses out URL-encoded bodies for request methods that aren't supported + * natively by PHP. In PHP 5.x, only POST has these parsed automatically. + * + * @since 4.4.0 + * @access protected + */ + protected function parse_body_params() { + if ( $this->parsed_body ) { + return; + } + + $this->parsed_body = true; + + /* + * Check that we got URL-encoded. Treat a missing content-type as + * URL-encoded for maximum compatibility. + */ + $content_type = $this->get_content_type(); + + if ( ! empty( $content_type ) && 'application/x-www-form-urlencoded' !== $content_type['value'] ) { + return; + } + + parse_str( $this->get_body(), $params ); + + /* + * Amazingly, parse_str follows magic quote rules. Sigh. + * + * NOTE: Do not refactor to use `wp_unslash`. + */ + if ( get_magic_quotes_gpc() ) { + $params = stripslashes_deep( $params ); + } + + /* + * Add to the POST parameters stored internally. If a user has already + * set these manually (via `set_body_params`), don't override them. + */ + $this->params['POST'] = array_merge( $params, $this->params['POST'] ); + } + + /** + * Retrieves the route that matched the request. + * + * @since 4.4.0 + * @access public + * + * @return string Route matching regex. + */ + public function get_route() { + return $this->route; + } + + /** + * Sets the route that matched the request. + * + * @since 4.4.0 + * @access public + * + * @param string $route Route matching regex. + */ + public function set_route( $route ) { + $this->route = $route; + } + + /** + * Retrieves the attributes for the request. + * + * These are the options for the route that was matched. + * + * @since 4.4.0 + * @access public + * + * @return array Attributes for the request. + */ + public function get_attributes() { + return $this->attributes; + } + + /** + * Sets the attributes for the request. + * + * @since 4.4.0 + * @access public + * + * @param array $attributes Attributes for the request. + */ + public function set_attributes( $attributes ) { + $this->attributes = $attributes; + } + + /** + * Sanitizes (where possible) the params on the request. + * + * This is primarily based off the sanitize_callback param on each registered + * argument. + * + * @since 4.4.0 + * @access public + * + * @return true|null True if there are no parameters to sanitize, null otherwise. + */ + public function sanitize_params() { + + $attributes = $this->get_attributes(); + + // No arguments set, skip sanitizing. + if ( empty( $attributes['args'] ) ) { + return true; + } + + $order = $this->get_parameter_order(); + + foreach ( $order as $type ) { + if ( empty( $this->params[ $type ] ) ) { + continue; + } + foreach ( $this->params[ $type ] as $key => $value ) { + // Check if this param has a sanitize_callback added. + if ( isset( $attributes['args'][ $key ] ) && ! empty( $attributes['args'][ $key ]['sanitize_callback'] ) ) { + $this->params[ $type ][ $key ] = call_user_func( $attributes['args'][ $key ]['sanitize_callback'], $value, $this, $key ); + } + } + } + return null; + } + + /** + * Checks whether this request is valid according to its attributes. + * + * @since 4.4.0 + * @access public + * + * @return bool|WP_Error True if there are no parameters to validate or if all pass validation, + * WP_Error if required parameters are missing. + */ + public function has_valid_params() { + + $attributes = $this->get_attributes(); + $required = array(); + + // No arguments set, skip validation. + if ( empty( $attributes['args'] ) ) { + return true; + } + + foreach ( $attributes['args'] as $key => $arg ) { + + $param = $this->get_param( $key ); + if ( isset( $arg['required'] ) && true === $arg['required'] && null === $param ) { + $required[] = $key; + } + } + + if ( ! empty( $required ) ) { + return new WP_Error( 'rest_missing_callback_param', sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ), array( 'status' => 400, 'params' => $required ) ); + } + + /* + * Check the validation callbacks for each registered arg. + * + * This is done after required checking as required checking is cheaper. + */ + $invalid_params = array(); + + foreach ( $attributes['args'] as $key => $arg ) { + + $param = $this->get_param( $key ); + + if ( null !== $param && ! empty( $arg['validate_callback'] ) ) { + $valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key ); + + if ( false === $valid_check ) { + $invalid_params[ $key ] = __( 'Invalid param.' ); + } + + if ( is_wp_error( $valid_check ) ) { + $invalid_params[] = sprintf( '%s (%s)', $key, $valid_check->get_error_message() ); + } + } + } + + if ( $invalid_params ) { + return new WP_Error( 'rest_invalid_param', sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', $invalid_params ) ), array( 'status' => 400, 'params' => $invalid_params ) ); + } + + return true; + + } + + /** + * Checks if a parameter is set. + * + * @since 4.4.0 + * @access public + * + * @param string $offset Parameter name. + * @return bool Whether the parameter is set. + */ + public function offsetExists( $offset ) { + $order = $this->get_parameter_order(); + + foreach ( $order as $type ) { + if ( isset( $this->params[ $type ][ $offset ] ) ) { + return true; + } + } + + return false; + } + + /** + * Retrieves a parameter from the request. + * + * @since 4.4.0 + * @access public + * + * @param string $offset Parameter name. + * @return mixed|null Value if set, null otherwise. + */ + public function offsetGet( $offset ) { + return $this->get_param( $offset ); + } + + /** + * Sets a parameter on the request. + * + * @since 4.4.0 + * @access public + * + * @param string $offset Parameter name. + * @param mixed $value Parameter value. + */ + public function offsetSet( $offset, $value ) { + $this->set_param( $offset, $value ); + } + + /** + * Removes a parameter from the request. + * + * @since 4.4.0 + * @access public + * + * @param string $offset Parameter name. + */ + public function offsetUnset( $offset ) { + $order = $this->get_parameter_order(); + + // Remove the offset from every group. + foreach ( $order as $type ) { + unset( $this->params[ $type ][ $offset ] ); + } + } +} diff --git a/src/wp-includes/rest-api/class-wp-rest-response.php b/src/wp-includes/rest-api/class-wp-rest-response.php new file mode 100644 index 0000000000..fed1a3124d --- /dev/null +++ b/src/wp-includes/rest-api/class-wp-rest-response.php @@ -0,0 +1,255 @@ +links[ $rel ] ) ) { + $this->links[ $rel ] = array(); + } + + if ( isset( $attributes['href'] ) ) { + // Remove the href attribute, as it's used for the main URL. + unset( $attributes['href'] ); + } + + $this->links[ $rel ][] = array( + 'href' => $href, + 'attributes' => $attributes, + ); + } + + /** + * Removes a link from the response. + * + * @since 4.4.0 + * @access public + * + * @param string $rel Link relation. Either an IANA registered type, or an absolute URL. + * @param string $href Optional. Only remove links for the relation matching the given href. + * Default null. + */ + public function remove_link( $rel, $href = null ) { + if ( ! isset( $this->links[ $rel ] ) ) { + return; + } + + if ( $href ) { + $this->links[ $rel ] = wp_list_filter( $this->links[ $rel ], array( 'href' => $href ), 'NOT' ); + } else { + $this->links[ $rel ] = array(); + } + + if ( ! $this->links[ $rel ] ) { + unset( $this->links[ $rel ] ); + } + } + + /** + * Adds multiple links to the response. + * + * Link data should be an associative array with link relation as the key. + * The value can either be an associative array of link attributes + * (including `href` with the URL for the response), or a list of these + * associative arrays. + * + * @since 4.4.0 + * @access public + * + * @param array $links Map of link relation to list of links. + */ + public function add_links( $links ) { + foreach ( $links as $rel => $set ) { + // If it's a single link, wrap with an array for consistent handling. + if ( isset( $set['href'] ) ) { + $set = array( $set ); + } + + foreach ( $set as $attributes ) { + $this->add_link( $rel, $attributes['href'], $attributes ); + } + } + } + + /** + * Retrieves links for the response. + * + * @since 4.4.0 + * @access public + * + * @return array List of links. + */ + public function get_links() { + return $this->links; + } + + /** + * Sets a single link header. + * + * @internal The $rel parameter is first, as this looks nicer when sending multiple. + * + * @since 4.4.0 + * @access public + * + * @link http://tools.ietf.org/html/rfc5988 + * @link http://www.iana.org/assignments/link-relations/link-relations.xml + * + * @param string $rel Link relation. Either an IANA registered type, or an absolute URL. + * @param string $link Target IRI for the link. + * @param array $other Optional. Other parameters to send, as an assocative array. + * Default empty array. + */ + public function link_header( $rel, $link, $other = array() ) { + $header = '<' . $link . '>; rel="' . $rel . '"'; + + foreach ( $other as $key => $value ) { + if ( 'title' === $key ) { + $value = '"' . $value . '"'; + } + $header .= '; ' . $key . '=' . $value; + } + $this->header( 'Link', $header, false ); + } + + /** + * Retrieves the route that was used. + * + * @since 4.4.0 + * @access public + * + * @return string The matched route. + */ + public function get_matched_route() { + return $this->matched_route; + } + + /** + * Sets the route (regex for path) that caused the response. + * + * @since 4.4.0 + * @access public + * + * @param string $route Route name. + */ + public function set_matched_route( $route ) { + $this->matched_route = $route; + } + + /** + * Retrieves the handler that was used to generate the response. + * + * @since 4.4.0 + * @access public + * + * @return null|array The handler that was used to create the response. + */ + public function get_matched_handler() { + return $this->matched_handler; + } + + /** + * Retrieves the handler that was responsible for generating the response. + * + * @since 4.4.0 + * @access public + * + * @param array $handler The matched handler. + */ + public function set_matched_handler( $handler ) { + $this->matched_handler = $handler; + } + + /** + * Checks if the response is an error, i.e. >= 400 response code. + * + * @since 4.4.0 + * @access public + * + * @return bool Whether the response is an error. + */ + public function is_error() { + return $this->get_status() >= 400; + } + + /** + * Retrieves a WP_Error object from the response. + * + * @since 4.4.0 + * @access public + * + * @return WP_Error|null WP_Error or null on not an errored response. + */ + public function as_error() { + if ( ! $this->is_error() ) { + return null; + } + + $error = new WP_Error; + + if ( is_array( $this->get_data() ) ) { + foreach ( $this->get_data() as $err ) { + $error->add( $err['code'], $err['message'], $err['data'] ); + } + } else { + $error->add( $this->get_status(), '', array( 'status' => $this->get_status() ) ); + } + + return $error; + } +} diff --git a/src/wp-includes/rest-api/class-wp-rest-server.php b/src/wp-includes/rest-api/class-wp-rest-server.php new file mode 100644 index 0000000000..87c3bf3c2b --- /dev/null +++ b/src/wp-includes/rest-api/class-wp-rest-server.php @@ -0,0 +1,1188 @@ +endpoints = array( + // Meta endpoints. + '/' => array( + 'callback' => array( $this, 'get_index' ), + 'methods' => 'GET', + 'args' => array( + 'context' => array( + 'default' => 'view', + ), + ), + ), + ); + } + + + /** + * Checks the authentication headers if supplied. + * + * @since 4.4.0 + * @access public + * + * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful + * or no authentication provided + */ + public function check_authentication() { + /** + * Pass an authentication error to the API + * + * This is used to pass a WP_Error from an authentication method back to + * the API. + * + * Authentication methods should check first if they're being used, as + * multiple authentication methods can be enabled on a site (cookies, + * HTTP basic auth, OAuth). If the authentication method hooked in is + * not actually being attempted, null should be returned to indicate + * another authentication method should check instead. Similarly, + * callbacks should ensure the value is `null` before checking for + * errors. + * + * A WP_Error instance can be returned if an error occurs, and this should + * match the format used by API methods internally (that is, the `status` + * data should be used). A callback can return `true` to indicate that + * the authentication method was used, and it succeeded. + * + * @since 4.4.0 + * + * @param WP_Error|null|bool WP_Error if authentication error, null if authentication + * method wasn't used, true if authentication succeeded. + */ + return apply_filters( 'rest_authentication_errors', null ); + } + + /** + * Converts an error to a response object. + * + * This iterates over all error codes and messages to change it into a flat + * array. This enables simpler client behaviour, as it is represented as a + * list in JSON rather than an object/map. + * + * @since 4.4.0 + * @access protected + * + * @param WP_Error $error WP_Error instance. + * @return WP_REST_Response List of associative arrays with code and message keys. + */ + protected function error_to_response( $error ) { + $error_data = $error->get_error_data(); + + if ( is_array( $error_data ) && isset( $error_data['status'] ) ) { + $status = $error_data['status']; + } else { + $status = 500; + } + + $data = array(); + + foreach ( (array) $error->errors as $code => $messages ) { + foreach ( (array) $messages as $message ) { + $data[] = array( 'code' => $code, 'message' => $message, 'data' => $error->get_error_data( $code ) ); + } + } + + $response = new WP_REST_Response( $data, $status ); + + return $response; + } + + /** + * Retrieves an appropriate error representation in JSON. + * + * Note: This should only be used in WP_REST_Server::serve_request(), as it + * cannot handle WP_Error internally. All callbacks and other internal methods + * should instead return a WP_Error with the data set to an array that includes + * a 'status' key, with the value being the HTTP status to send. + * + * @since 4.4.0 + * @access protected + * + * @param string $code WP_Error-style code. + * @param string $message Human-readable message. + * @param int $status Optional. HTTP status code to send. Default null. + * @return string JSON representation of the error + */ + protected function json_error( $code, $message, $status = null ) { + if ( $status ) { + $this->set_status( $status ); + } + + $error = compact( 'code', 'message' ); + + return wp_json_encode( array( $error ) ); + } + + /** + * Handles serving an API request. + * + * Matches the current server URI to a route and runs the first matching + * callback then outputs a JSON representation of the returned value. + * + * @since 4.4.0 + * @access public + * + * @see WP_REST_Server::dispatch() + * + * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used. + * Default null. + * @return false|null Null if not served and a HEAD request, false otherwise. + */ + public function serve_request( $path = null ) { + $content_type = isset( $_GET['_jsonp'] ) ? 'application/javascript' : 'application/json'; + $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) ); + + /* + * Mitigate possible JSONP Flash attacks. + * + * http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/ + */ + $this->send_header( 'X-Content-Type-Options', 'nosniff' ); + $this->send_header( 'Access-Control-Expose-Headers', 'X-WP-Total, X-WP-TotalPages' ); + $this->send_header( 'Access-Control-Allow-Headers', 'Authorization' ); + + /** + * Filter whether the REST API is enabled. + * + * @since 4.4.0 + * + * @param bool $rest_enabled Whether the REST API is enabled. Default true. + */ + $enabled = apply_filters( 'rest_enabled', true ); + + /** + * Filter whether jsonp is enabled. + * + * @since 4.4.0 + * + * @param bool $jsonp_enabled Whether jsonp is enabled. Default true. + */ + $jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true ); + + $jsonp_callback = null; + + if ( ! $enabled ) { + echo $this->json_error( 'rest_disabled', __( 'The REST API is disabled on this site.' ), 404 ); + return false; + } + if ( isset( $_GET['_jsonp'] ) ) { + if ( ! $jsonp_enabled ) { + echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 ); + return false; + } + + // Check for invalid characters (only alphanumeric allowed). + if ( is_string( $_GET['_jsonp'] ) ) { + $jsonp_callback = preg_replace( '/[^\w\.]/', '', wp_unslash( $_GET['_jsonp'] ), -1, $illegal_char_count ); + if ( 0 !== $illegal_char_count ) { + $jsonp_callback = null; + } + } + if ( null === $jsonp_callback ) { + echo $this->json_error( 'rest_callback_invalid', __( 'The JSONP callback function is invalid.' ), 400 ); + return false; + } + } + + if ( empty( $path ) ) { + if ( isset( $_SERVER['PATH_INFO'] ) ) { + $path = $_SERVER['PATH_INFO']; + } else { + $path = '/'; + } + } + + $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path ); + + $request->set_query_params( $_GET ); + $request->set_body_params( $_POST ); + $request->set_file_params( $_FILES ); + $request->set_headers( $this->get_headers( $_SERVER ) ); + $request->set_body( $this->get_raw_data() ); + + /* + * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check + * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE + * header. + */ + if ( isset( $_GET['_method'] ) ) { + $request->set_method( $_GET['_method'] ); + } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) { + $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ); + } + + $result = $this->check_authentication(); + + if ( ! is_wp_error( $result ) ) { + $result = $this->dispatch( $request ); + } + + // Normalize to either WP_Error or WP_REST_Response... + $result = rest_ensure_response( $result ); + + // ...then convert WP_Error across. + if ( is_wp_error( $result ) ) { + $result = $this->error_to_response( $result ); + } + + /** + * Filter the API response. + * + * Allows modification of the response before returning. + * + * @since 4.4.0 + * + * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response. + * @param WP_REST_Server $this Server instance. + * @param WP_REST_Request $request Request used to generate the response. + */ + $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request ); + + // Wrap the response in an envelope if asked for. + if ( isset( $_GET['_envelope'] ) ) { + $result = $this->envelope_response( $result, isset( $_GET['_embed'] ) ); + } + + // Send extra data from response objects. + $headers = $result->get_headers(); + $this->send_headers( $headers ); + + $code = $result->get_status(); + $this->set_status( $code ); + + /** + * Filter whether the request has already been served. + * + * Allow sending the request manually - by returning true, the API result + * will not be sent to the client. + * + * @since 4.4.0 + * + * @param bool $served Whether the request has already been served. + * Default false. + * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response. + * @param WP_REST_Request $request Request used to generate the response. + * @param WP_REST_Server $this Server instance. + */ + $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this ); + + if ( ! $served ) { + if ( 'HEAD' === $request->get_method() ) { + return null; + } + + // Embed links inside the request. + $result = $this->response_to_data( $result, isset( $_GET['_embed'] ) ); + + $result = wp_json_encode( $result ); + + $json_error_message = $this->get_json_last_error(); + if ( $json_error_message ) { + $json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, array( 'status' => 500 ) ); + $result = $this->error_to_response( $json_error_obj ); + $result = wp_json_encode( $result->data[0] ); + } + + if ( $jsonp_callback ) { + // Prepend '/**/' to mitigate possible JSONP Flash attacks + // http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/ + echo '/**/' . $jsonp_callback . '(' . $result . ')'; + } else { + echo $result; + } + } + return null; + } + + /** + * Converts a response to data to send. + * + * @since 4.4.0 + * @access public + * + * @param WP_REST_Response $response Response object. + * @param bool $embed Whether links should be embedded. + * @return array { + * Data with sub-requests embedded. + * + * @type array [$_links] Links. + * @type array [$_embedded] Embeddeds. + * } + */ + public function response_to_data( $response, $embed ) { + $data = $response->get_data(); + $links = $this->get_response_links( $response ); + + if ( ! empty( $links ) ) { + // Convert links to part of the data. + $data['_links'] = $links; + } + if ( $embed ) { + // Determine if this is a numeric array. + if ( wp_is_numeric_array( $data ) ) { + $data = array_map( array( $this, 'embed_links' ), $data ); + } else { + $data = $this->embed_links( $data ); + } + } + + return $data; + } + + /** + * Retrieves links from a response. + * + * Extracts the links from a response into a structured hash, suitable for + * direct output. + * + * @since 4.4.0 + * @access public + * @static + * + * @param WP_REST_Response $response Response to extract links from. + * @return array Map of link relation to list of link hashes. + */ + public static function get_response_links( $response ) { + $links = $response->get_links(); + + if ( empty( $links ) ) { + return array(); + } + + // Convert links to part of the data. + $data = array(); + foreach ( $links as $rel => $items ) { + $data[ $rel ] = array(); + + foreach ( $items as $item ) { + $attributes = $item['attributes']; + $attributes['href'] = $item['href']; + $data[ $rel ][] = $attributes; + } + } + + return $data; + } + + /** + * Embeds the links from the data into the request. + * + * @since 4.4.0 + * @access protected + * + * @param array $data Data from the request. + * @return array { + * Data with sub-requests embedded. + * + * @type array [$_links] Links. + * @type array [$_embedded] Embeddeds. + * } + */ + protected function embed_links( $data ) { + if ( empty( $data['_links'] ) ) { + return $data; + } + + $embedded = array(); + $api_root = rest_url(); + + foreach ( $data['_links'] as $rel => $links ) { + // Ignore links to self, for obvious reasons. + if ( 'self' === $rel ) { + continue; + } + + $embeds = array(); + + foreach ( $links as $item ) { + // Determine if the link is embeddable. + if ( empty( $item['embeddable'] ) || strpos( $item['href'], $api_root ) !== 0 ) { + // Ensure we keep the same order. + $embeds[] = array(); + continue; + } + + // Run through our internal routing and serve. + $route = substr( $item['href'], strlen( untrailingslashit( $api_root ) ) ); + $query_params = array(); + + // Parse out URL query parameters. + $parsed = parse_url( $route ); + if ( empty( $parsed['path'] ) ) { + $embeds[] = array(); + continue; + } + + if ( ! empty( $parsed['query'] ) ) { + parse_str( $parsed['query'], $query_params ); + + // Ensure magic quotes are stripped. + if ( get_magic_quotes_gpc() ) { + $query_params = stripslashes_deep( $query_params ); + } + } + + // Embedded resources get passed context=embed. + if ( empty( $query_params['context'] ) ) { + $query_params['context'] = 'embed'; + } + + $request = new WP_REST_Request( 'GET', $parsed['path'] ); + + $request->set_query_params( $query_params ); + $response = $this->dispatch( $request ); + + $embeds[] = $this->response_to_data( $response, false ); + } + + // Determine if any real links were found. + $has_links = count( array_filter( $embeds ) ); + if ( $has_links ) { + $embedded[ $rel ] = $embeds; + } + } + + if ( ! empty( $embedded ) ) { + $data['_embedded'] = $embedded; + } + + return $data; + } + + /** + * Wraps the response in an envelope. + * + * The enveloping technique is used to work around browser/client + * compatibility issues. Essentially, it converts the full HTTP response to + * data instead. + * + * @since 4.4.0 + * @access public + * + * @param WP_REST_Response $response Response object. + * @param bool $embed Whether links should be embedded. + * @return WP_REST_Response New response with wrapped data + */ + public function envelope_response( $response, $embed ) { + $envelope = array( + 'body' => $this->response_to_data( $response, $embed ), + 'status' => $response->get_status(), + 'headers' => $response->get_headers(), + ); + + /** + * Filter the enveloped form of a response. + * + * @since 4.4.0 + * + * @param array $envelope Envelope data. + * @param WP_REST_Response $response Original response data. + */ + $envelope = apply_filters( 'rest_envelope_response', $envelope, $response ); + + // Ensure it's still a response and return. + return rest_ensure_response( $envelope ); + } + + /** + * Registers a route to the server. + * + * @since 4.4.0 + * @access public + * + * @param string $namespace Namespace. + * @param string $route The REST route. + * @param array $route_args Route arguments. + * @param bool $override Optional. Whether the route should be overriden if it already exists. + * Default false. + */ + public function register_route( $namespace, $route, $route_args, $override = false ) { + if ( ! isset( $this->namespaces[ $namespace ] ) ) { + $this->namespaces[ $namespace ] = array(); + + $this->register_route( $namespace, '/' . $namespace, array( + array( + 'methods' => self::READABLE, + 'callback' => array( $this, 'get_namespace_index' ), + 'args' => array( + 'namespace' => array( + 'default' => $namespace, + ), + 'context' => array( + 'default' => 'view', + ), + ), + ), + ) ); + } + + // Associative to avoid double-registration. + $this->namespaces[ $namespace ][ $route ] = true; + $route_args['namespace'] = $namespace; + + if ( $override || empty( $this->endpoints[ $route ] ) ) { + $this->endpoints[ $route ] = $route_args; + } else { + $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args ); + } + } + + /** + * Retrieves the route map. + * + * The route map is an associative array with path regexes as the keys. The + * value is an indexed array with the callback function/method as the first + * item, and a bitmask of HTTP methods as the second item (see the class + * constants). + * + * Each route can be mapped to more than one callback by using an array of + * the indexed arrays. This allows mapping e.g. GET requests to one callback + * and POST requests to another. + * + * Note that the path regexes (array keys) must have @ escaped, as this is + * used as the delimiter with preg_match() + * + * @since 4.4.0 + * @access public + * + * @return array `'/path/regex' => array( $callback, $bitmask )` or + * `'/path/regex' => array( array( $callback, $bitmask ), ...)`. + */ + public function get_routes() { + + /** + * Filter the array of available endpoints. + * + * @since 4.4.0 + * + * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped + * to an array of callbacks for the endpoint. These take the format + * `'/path/regex' => array( $callback, $bitmask )` or + * `'/path/regex' => array( array( $callback, $bitmask ). + */ + $endpoints = apply_filters( 'rest_endpoints', $this->endpoints ); + + // Normalise the endpoints. + $defaults = array( + 'methods' => '', + 'accept_json' => false, + 'accept_raw' => false, + 'show_in_index' => true, + 'args' => array(), + ); + + foreach ( $endpoints as $route => &$handlers ) { + + if ( isset( $handlers['callback'] ) ) { + // Single endpoint, add one deeper. + $handlers = array( $handlers ); + } + + if ( ! isset( $this->route_options[ $route ] ) ) { + $this->route_options[ $route ] = array(); + } + + foreach ( $handlers as $key => &$handler ) { + + if ( ! is_numeric( $key ) ) { + // Route option, move it to the options. + $this->route_options[ $route ][ $key ] = $handler; + unset( $handlers[ $key ] ); + continue; + } + + $handler = wp_parse_args( $handler, $defaults ); + + // Allow comma-separated HTTP methods. + if ( is_string( $handler['methods'] ) ) { + $methods = explode( ',', $handler['methods'] ); + } else if ( is_array( $handler['methods'] ) ) { + $methods = $handler['methods']; + } else { + $methods = array(); + } + + $handler['methods'] = array(); + + foreach ( $methods as $method ) { + $method = strtoupper( trim( $method ) ); + $handler['methods'][ $method ] = true; + } + } + } + return $endpoints; + } + + /** + * Retrieves namespaces registered on the server. + * + * @since 4.4.0 + * @access public + * + * @return array List of registered namespaces. + */ + public function get_namespaces() { + return array_keys( $this->namespaces ); + } + + /** + * Retrieves specified options for a route. + * + * @since 4.4.0 + * @access public + * + * @param string $route Route pattern to fetch options for. + * @return array|null Data as an associative array if found, or null if not found. + */ + public function get_route_options( $route ) { + if ( ! isset( $this->route_options[ $route ] ) ) { + return null; + } + + return $this->route_options[ $route ]; + } + + /** + * Matches the request to a callback and call it. + * + * @since 4.4.0 + * @access public + * + * @param WP_REST_Request $request Request to attempt dispatching. + * @return WP_REST_Response Response returned by the callback. + */ + public function dispatch( $request ) { + /** + * Filter the pre-calculated result of a REST dispatch request. + * + * Allow hijacking the request before dispatching by returning a non-empty. The returned value + * will be used to serve the request instead. + * + * @since 4.4.0 + * + * @param mixed $result Response to replace the requested version with. Can be anything + * a normal endpoint can return, or null to not hijack the request. + * @param WP_REST_Server $this Server instance. + * @param WP_REST_Request $request Request used to generate the response. + */ + $result = apply_filters( 'rest_pre_dispatch', null, $this, $request ); + + if ( ! empty( $result ) ) { + return $result; + } + + $method = $request->get_method(); + $path = $request->get_route(); + + foreach ( $this->get_routes() as $route => $handlers ) { + foreach ( $handlers as $handler ) { + $callback = $handler['callback']; + $response = null; + + if ( empty( $handler['methods'][ $method ] ) ) { + continue; + } + + $match = preg_match( '@^' . $route . '$@i', $path, $args ); + + if ( ! $match ) { + continue; + } + + if ( ! is_callable( $callback ) ) { + $response = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) ); + } + + if ( ! is_wp_error( $response ) ) { + + $request->set_url_params( $args ); + $request->set_attributes( $handler ); + + $request->sanitize_params(); + + $defaults = array(); + + foreach ( $handler['args'] as $arg => $options ) { + if ( isset( $options['default'] ) ) { + $defaults[ $arg ] = $options['default']; + } + } + + $request->set_default_params( $defaults ); + + $check_required = $request->has_valid_params(); + if ( is_wp_error( $check_required ) ) { + $response = $check_required; + } + } + + if ( ! is_wp_error( $response ) ) { + // Check permission specified on the route. + if ( ! empty( $handler['permission_callback'] ) ) { + $permission = call_user_func( $handler['permission_callback'], $request ); + + if ( is_wp_error( $permission ) ) { + $response = $permission; + } else if ( false === $permission || null === $permission ) { + $response = new WP_Error( 'rest_forbidden', __( "You don't have permission to do this." ), array( 'status' => 403 ) ); + } + } + } + + if ( ! is_wp_error( $response ) ) { + /** + * Filter the REST dispatch request result. + * + * Allow plugins to override dispatching the request. + * + * @since 4.4.0 + * + * @param bool $dispatch_result Dispatch result, will be used if not empty. + * @param WP_REST_Request $request Request used to generate the response. + */ + $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request ); + + // Allow plugins to halt the request via this filter. + if ( null !== $dispatch_result ) { + $response = $dispatch_result; + } else { + $response = call_user_func( $callback, $request ); + } + } + + if ( is_wp_error( $response ) ) { + $response = $this->error_to_response( $response ); + } else { + $response = rest_ensure_response( $response ); + } + + $response->set_matched_route( $route ); + $response->set_matched_handler( $handler ); + + return $response; + } + } + + return $this->error_to_response( new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method' ), array( 'status' => 404 ) ) ); + } + + /** + * Returns if an error occurred during most recent JSON encode/decode. + * + * Strings to be translated will be in format like + * "Encoding error: Maximum stack depth exceeded". + * + * @since 4.4.0 + * @access protected + * + * @return bool|string Boolean false or string error message. + */ + protected function get_json_last_error() { + // See https://core.trac.wordpress.org/ticket/27799. + if ( ! function_exists( 'json_last_error' ) ) { + return false; + } + + $last_error_code = json_last_error(); + + if ( ( defined( 'JSON_ERROR_NONE' ) && JSON_ERROR_NONE === $last_error_code ) || empty( $last_error_code ) ) { + return false; + } + + return json_last_error_msg(); + } + + /** + * Retrieves the site index. + * + * This endpoint describes the capabilities of the site. + * + * @since 4.4.0 + * @access public + * + * @param array $request { + * Request. + * + * @type string $context Context. + * } + * @return array Index entity + */ + public function get_index( $request ) { + // General site data. + $available = array( + 'name' => get_option( 'blogname' ), + 'description' => get_option( 'blogdescription' ), + 'url' => get_option( 'siteurl' ), + 'namespaces' => array_keys( $this->namespaces ), + 'authentication' => array(), + 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ), + ); + + $response = new WP_REST_Response( $available ); + + $response->add_link( 'help', 'http://v2.wp-api.org/' ); + + /** + * Filter the API root index data. + * + * This contains the data describing the API. This includes information + * about supported authentication schemes, supported namespaces, routes + * available on the API, and a small amount of data about the site. + * + * @since 4.4.0 + * + * @param WP_REST_Response $response Response data. + */ + return apply_filters( 'rest_index', $response ); + } + + /** + * Retrieves the index for a namespace. + * + * @since 4.4.0 + * @access public + * + * @param WP_REST_Request $request REST request instance. + * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found, + * WP_Error if the namespace isn't set. + */ + public function get_namespace_index( $request ) { + $namespace = $request['namespace']; + + if ( ! isset( $this->namespaces[ $namespace ] ) ) { + return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) ); + } + + $routes = $this->namespaces[ $namespace ]; + $endpoints = array_intersect_key( $this->get_routes(), $routes ); + + $data = array( + 'namespace' => $namespace, + 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ), + ); + $response = rest_ensure_response( $data ); + + // Link to the root index. + $response->add_link( 'up', rest_url( '/' ) ); + + /** + * Filter the namespace index data. + * + * This typically is just the route data for the namespace, but you can + * add any data you'd like here. + * + * @since 4.4.0 + * + * @param WP_REST_Response $response Response data. + * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter. + */ + return apply_filters( 'rest_namespace_index', $response, $request ); + } + + /** + * Retrieves the publicly-visible data for routes. + * + * @since 4.4.0 + * @access public + * + * @param array $routes Routes to get data for. + * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'. + * @return array Route data to expose in indexes. + */ + public function get_data_for_routes( $routes, $context = 'view' ) { + $available = array(); + + // Find the available routes. + foreach ( $routes as $route => $callbacks ) { + $data = $this->get_data_for_route( $route, $callbacks, $context ); + if ( empty( $data ) ) { + continue; + } + + /** + * Filter the REST endpoint data. + * + * @since 4.4.0 + * + * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter. + */ + $available[ $route ] = apply_filters( 'rest_endpoints_description', $data ); + } + + /** + * Filter the publicly-visible data for routes. + * + * This data is exposed on indexes and can be used by clients or + * developers to investigate the site and find out how to use it. It + * acts as a form of self-documentation. + * + * @since 4.4.0 + * + * @param array $available Map of route to route data. + * @param array $routes Internal route data as an associative array. + */ + return apply_filters( 'rest_route_data', $available, $routes ); + } + + /** + * Retrieves publicly-visible data for the route. + * + * @since 4.4.0 + * @access public + * + * @param string $route Route to get data for. + * @param array $callbacks Callbacks to convert to data. + * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'. + * @return array|null Data for the route, or null if no publicly-visible data. + */ + public function get_data_for_route( $route, $callbacks, $context = 'view' ) { + $data = array( + 'namespace' => '', + 'methods' => array(), + 'endpoints' => array(), + ); + + if ( isset( $this->route_options[ $route ] ) ) { + $options = $this->route_options[ $route ]; + + if ( isset( $options['namespace'] ) ) { + $data['namespace'] = $options['namespace']; + } + + if ( isset( $options['schema'] ) && 'help' === $context ) { + $data['schema'] = call_user_func( $options['schema'] ); + } + } + + $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route ); + + foreach ( $callbacks as $callback ) { + // Skip to the next route if any callback is hidden. + if ( empty( $callback['show_in_index'] ) ) { + continue; + } + + $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) ); + $endpoint_data = array( + 'methods' => array_keys( $callback['methods'] ), + ); + + if ( isset( $callback['args'] ) ) { + $endpoint_data['args'] = array(); + foreach ( $callback['args'] as $key => $opts ) { + $arg_data = array( + 'required' => ! empty( $opts['required'] ), + ); + if ( isset( $opts['default'] ) ) { + $arg_data['default'] = $opts['default']; + } + $endpoint_data['args'][ $key ] = $arg_data; + } + } + + $data['endpoints'][] = $endpoint_data; + + // For non-variable routes, generate links. + if ( strpos( $route, '{' ) === false ) { + $data['_links'] = array( + 'self' => rest_url( $route ), + ); + } + } + + if ( empty( $data['methods'] ) ) { + // No methods supported, hide the route. + return null; + } + + return $data; + } + + /** + * Sends an HTTP status code. + * + * @since 4.4.0 + * @access protected + * + * @param int $code HTTP status. + */ + protected function set_status( $code ) { + status_header( $code ); + } + + /** + * Sends an HTTP header. + * + * @since 4.4.0 + * @access public + * + * @param string $key Header key. + * @param string $value Header value. + */ + public function send_header( $key, $value ) { + /* + * Sanitize as per RFC2616 (Section 4.2): + * + * Any LWS that occurs between field-content MAY be replaced with a + * single SP before interpreting the field value or forwarding the + * message downstream. + */ + $value = preg_replace( '/\s+/', ' ', $value ); + header( sprintf( '%s: %s', $key, $value ) ); + } + + /** + * Sends multiple HTTP headers. + * + * @since 4.4.0 + * @access public + * + * @param array $headers Map of header name to header value. + */ + public function send_headers( $headers ) { + foreach ( $headers as $key => $value ) { + $this->send_header( $key, $value ); + } + } + + /** + * Retrieves the raw request entity (body). + * + * @since 4.4.0 + * @access public + * + * @global string $HTTP_RAW_POST_DATA Raw post data. + * + * @return string Raw request data. + */ + public function get_raw_data() { + global $HTTP_RAW_POST_DATA; + + /* + * A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default, + * but we can do it ourself. + */ + if ( ! isset( $HTTP_RAW_POST_DATA ) ) { + $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' ); + } + + return $HTTP_RAW_POST_DATA; + } + + /** + * Extracts headers from a PHP-style $_SERVER array. + * + * @since 4.4.0 + * @access public + * + * @param array $server Associative array similar to `$_SERVER`. + * @return array Headers extracted from the input. + */ + public function get_headers( $server ) { + $headers = array(); + + // CONTENT_* headers are not prefixed with HTTP_. + $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true ); + + foreach ( $server as $key => $value ) { + if ( strpos( $key, 'HTTP_' ) === 0 ) { + $headers[ substr( $key, 5 ) ] = $value; + } elseif ( isset( $additional[ $key ] ) ) { + $headers[ $key ] = $value; + } + } + + return $headers; + } +} diff --git a/src/wp-includes/rest-api/rest-functions.php b/src/wp-includes/rest-api/rest-functions.php new file mode 100644 index 0000000000..8a687f78ad --- /dev/null +++ b/src/wp-includes/rest-api/rest-functions.php @@ -0,0 +1,666 @@ + 'GET', + 'callback' => null, + 'args' => array(), + ); + foreach ( $args as $key => &$arg_group ) { + if ( ! is_numeric( $arg_group ) ) { + // Route option, skip here. + continue; + } + + $arg_group = array_merge( $defaults, $arg_group ); + } + + if ( $namespace ) { + $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' ); + } else { + /* + * Non-namespaced routes are not allowed, with the exception of the main + * and namespace indexes. If you really need to register a + * non-namespaced route, call `WP_REST_Server::register_route` directly. + */ + _doing_it_wrong( 'register_rest_route', 'Routes must be namespaced with plugin name and version', 'WPAPI-2.0' ); + + $full_route = '/' . trim( $route, '/' ); + } + + $wp_rest_server->register_route( $namespace, $full_route, $args, $override ); +} + +/** + * Registers a new field on an existing WordPress object type. + * + * @since 4.4.0 + * + * @global array $wp_rest_additional_fields Holds registered fields, organized + * by object type. + * + * @param string|array $object_type Object(s) the field is being registered + * to, "post"|"term"|"comment" etc. + * @param string $attribute The attribute name. + * @param array $args { + * Optional. An array of arguments used to handle the registered field. + * + * @type string|array|null $get_callback Optional. The callback function used to retrieve the field + * value. Default is 'null', the field will not be returned in + * the response. + * @type string|array|null $update_callback Optional. The callback function used to set and update the + * field value. Default is 'null', the value cannot be set or + * updated. + * @type string|array|null schema Optional. The callback function used to create the schema for + * this field. Default is 'null', no schema entry will be returned. + * } + */ +function register_api_field( $object_type, $attribute, $args = array() ) { + + $defaults = array( + 'get_callback' => null, + 'update_callback' => null, + 'schema' => null, + ); + + $args = wp_parse_args( $args, $defaults ); + + global $wp_rest_additional_fields; + + $object_types = (array) $object_type; + + foreach ( $object_types as $object_type ) { + $wp_rest_additional_fields[ $object_type ][ $attribute ] = $args; + } +} + +/** + * Registers rewrite rules for the API. + * + * @since 4.4.0 + * + * @see rest_api_register_rewrites() + * @global WP $wp Current WordPress environment instance. + */ +function rest_api_init() { + rest_api_register_rewrites(); + + global $wp; + $wp->add_query_var( 'rest_route' ); +} + +/** + * Adds REST rewrite rules. + * + * @since 4.4.0 + * + * @see add_rewrite_rule() + */ +function rest_api_register_rewrites() { + add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$','index.php?rest_route=/','top' ); + add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?','index.php?rest_route=/$matches[1]','top' ); +} + +/** + * Registers the default REST API filters. + * + * @since 4.4.0 + * + * @internal This will live in default-filters.php + */ +function rest_api_default_filters() { + // Deprecated reporting. + add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 ); + add_filter( 'deprecated_function_trigger_error', '__return_false' ); + add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 ); + add_filter( 'deprecated_argument_trigger_error', '__return_false' ); + + // Default serving. + add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' ); + add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 ); + + add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 ); +} + +/** + * Loads the REST API. + * + * @since 4.4.0 + */ +function rest_api_loaded() { + if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) { + return; + } + + /** + * Whether this is a REST Request. + * + * @var bool + */ + define( 'REST_REQUEST', true ); + + /** @var WP_REST_Server $wp_rest_server */ + global $wp_rest_server; + + /** + * Filter the REST Server Class. + * + * This filter allows you to adjust the server class used by the API, using a + * different class to handle requests. + * + * @since 4.4.0 + * + * @param string $class_name The name of the server class. Default 'WP_REST_Server'. + */ + $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' ); + $wp_rest_server = new $wp_rest_server_class; + + /** + * Fires when preparing to serve an API request. + * + * Endpoint objects should be created and register their hooks on this action rather + * than another action to ensure they're only loaded when needed. + * + * @since 4.4.0 + * + * @param WP_REST_Server $wp_rest_server Server object. + */ + do_action( 'rest_api_init', $wp_rest_server ); + + // Fire off the request. + $wp_rest_server->serve_request( $GLOBALS['wp']->query_vars['rest_route'] ); + + // We're done. + die(); +} + +/** + * Retrieves the URL prefix for any API resource. + * + * @since 4.4.0 + * + * @return string Prefix. + */ +function rest_get_url_prefix() { + /** + * Filter the REST URL prefix. + * + * @since 4.4.0 + * + * @param string $prefix URL prefix. Default 'wp-json'. + */ + return apply_filters( 'rest_url_prefix', 'wp-json' ); +} + +/** + * Retrieves the URL to a REST endpoint on a site. + * + * Note: The returned URL is NOT escaped. + * + * @since 4.4.0 + * + * @todo Check if this is even necessary + * + * @param int $blog_id Optional. Blog ID. Default of null returns URL for current blog. + * @param string $path Optional. REST route. Default '/'. + * @param string $scheme Optional. Sanitization scheme. Default 'json'. + * @return string Full URL to the endpoint. + */ +function get_rest_url( $blog_id = null, $path = '/', $scheme = 'json' ) { + if ( empty( $path ) ) { + $path = '/'; + } + + if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) { + $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme ); + $url .= '/' . ltrim( $path, '/' ); + } else { + $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) ); + + $path = '/' . ltrim( $path, '/' ); + + $url = add_query_arg( 'rest_route', $path, $url ); + } + + /** + * Filter the REST URL. + * + * Use this filter to adjust the url returned by the `get_rest_url` function. + * + * @since 4.4.0 + * + * @param string $url REST URL. + * @param string $path REST route. + * @param int $blod_ig Blog ID. + * @param string $scheme Sanitization scheme. + */ + return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme ); +} + +/** + * Retrieves the URL to a REST endpoint. + * + * Note: The returned URL is NOT escaped. + * + * @since 4.4.0 + * + * @param string $path Optional. REST route. Default empty. + * @param string $scheme Optional. Sanitization scheme. Default 'json'. + * @return string Full URL to the endpoint. + */ +function rest_url( $path = '', $scheme = 'json' ) { + return get_rest_url( null, $path, $scheme ); +} + +/** + * Do a REST request. + * + * Used primarily to route internal requests through WP_REST_Server. + * + * @since 4.4.0 + * + * @global WP_REST_Server $wp_rest_server + * + * @param WP_REST_Request|string $request Request. + * @return WP_REST_Response REST response. + */ +function rest_do_request( $request ) { + global $wp_rest_server; + $request = rest_ensure_request( $request ); + return $wp_rest_server->dispatch( $request ); +} + +/** + * Ensures request arguments are a request object (for consistency). + * + * @since 4.4.0 + * + * @param array|WP_REST_Request $request Request to check. + * @return WP_REST_Request REST request instance. + */ +function rest_ensure_request( $request ) { + if ( $request instanceof WP_REST_Request ) { + return $request; + } + + return new WP_REST_Request( 'GET', '', $request ); +} + +/** + * Ensures a REST response is a response object (for consistency). + * + * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc + * without needing to double-check the object. Will also allow WP_Error to indicate error + * responses, so users should immediately check for this value. + * + * @since 4.4.0 + * + * @param WP_Error|WP_HTTP_Response|mixed $response Response to check. + * @return mixed WP_Error if response generated an error, WP_HTTP_Response if response + * is a already an instance, otherwise returns a new WP_REST_Response instance. + */ +function rest_ensure_response( $response ) { + if ( is_wp_error( $response ) ) { + return $response; + } + + if ( $response instanceof WP_HTTP_Response ) { + return $response; + } + + return new WP_REST_Response( $response ); +} + +/** + * Handles _deprecated_function() errors. + * + * @since 4.4.0 + * + * @param string $function Function name. + * @param string $replacement Replacement function name. + * @param string $version Version. + */ +function rest_handle_deprecated_function( $function, $replacement, $version ) { + if ( ! empty( $replacement ) ) { + $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement ); + } else { + $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version ); + } + + header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) ); +} + +/** + * Handles _deprecated_argument() errors. + * + * @since 4.4.0 + * + * @param string $function Function name. + * @param string $replacement Replacement function name. + * @param string $version Version. + */ +function rest_handle_deprecated_argument( $function, $replacement, $version ) { + if ( ! empty( $replacement ) ) { + $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $replacement ); + } else { + $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version ); + } + + header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) ); +} + +/** + * Sends Cross-Origin Resource Sharing headers with API requests. + * + * @since 4.4.0 + * + * @param mixed $value Response data. + * @return mixed Response data. + */ +function rest_send_cors_headers( $value ) { + $origin = get_http_origin(); + + if ( $origin ) { + header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) ); + header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' ); + header( 'Access-Control-Allow-Credentials: true' ); + } + + return $value; +} + +/** + * Handles OPTIONS requests for the server. + * + * This is handled outside of the server code, as it doesn't obey normal route + * mapping. + * + * @since 4.4.0 + * + * @param mixed $response Current response, either response or `null` to indicate pass-through. + * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server). + * @param WP_REST_Request $request The request that was used to make current response. + * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through. + */ +function rest_handle_options_request( $response, $handler, $request ) { + if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) { + return $response; + } + + $response = new WP_REST_Response(); + $data = array(); + + $accept = array(); + + foreach ( $handler->get_routes() as $route => $endpoints ) { + $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $args ); + + if ( ! $match ) { + continue; + } + + $data = $handler->get_data_for_route( $route, $endpoints, 'help' ); + $accept = array_merge( $accept, $data['methods'] ); + break; + } + $response->header( 'Accept', implode( ', ', $accept ) ); + + $response->set_data( $data ); + return $response; +} + +/** + * Sends the "Allow" header to state all methods that can be sent to the current route. + * + * @since 4.4.0 + * + * @param WP_REST_Response $response Current response being served. + * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server). + * @param WP_REST_Request $request The request that was used to make current response. + * @return WP_REST_Response Current response being served. + */ +function rest_send_allow_header( $response, $server, $request ) { + + $matched_route = $response->get_matched_route(); + + if ( ! $matched_route ) { + return $response; + } + + $routes = $server->get_routes(); + + $allowed_methods = array(); + + // Get the allowed methods across the routes. + foreach ( $routes[ $matched_route ] as $_handler ) { + foreach ( $_handler['methods'] as $handler_method => $value ) { + + if ( ! empty( $_handler['permission_callback'] ) ) { + + $permission = call_user_func( $_handler['permission_callback'], $request ); + + $allowed_methods[ $handler_method ] = true === $permission; + } else { + $allowed_methods[ $handler_method ] = true; + } + } + } + + // Strip out all the methods that are not allowed (false values). + $allowed_methods = array_filter( $allowed_methods ); + + if ( $allowed_methods ) { + $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) ); + } + + return $response; +} + +/** + * Adds the REST API URL to the WP RSD endpoint. + * + * @since 4.4.0 + * + * @see get_rest_url() + */ +function rest_output_rsd() { + $api_root = get_rest_url(); + + if ( empty( $api_root ) ) { + return; + } + ?> + + \n"; +} + +/** + * Sends a Link header for the REST API. + * + * @since 4.4.0 + */ +function rest_output_link_header() { + if ( headers_sent() ) { + return; + } + + $api_root = get_rest_url(); + + if ( empty( $api_root ) ) { + return; + } + + header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://github.com/WP-API/WP-API"', false ); +} + +/** + * Checks for errors when using cookie-based authentication. + * + * WordPress' built-in cookie authentication is always active + * for logged in users. However, the API has to check nonces + * for each request to ensure users are not vulnerable to CSRF. + * + * @since 4.4.0 + * + * @global mixed $wp_rest_auth_cookie + * + * @param WP_Error|mixed $result Error from another authentication handler, null if we should handle it, + * or another value if not. + * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true. + */ +function rest_cookie_check_errors( $result ) { + if ( ! empty( $result ) ) { + return $result; + } + + global $wp_rest_auth_cookie; + + /* + * Is cookie authentication being used? (If we get an auth + * error, but we're still logged in, another authentication + * must have been used). + */ + if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) { + return $result; + } + + // Determine if there is a nonce. + $nonce = null; + + if ( isset( $_REQUEST['_wp_rest_nonce'] ) ) { + $nonce = $_REQUEST['_wp_rest_nonce']; + } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) { + $nonce = $_SERVER['HTTP_X_WP_NONCE']; + } + + if ( null === $nonce ) { + // No nonce at all, so act as if it's an unauthenticated request. + wp_set_current_user( 0 ); + return true; + } + + // Check the nonce. + $result = wp_verify_nonce( $nonce, 'wp_rest' ); + + if ( ! $result ) { + return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) ); + } + + return true; +} + +/** + * Collects cookie authentication status. + * + * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors. + * + * @since 4.4.0 + * + * @see current_action() + * @global mixed $wp_rest_auth_cookie + */ +function rest_cookie_collect_status() { + global $wp_rest_auth_cookie; + + $status_type = current_action(); + + if ( 'auth_cookie_valid' !== $status_type ) { + $wp_rest_auth_cookie = substr( $status_type, 12 ); + return; + } + + $wp_rest_auth_cookie = true; +} + +/** + * Parses an RFC3339 timestamp into a DateTime. + * + * @since 4.4.0 + * + * @param string $date RFC3339 timestamp. + * @param bool $force_utc Optional. Whether to force UTC timezone instead of using + * the timestamp's timezone. Default false. + * @return DateTime DateTime instance. + */ +function rest_parse_date( $date, $force_utc = false ) { + if ( $force_utc ) { + $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date ); + } + + $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#'; + + if ( ! preg_match( $regex, $date, $matches ) ) { + return false; + } + + return strtotime( $date ); +} + +/** + * Retrieves a local date with its GMT equivalent, in MySQL datetime format. + * + * @since 4.4.0 + * + * @see rest_parse_date() + * + * @param string $date RFC3339 timestamp. + * @param bool $force_utc Whether a UTC timestamp should be forced. Default false. + * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s), + * null on failure. + */ +function rest_get_date_with_gmt( $date, $force_utc = false ) { + $date = rest_parse_date( $date, $force_utc ); + + if ( empty( $date ) ) { + return null; + } + + $utc = date( 'Y-m-d H:i:s', $date ); + $local = get_date_from_gmt( $utc ); + + return array( $local, $utc ); +} diff --git a/src/wp-settings.php b/src/wp-settings.php index 26ef9885c2..55b8dae211 100644 --- a/src/wp-settings.php +++ b/src/wp-settings.php @@ -154,6 +154,7 @@ require( ABSPATH . WPINC . '/widgets.php' ); require( ABSPATH . WPINC . '/nav-menu.php' ); require( ABSPATH . WPINC . '/nav-menu-template.php' ); require( ABSPATH . WPINC . '/admin-bar.php' ); +require( ABSPATH . WPINC . '/rest-api.php' ); // Load multisite-specific files. if ( is_multisite() ) { diff --git a/tests/phpunit/includes/bootstrap.php b/tests/phpunit/includes/bootstrap.php index a33c0f8897..c65d88dec1 100644 --- a/tests/phpunit/includes/bootstrap.php +++ b/tests/phpunit/includes/bootstrap.php @@ -90,11 +90,13 @@ require_once ABSPATH . '/wp-settings.php'; _delete_all_posts(); require dirname( __FILE__ ) . '/testcase.php'; +require dirname( __FILE__ ) . '/testcase-rest-api.php'; require dirname( __FILE__ ) . '/testcase-xmlrpc.php'; require dirname( __FILE__ ) . '/testcase-ajax.php'; require dirname( __FILE__ ) . '/testcase-canonical.php'; require dirname( __FILE__ ) . '/exceptions.php'; require dirname( __FILE__ ) . '/utils.php'; +require dirname( __FILE__ ) . '/spy-rest-server.php'; /** * A child class of the PHP test runner. diff --git a/tests/phpunit/includes/spy-rest-server.php b/tests/phpunit/includes/spy-rest-server.php new file mode 100644 index 0000000000..c90ac2fcf3 --- /dev/null +++ b/tests/phpunit/includes/spy-rest-server.php @@ -0,0 +1,23 @@ +endpoints; + } + + /** + * Allow calling protected methods from tests + * + * @param string $method Method to call + * @param array $args Arguments to pass to the method + * @return mixed + */ + public function __call( $method, $args ) { + return call_user_func_array( array( $this, $method ), $args ); + } +} diff --git a/tests/phpunit/includes/testcase-rest-api.php b/tests/phpunit/includes/testcase-rest-api.php new file mode 100644 index 0000000000..c857e0e392 --- /dev/null +++ b/tests/phpunit/includes/testcase-rest-api.php @@ -0,0 +1,19 @@ +as_error(); + } + + $this->assertInstanceOf( 'WP_Error', $response ); + $this->assertEquals( $code, $response->get_error_code() ); + + if ( null !== $status ) { + $data = $response->get_error_data(); + $this->assertArrayHasKey( 'status', $data ); + $this->assertEquals( $status, $data['status'] ); + } + } +} diff --git a/tests/phpunit/tests/rest-api.php b/tests/phpunit/tests/rest-api.php new file mode 100644 index 0000000000..93e627428f --- /dev/null +++ b/tests/phpunit/tests/rest-api.php @@ -0,0 +1,255 @@ +assertTrue( class_exists( 'WP_REST_Server' ) ); + } + + /** + * The rest_api_init hook should have been registered with init, and should + * have a default priority of 10. + */ + function test_init_action_added() { + $this->assertEquals( 10, has_action( 'init', 'rest_api_init' ) ); + } + + /** + * Check that a single route is canonicalized. + * + * Ensures that single and multiple routes are handled correctly. + */ + public function test_route_canonicalized() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + ) ); + + // Check the route was registered correctly. + $endpoints = $GLOBALS['wp_rest_server']->get_raw_endpoint_data(); + $this->assertArrayHasKey( '/test-ns/test', $endpoints ); + + // Check the route was wrapped in an array. + $endpoint = $endpoints['/test-ns/test']; + $this->assertArrayNotHasKey( 'callback', $endpoint ); + $this->assertArrayHasKey( 'namespace', $endpoint ); + $this->assertEquals( 'test-ns', $endpoint['namespace'] ); + + // Grab the filtered data. + $filtered_endpoints = $GLOBALS['wp_rest_server']->get_routes(); + $this->assertArrayHasKey( '/test-ns/test', $filtered_endpoints ); + $endpoint = $filtered_endpoints['/test-ns/test']; + $this->assertCount( 1, $endpoint ); + $this->assertArrayHasKey( 'callback', $endpoint[0] ); + $this->assertArrayHasKey( 'methods', $endpoint[0] ); + $this->assertArrayHasKey( 'args', $endpoint[0] ); + } + + /** + * Check that a single route is canonicalized. + * + * Ensures that single and multiple routes are handled correctly. + */ + public function test_route_canonicalized_multiple() { + register_rest_route( 'test-ns', '/test', array( + array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + ), + array( + 'methods' => array( 'POST' ), + 'callback' => '__return_null', + ), + ) ); + + // Check the route was registered correctly. + $endpoints = $GLOBALS['wp_rest_server']->get_raw_endpoint_data(); + $this->assertArrayHasKey( '/test-ns/test', $endpoints ); + + // Check the route was wrapped in an array. + $endpoint = $endpoints['/test-ns/test']; + $this->assertArrayNotHasKey( 'callback', $endpoint ); + $this->assertArrayHasKey( 'namespace', $endpoint ); + $this->assertEquals( 'test-ns', $endpoint['namespace'] ); + + $filtered_endpoints = $GLOBALS['wp_rest_server']->get_routes(); + $endpoint = $filtered_endpoints['/test-ns/test']; + $this->assertCount( 2, $endpoint ); + + // Check for both methods. + foreach ( array( 0, 1 ) as $key ) { + $this->assertArrayHasKey( 'callback', $endpoint[ $key ] ); + $this->assertArrayHasKey( 'methods', $endpoint[ $key ] ); + $this->assertArrayHasKey( 'args', $endpoint[ $key ] ); + } + } + + /** + * Check that routes are merged by default. + */ + public function test_route_merge() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + ) ); + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'POST' ), + 'callback' => '__return_null', + ) ); + + // Check both routes exist. + $endpoints = $GLOBALS['wp_rest_server']->get_routes(); + $endpoint = $endpoints['/test-ns/test']; + $this->assertCount( 2, $endpoint ); + } + + /** + * Check that we can override routes. + */ + public function test_route_override() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + 'should_exist' => false, + ) ); + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'POST' ), + 'callback' => '__return_null', + 'should_exist' => true, + ), true ); + + // Check we only have one route. + $endpoints = $GLOBALS['wp_rest_server']->get_routes(); + $endpoint = $endpoints['/test-ns/test']; + $this->assertCount( 1, $endpoint ); + + // Check it's the right one. + $this->assertArrayHasKey( 'should_exist', $endpoint[0] ); + $this->assertTrue( $endpoint[0]['should_exist'] ); + } + + /** + * The rest_route query variable should be registered. + */ + function test_rest_route_query_var() { + rest_api_init(); + $this->assertTrue( in_array( 'rest_route', $GLOBALS['wp']->public_query_vars ) ); + } + + public function test_route_method() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + ) ); + + $routes = $GLOBALS['wp_rest_server']->get_routes(); + + $this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true ) ); + } + + /** + * The 'methods' arg should accept a single value as well as array. + */ + public function test_route_method_string() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET', + 'callback' => '__return_null', + ) ); + + $routes = $GLOBALS['wp_rest_server']->get_routes(); + + $this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true ) ); + } + + /** + * The 'methods' arg should accept a single value as well as array. + */ + public function test_route_method_array() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'GET', 'POST' ), + 'callback' => '__return_null', + ) ); + + $routes = $GLOBALS['wp_rest_server']->get_routes(); + + $this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true, 'POST' => true ) ); + } + + /** + * The 'methods' arg should a comma seperated string. + */ + public function test_route_method_comma_seperated() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET,POST', + 'callback' => '__return_null', + ) ); + + $routes = $GLOBALS['wp_rest_server']->get_routes(); + + $this->assertEquals( $routes['/test-ns/test'][0]['methods'], array( 'GET' => true, 'POST' => true ) ); + } + + public function test_options_request() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET,POST', + 'callback' => '__return_null', + ) ); + + $request = new WP_REST_Request( 'OPTIONS', '/test-ns/test' ); + $response = rest_handle_options_request( null, $GLOBALS['wp_rest_server'], $request ); + + $headers = $response->get_headers(); + $this->assertArrayHasKey( 'Accept', $headers ); + + $this->assertEquals( 'GET, POST', $headers['Accept'] ); + } + + /** + * Ensure that the OPTIONS handler doesn't kick in for non-OPTIONS requests. + */ + public function test_options_request_not_options() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET,POST', + 'callback' => '__return_true', + ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test' ); + $response = rest_handle_options_request( null, $GLOBALS['wp_rest_server'], $request ); + + $this->assertNull( $response ); + } + + /** + * The get_rest_url function should return a URL consistently terminated with a "/", + * whether the blog is configured with pretty permalink support or not. + */ + public function test_rest_url_generation() { + // In pretty permalinks case, we expect a path of wp-json/ with no query. + update_option( 'permalink_structure', '/%year%/%monthnum%/%day%/%postname%/' ); + $this->assertEquals( 'http://' . WP_TESTS_DOMAIN . '/wp-json/', get_rest_url() ); + + update_option( 'permalink_structure', '' ); + // In non-pretty case, we get a query string to invoke the rest router. + $this->assertEquals( 'http://' . WP_TESTS_DOMAIN . '/?rest_route=/', get_rest_url() ); + } +} diff --git a/tests/phpunit/tests/rest-api/rest-request.php b/tests/phpunit/tests/rest-api/rest-request.php new file mode 100644 index 0000000000..ba40892aa5 --- /dev/null +++ b/tests/phpunit/tests/rest-api/rest-request.php @@ -0,0 +1,394 @@ +request = new WP_REST_Request(); + } + + public function test_header() { + $value = 'application/x-wp-example'; + + $this->request->set_header( 'Content-Type', $value ); + + $this->assertEquals( $value, $this->request->get_header( 'Content-Type' ) ); + } + + public function test_header_missing() { + $this->assertNull( $this->request->get_header( 'missing' ) ); + $this->assertNull( $this->request->get_header_as_array( 'missing' ) ); + } + + public function test_header_multiple() { + $value1 = 'application/x-wp-example-1'; + $value2 = 'application/x-wp-example-2'; + $this->request->add_header( 'Accept', $value1 ); + $this->request->add_header( 'Accept', $value2 ); + + $this->assertEquals( $value1 . ',' . $value2, $this->request->get_header( 'Accept' ) ); + $this->assertEquals( array( $value1, $value2 ), $this->request->get_header_as_array( 'Accept' ) ); + } + + public static function header_provider() { + return array( + array( 'Test', 'test' ), + array( 'TEST', 'test' ), + array( 'Test-Header', 'test_header' ), + array( 'test-header', 'test_header' ), + array( 'Test_Header', 'test_header' ), + array( 'test_header', 'test_header' ), + ); + } + + /** + * @dataProvider header_provider + * @param string $original Original header key. + * @param string $expected Expected canonicalized version. + */ + public function test_header_canonicalization( $original, $expected ) { + $this->assertEquals( $expected, $this->request->canonicalize_header_name( $original ) ); + } + + public static function content_type_provider() { + return array( + // Check basic parsing. + array( 'application/x-wp-example', 'application/x-wp-example', 'application', 'x-wp-example', '' ), + array( 'application/x-wp-example; charset=utf-8', 'application/x-wp-example', 'application', 'x-wp-example', 'charset=utf-8' ), + + // Check case insensitivity. + array( 'APPLICATION/x-WP-Example', 'application/x-wp-example', 'application', 'x-wp-example', '' ), + ); + } + + /** + * @dataProvider content_type_provider + * + * @param string $header Header value. + * @param string $value Full type value. + * @param string $type Main type (application, text, etc). + * @param string $subtype Subtype (json, etc). + * @param string $parameters Parameters (charset=utf-8, etc). + */ + public function test_content_type_parsing( $header, $value, $type, $subtype, $parameters ) { + // Check we start with nothing. + $this->assertEmpty( $this->request->get_content_type() ); + + $this->request->set_header( 'Content-Type', $header ); + $parsed = $this->request->get_content_type(); + + $this->assertEquals( $value, $parsed['value'] ); + $this->assertEquals( $type, $parsed['type'] ); + $this->assertEquals( $subtype, $parsed['subtype'] ); + $this->assertEquals( $parameters, $parsed['parameters'] ); + } + + protected function request_with_parameters() { + $this->request->set_url_params( array( + 'source' => 'url', + 'has_url_params' => true, + ) ); + $this->request->set_query_params( array( + 'source' => 'query', + 'has_query_params' => true, + ) ); + $this->request->set_body_params( array( + 'source' => 'body', + 'has_body_params' => true, + ) ); + + $json_data = wp_json_encode( array( + 'source' => 'json', + 'has_json_params' => true, + ) ); + $this->request->set_body( $json_data ); + + $this->request->set_default_params( array( + 'source' => 'defaults', + 'has_default_params' => true, + ) ); + } + + public function test_parameter_order() { + $this->request_with_parameters(); + + $this->request->set_method( 'GET' ); + + // Check that query takes precedence. + $this->assertEquals( 'query', $this->request->get_param( 'source' ) ); + + // Check that the correct arguments are parsed (and that falling through + // the stack works). + $this->assertTrue( $this->request->get_param( 'has_url_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_query_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_default_params' ) ); + + // POST and JSON parameters shouldn't be parsed. + $this->assertEmpty( $this->request->get_param( 'has_body_params' ) ); + $this->assertEmpty( $this->request->get_param( 'has_json_params' ) ); + } + + public function test_parameter_order_post() { + $this->request_with_parameters(); + + $this->request->set_method( 'POST' ); + $this->request->set_header( 'Content-Type', 'application/x-www-form-urlencoded' ); + $this->request->set_attributes( array( 'accept_json' => true ) ); + + // Check that POST takes precedence. + $this->assertEquals( 'body', $this->request->get_param( 'source' ) ); + + // Check that the correct arguments are parsed (and that falling through + // the stack works). + $this->assertTrue( $this->request->get_param( 'has_url_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_query_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_body_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_default_params' ) ); + + // JSON shouldn't be parsed. + $this->assertEmpty( $this->request->get_param( 'has_json_params' ) ); + } + + public function test_parameter_order_json() { + $this->request_with_parameters(); + + $this->request->set_method( 'POST' ); + $this->request->set_header( 'Content-Type', 'application/json' ); + $this->request->set_attributes( array( 'accept_json' => true ) ); + + // Check that JSON takes precedence. + $this->assertEquals( 'json', $this->request->get_param( 'source' ) ); + + // Check that the correct arguments are parsed (and that falling through + // the stack works). + $this->assertTrue( $this->request->get_param( 'has_url_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_query_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_body_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_json_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_default_params' ) ); + } + + public function test_parameter_order_json_invalid() { + $this->request_with_parameters(); + + $this->request->set_method( 'POST' ); + $this->request->set_header( 'Content-Type', 'application/json' ); + $this->request->set_attributes( array( 'accept_json' => true ) ); + + // Use invalid JSON data. + $this->request->set_body( '{ this is not json }' ); + + // Check that JSON is ignored. + $this->assertEquals( 'body', $this->request->get_param( 'source' ) ); + + // Check that the correct arguments are parsed (and that falling through + // the stack works). + $this->assertTrue( $this->request->get_param( 'has_url_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_query_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_body_params' ) ); + $this->assertTrue( $this->request->get_param( 'has_default_params' ) ); + + // JSON should be ignored. + $this->assertEmpty( $this->request->get_param( 'has_json_params' ) ); + } + + /** + * PUT requests don't get $_POST automatically parsed, so ensure that + * WP_REST_Request does it for us. + */ + public function test_parameters_for_put() { + $data = array( + 'foo' => 'bar', + 'alot' => array( + 'of' => 'parameters', + ), + 'list' => array( + 'of', + 'cool', + 'stuff', + ), + ); + + $this->request->set_method( 'PUT' ); + $this->request->set_body_params( array() ); + $this->request->set_body( http_build_query( $data ) ); + + foreach ( $data as $key => $expected_value ) { + $this->assertEquals( $expected_value, $this->request->get_param( $key ) ); + } + } + + public function test_parameters_for_json_put() { + $data = array( + 'foo' => 'bar', + 'alot' => array( + 'of' => 'parameters', + ), + 'list' => array( + 'of', + 'cool', + 'stuff', + ), + ); + + $this->request->set_method( 'PUT' ); + $this->request->add_header( 'content-type', 'application/json' ); + $this->request->set_body( wp_json_encode( $data ) ); + + foreach ( $data as $key => $expected_value ) { + $this->assertEquals( $expected_value, $this->request->get_param( $key ) ); + } + } + + public function test_parameters_for_json_post() { + $data = array( + 'foo' => 'bar', + 'alot' => array( + 'of' => 'parameters', + ), + 'list' => array( + 'of', + 'cool', + 'stuff', + ), + ); + + $this->request->set_method( 'POST' ); + $this->request->add_header( 'content-type', 'application/json' ); + $this->request->set_body( wp_json_encode( $data ) ); + + foreach ( $data as $key => $expected_value ) { + $this->assertEquals( $expected_value, $this->request->get_param( $key ) ); + } + } + + public function test_parameter_merging() { + $this->request_with_parameters(); + + $this->request->set_method( 'POST' ); + + $expected = array( + 'source' => 'body', + 'has_url_params' => true, + 'has_query_params' => true, + 'has_body_params' => true, + 'has_default_params' => true, + ); + $this->assertEquals( $expected, $this->request->get_params() ); + } + + public function test_sanitize_params() { + $this->request->set_url_params( array( + 'someinteger' => '123', + 'somestring' => 'hello', + )); + + $this->request->set_attributes( array( + 'args' => array( + 'someinteger' => array( + 'sanitize_callback' => 'absint', + ), + 'somestring' => array( + 'sanitize_callback' => 'absint', + ), + ), + ) ); + + $this->request->sanitize_params(); + + $this->assertEquals( 123, $this->request->get_param( 'someinteger' ) ); + $this->assertEquals( 0, $this->request->get_param( 'somestring' ) ); + } + + public function test_has_valid_params_required_flag() { + $this->request->set_attributes( array( + 'args' => array( + 'someinteger' => array( + 'required' => true, + ), + ), + ) ); + + $valid = $this->request->has_valid_params(); + + $this->assertWPError( $valid ); + $this->assertEquals( 'rest_missing_callback_param', $valid->get_error_code() ); + } + + public function test_has_valid_params_required_flag_multiple() { + $this->request->set_attributes( array( + 'args' => array( + 'someinteger' => array( + 'required' => true, + ), + 'someotherinteger' => array( + 'required' => true, + ), + ), + )); + + $valid = $this->request->has_valid_params(); + + $this->assertWPError( $valid ); + $this->assertEquals( 'rest_missing_callback_param', $valid->get_error_code() ); + + $data = $valid->get_error_data( 'rest_missing_callback_param' ); + + $this->assertTrue( in_array( 'someinteger', $data['params'] ) ); + $this->assertTrue( in_array( 'someotherinteger', $data['params'] ) ); + } + + public function test_has_valid_params_validate_callback() { + $this->request->set_url_params( array( + 'someinteger' => '123', + )); + + $this->request->set_attributes( array( + 'args' => array( + 'someinteger' => array( + 'validate_callback' => '__return_false', + ), + ), + )); + + $valid = $this->request->has_valid_params(); + + $this->assertWPError( $valid ); + $this->assertEquals( 'rest_invalid_param', $valid->get_error_code() ); + } + + public function test_has_multiple_invalid_params_validate_callback() { + $this->request->set_url_params( array( + 'someinteger' => '123', + 'someotherinteger' => '123', + )); + + $this->request->set_attributes( array( + 'args' => array( + 'someinteger' => array( + 'validate_callback' => '__return_false', + ), + 'someotherinteger' => array( + 'validate_callback' => '__return_false', + ), + ), + )); + + $valid = $this->request->has_valid_params(); + + $this->assertWPError( $valid ); + $this->assertEquals( 'rest_invalid_param', $valid->get_error_code() ); + + $data = $valid->get_error_data( 'rest_invalid_param' ); + + $this->assertArrayHasKey( 'someinteger', $data['params'] ); + $this->assertArrayHasKey( 'someotherinteger', $data['params'] ); + } +} diff --git a/tests/phpunit/tests/rest-api/rest-server.php b/tests/phpunit/tests/rest-api/rest-server.php new file mode 100644 index 0000000000..b49b5c6eed --- /dev/null +++ b/tests/phpunit/tests/rest-api/rest-server.php @@ -0,0 +1,582 @@ +server = $wp_rest_server = new Spy_REST_Server(); + + do_action( 'rest_api_init', $this->server ); + } + + public function test_envelope() { + $data = array( + 'amount of arbitrary data' => 'alot', + ); + $status = 987; + $headers = array( + 'Arbitrary-Header' => 'value', + 'Multiple' => 'maybe, yes', + ); + + $response = new WP_REST_Response( $data, $status ); + $response->header( 'Arbitrary-Header', 'value' ); + + // Check header concatenation as well. + $response->header( 'Multiple', 'maybe' ); + $response->header( 'Multiple', 'yes', false ); + + $envelope_response = $this->server->envelope_response( $response, false ); + + // The envelope should still be a response, but with defaults. + $this->assertInstanceOf( 'WP_REST_Response', $envelope_response ); + $this->assertEquals( 200, $envelope_response->get_status() ); + $this->assertEmpty( $envelope_response->get_headers() ); + $this->assertEmpty( $envelope_response->get_links() ); + + $enveloped = $envelope_response->get_data(); + + $this->assertEquals( $data, $enveloped['body'] ); + $this->assertEquals( $status, $enveloped['status'] ); + $this->assertEquals( $headers, $enveloped['headers'] ); + } + + public function test_default_param() { + + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + 'args' => array( + 'foo' => array( + 'default' => 'bar', + ), + ), + ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test' ); + $response = $this->server->dispatch( $request ); + + $this->assertEquals( 'bar', $request['foo'] ); + } + + public function test_default_param_is_overridden() { + + register_rest_route( 'test-ns', '/test', array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + 'args' => array( + 'foo' => array( + 'default' => 'bar', + ), + ), + ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test' ); + $request->set_query_params( array( 'foo' => 123 ) ); + $response = $this->server->dispatch( $request ); + + $this->assertEquals( '123', $request['foo'] ); + } + + public function test_optional_param() { + register_rest_route( 'optional', '/test', array( + 'methods' => array( 'GET' ), + 'callback' => '__return_null', + 'args' => array( + 'foo' => array(), + ), + ) ); + + $request = new WP_REST_Request( 'GET', '/optional/test' ); + $request->set_query_params( array() ); + $response = $this->server->dispatch( $request ); + $this->assertInstanceOf( 'WP_REST_Response', $response ); + $this->assertEquals( 200, $response->get_status() ); + $this->assertArrayNotHasKey( 'foo', (array) $request ); + } + + /** + * Pass a capability which the user does not have, this should + * result in a 403 error. + */ + function test_rest_route_capability_authorization_fails() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET', + 'callback' => '__return_null', + 'should_exist' => false, + 'permission_callback' => array( $this, 'permission_denied' ), + ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test', array() ); + $result = $this->server->dispatch( $request ); + + $this->assertEquals( 403, $result->get_status() ); + } + + /** + * An editor should be able to get access to an route with the + * edit_posts capability. + */ + function test_rest_route_capability_authorization() { + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET', + 'callback' => '__return_null', + 'should_exist' => false, + 'permission_callback' => '__return_true', + ) ); + + $editor = $this->factory->user->create( array( 'role' => 'editor' ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test', array() ); + + wp_set_current_user( $editor ); + + $result = $this->server->dispatch( $request ); + + $this->assertEquals( 200, $result->get_status() ); + } + + /** + * An "Allow" HTTP header should be sent with a request + * for all available methods on that route. + */ + function test_allow_header_sent() { + + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET', + 'callback' => '__return_null', + 'should_exist' => false, + ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test', array() ); + + $result = $this->server->dispatch( $request ); + $result = apply_filters( 'rest_post_dispatch', $result, $this->server, $request ); + + $this->assertFalse( $result->get_status() !== 200 ); + + $sent_headers = $result->get_headers(); + $this->assertEquals( $sent_headers['Allow'], 'GET' ); + } + + /** + * The "Allow" HTTP header should include all available + * methods that can be sent to a route. + */ + function test_allow_header_sent_with_multiple_methods() { + + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET', + 'callback' => '__return_null', + 'should_exist' => false, + ) ); + + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'POST', + 'callback' => '__return_null', + 'should_exist' => false, + ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test', array() ); + + $result = $this->server->dispatch( $request ); + + $this->assertFalse( $result->get_status() !== 200 ); + + $result = apply_filters( 'rest_post_dispatch', $result, $this->server, $request ); + + $sent_headers = $result->get_headers(); + $this->assertEquals( $sent_headers['Allow'], 'GET, POST' ); + } + + /** + * The "Allow" HTTP header should NOT include other methods + * which the user does not have access to. + */ + function test_allow_header_send_only_permitted_methods() { + + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'GET', + 'callback' => '__return_null', + 'should_exist' => false, + 'permission_callback' => array( $this, 'permission_denied' ), + ) ); + + register_rest_route( 'test-ns', '/test', array( + 'methods' => 'POST', + 'callback' => '__return_null', + 'should_exist' => false, + ) ); + + $request = new WP_REST_Request( 'GET', '/test-ns/test', array() ); + + $result = $this->server->dispatch( $request ); + $result = apply_filters( 'rest_post_dispatch', $result, $this->server, $request ); + + $this->assertEquals( $result->get_status(), 403 ); + + $sent_headers = $result->get_headers(); + $this->assertEquals( $sent_headers['Allow'], 'POST' ); + } + + public function permission_denied() { + return new WP_Error( 'forbidden', 'You are not allowed to do this', array( 'status' => 403 ) ); + } + + public function test_error_to_response() { + $code = 'wp-api-test-error'; + $message = 'Test error message for the API'; + $error = new WP_Error( $code, $message ); + + $response = $this->server->error_to_response( $error ); + $this->assertInstanceOf( 'WP_REST_Response', $response ); + + // Make sure we default to a 500 error. + $this->assertEquals( 500, $response->get_status() ); + + $data = $response->get_data(); + $this->assertCount( 1, $data ); + + $this->assertEquals( $code, $data[0]['code'] ); + $this->assertEquals( $message, $data[0]['message'] ); + } + + public function test_error_to_response_with_status() { + $code = 'wp-api-test-error'; + $message = 'Test error message for the API'; + $error = new WP_Error( $code, $message, array( 'status' => 400 ) ); + + $response = $this->server->error_to_response( $error ); + $this->assertInstanceOf( 'WP_REST_Response', $response ); + + $this->assertEquals( 400, $response->get_status() ); + + $data = $response->get_data(); + $this->assertCount( 1, $data ); + + $this->assertEquals( $code, $data[0]['code'] ); + $this->assertEquals( $message, $data[0]['message'] ); + } + + public function test_rest_error() { + $data = array( + array( + 'code' => 'wp-api-test-error', + 'message' => 'Message text', + ), + ); + $expected = wp_json_encode( $data ); + $response = $this->server->json_error( 'wp-api-test-error', 'Message text' ); + + $this->assertEquals( $expected, $response ); + } + + public function test_json_error_with_status() { + $stub = $this->getMockBuilder( 'Spy_REST_Server' ) + ->setMethods( array( 'set_status' ) ) + ->getMock(); + + $stub->expects( $this->once() ) + ->method( 'set_status' ) + ->with( $this->equalTo( 400 ) ); + + $data = array( + array( + 'code' => 'wp-api-test-error', + 'message' => 'Message text', + ), + ); + $expected = wp_json_encode( $data ); + + $response = $stub->json_error( 'wp-api-test-error', 'Message text', 400 ); + + $this->assertEquals( $expected, $response ); + } + + public function test_response_to_data_links() { + $response = new WP_REST_Response(); + $response->add_link( 'self', 'http://example.com/' ); + $response->add_link( 'alternate', 'http://example.org/', array( 'type' => 'application/xml' ) ); + + $data = $this->server->response_to_data( $response, false ); + $this->assertArrayHasKey( '_links', $data ); + + $self = array( + 'href' => 'http://example.com/', + ); + $this->assertEquals( $self, $data['_links']['self'][0] ); + + $alternate = array( + 'href' => 'http://example.org/', + 'type' => 'application/xml', + ); + $this->assertEquals( $alternate, $data['_links']['alternate'][0] ); + } + + public function test_link_embedding() { + // Register our testing route. + $this->server->register_route( 'test', '/test/embeddable', array( + 'methods' => 'GET', + 'callback' => array( $this, 'embedded_response_callback' ), + ) ); + $response = new WP_REST_Response(); + + // External links should be ignored. + $response->add_link( 'alternate', 'http://not-api.example.com/', array( 'embeddable' => true ) ); + + // All others should be embedded. + $response->add_link( 'alternate', rest_url( '/test/embeddable' ), array( 'embeddable' => true ) ); + + $data = $this->server->response_to_data( $response, true ); + $this->assertArrayHasKey( '_embedded', $data ); + + $alternate = $data['_embedded']['alternate']; + $this->assertCount( 2, $alternate ); + $this->assertEmpty( $alternate[0] ); + + $this->assertInternalType( 'array', $alternate[1] ); + $this->assertArrayNotHasKey( 'code', $alternate[1] ); + $this->assertTrue( $alternate[1]['hello'] ); + + // Ensure the context is set to embed when requesting. + $this->assertEquals( 'embed', $alternate[1]['parameters']['context'] ); + } + + /** + * @depends test_link_embedding + */ + public function test_link_embedding_self() { + // Register our testing route. + $this->server->register_route( 'test', '/test/embeddable', array( + 'methods' => 'GET', + 'callback' => array( $this, 'embedded_response_callback' ), + ) ); + $response = new WP_REST_Response(); + + // 'self' should be ignored. + $response->add_link( 'self', rest_url( '/test/notembeddable' ), array( 'embeddable' => true ) ); + + $data = $this->server->response_to_data( $response, true ); + + $this->assertArrayNotHasKey( '_embedded', $data ); + } + + /** + * @depends test_link_embedding + */ + public function test_link_embedding_params() { + // Register our testing route. + $this->server->register_route( 'test', '/test/embeddable', array( + 'methods' => 'GET', + 'callback' => array( $this, 'embedded_response_callback' ), + ) ); + + $response = new WP_REST_Response(); + $response->add_link( 'alternate', rest_url( '/test/embeddable?parsed_params=yes' ), array( 'embeddable' => true ) ); + + $data = $this->server->response_to_data( $response, true ); + + $this->assertArrayHasKey( '_embedded', $data ); + $this->assertArrayHasKey( 'alternate', $data['_embedded'] ); + $data = $data['_embedded']['alternate'][0]; + + $this->assertEquals( 'yes', $data['parameters']['parsed_params'] ); + } + + /** + * @depends test_link_embedding_params + */ + public function test_link_embedding_error() { + // Register our testing route. + $this->server->register_route( 'test', '/test/embeddable', array( + 'methods' => 'GET', + 'callback' => array( $this, 'embedded_response_callback' ), + ) ); + + $response = new WP_REST_Response(); + $response->add_link( 'up', rest_url( '/test/embeddable?error=1' ), array( 'embeddable' => true ) ); + + $data = $this->server->response_to_data( $response, true ); + + $this->assertArrayHasKey( '_embedded', $data ); + $this->assertArrayHasKey( 'up', $data['_embedded'] ); + + // Check that errors are embedded correctly. + $up = $data['_embedded']['up']; + $this->assertCount( 1, $up ); + + $up_data = $up[0]; + $this->assertEquals( 'wp-api-test-error', $up_data[0]['code'] ); + $this->assertEquals( 'Test message', $up_data[0]['message'] ); + $this->assertEquals( 403, $up_data[0]['data']['status'] ); + } + + /** + * Ensure embedding is a no-op without links in the data. + */ + public function test_link_embedding_without_links() { + $data = array( + 'untouched' => 'data', + ); + $result = $this->server->embed_links( $data ); + + $this->assertArrayNotHasKey( '_links', $data ); + $this->assertArrayNotHasKey( '_embedded', $data ); + $this->assertEquals( 'data', $data['untouched'] ); + } + + public function embedded_response_callback( $request ) { + $params = $request->get_params(); + + if ( isset( $params['error'] ) ) { + return new WP_Error( 'wp-api-test-error', 'Test message', array( 'status' => 403 ) ); + } + + $data = array( + 'hello' => true, + 'parameters' => $params, + ); + + return $data; + } + + public function test_removing_links() { + $response = new WP_REST_Response(); + $response->add_link( 'self', 'http://example.com/' ); + $response->add_link( 'alternate', 'http://example.org/', array( 'type' => 'application/xml' ) ); + + $response->remove_link( 'self' ); + + $data = $this->server->response_to_data( $response, false ); + $this->assertArrayHasKey( '_links', $data ); + + $this->assertArrayNotHasKey( 'self', $data['_links'] ); + + $alternate = array( + 'href' => 'http://example.org/', + 'type' => 'application/xml', + ); + $this->assertEquals( $alternate, $data['_links']['alternate'][0] ); + } + + public function test_removing_links_for_href() { + $response = new WP_REST_Response(); + $response->add_link( 'self', 'http://example.com/' ); + $response->add_link( 'self', 'https://example.com/' ); + + $response->remove_link( 'self', 'https://example.com/' ); + + $data = $this->server->response_to_data( $response, false ); + $this->assertArrayHasKey( '_links', $data ); + + $this->assertArrayHasKey( 'self', $data['_links'] ); + + $self_not_filtered = array( + 'href' => 'http://example.com/', + ); + $this->assertEquals( $self_not_filtered, $data['_links']['self'][0] ); + } + + public function test_get_index() { + $server = new WP_REST_Server(); + $server->register_route( 'test/example', '/test/example/some-route', array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => '__return_true', + ), + array( + 'methods' => WP_REST_Server::DELETABLE, + 'callback' => '__return_true', + ), + ) ); + + $request = new WP_REST_Request( 'GET', '/' ); + $index = $server->dispatch( $request ); + $data = $index->get_data(); + + $this->assertArrayHasKey( 'name', $data ); + $this->assertArrayHasKey( 'description', $data ); + $this->assertArrayHasKey( 'url', $data ); + $this->assertArrayHasKey( 'namespaces', $data ); + $this->assertArrayHasKey( 'authentication', $data ); + $this->assertArrayHasKey( 'routes', $data ); + + // Check namespace data. + $this->assertContains( 'test/example', $data['namespaces'] ); + + // Check the route. + $this->assertArrayHasKey( '/test/example/some-route', $data['routes'] ); + $route = $data['routes']['/test/example/some-route']; + $this->assertEquals( 'test/example', $route['namespace'] ); + $this->assertArrayHasKey( 'methods', $route ); + $this->assertContains( 'GET', $route['methods'] ); + $this->assertContains( 'DELETE', $route['methods'] ); + $this->assertArrayHasKey( '_links', $route ); + } + + public function test_get_namespace_index() { + $server = new WP_REST_Server(); + $server->register_route( 'test/example', '/test/example/some-route', array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => '__return_true', + ), + array( + 'methods' => WP_REST_Server::DELETABLE, + 'callback' => '__return_true', + ), + ) ); + $server->register_route( 'test/another', '/test/another/route', array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => '__return_false', + ), + ) ); + + $request = new WP_REST_Request(); + $request->set_param( 'namespace', 'test/example' ); + $index = rest_ensure_response( $server->get_namespace_index( $request ) ); + $data = $index->get_data(); + + // Check top-level. + $this->assertEquals( 'test/example', $data['namespace'] ); + $this->assertArrayHasKey( 'routes', $data ); + + // Check we have the route we expect... + $this->assertArrayHasKey( '/test/example/some-route', $data['routes'] ); + + // ...and none we don't. + $this->assertArrayNotHasKey( '/test/another/route', $data['routes'] ); + } + + public function test_get_namespaces() { + $server = new WP_REST_Server(); + $server->register_route( 'test/example', '/test/example/some-route', array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => '__return_true', + ), + ) ); + $server->register_route( 'test/another', '/test/another/route', array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => '__return_false', + ), + ) ); + + $namespaces = $server->get_namespaces(); + $this->assertContains( 'test/example', $namespaces ); + $this->assertContains( 'test/another', $namespaces ); + } +}