haracteristics.
* These annotations are hints for tooling and documentation.
*
* @type bool|null $readonly Optional. If true, the ability does not modify its environment.
* @type bool|null $destructive Optional. If true, the ability may perform destructive updates to its environment.
* If false, the ability performs only additive updates.
* @type bool|null $idempotent Optional. If true, calling the ability repeatedly with the same arguments
* will have no additional effect on its environment.
* }
* @type bool $public Optional. Whether the ability is meant to be available
* to clients such as the REST API, MCP, or AI agents.
* Seeds the default for per-channel flags like
* `$show_in_rest`. Defaults to false.
* @type bool $show_in_rest Optional. Whether to expose this ability in the REST API.
* Default is the value of `$public` when set, false otherwise.
* }
* }
*/
public function __construct( string $name, array $args ) {
$this->name = $name;
$properties = $this->prepare_properties( $args );
foreach ( $properties as $property_name => $property_value ) {
if ( ! property_exists( $this, $property_name ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: %s: Property name. */
__( 'Property "%1$s" is not a valid property for ability "%2$s". Please check the %3$s class for allowed properties.' ),
'' . esc_html( $property_name ) . '',
'' . esc_html( $this->name ) . '',
'' . __CLASS__ . ''
),
'6.9.0'
);
continue;
}
$this->$property_name = $property_value;
}
}
/**
* Prepares and validates the properties used to instantiate the ability.
*
* Errors are thrown as exceptions instead of WP_Errors to allow for simpler handling and overloading. They are then
* caught and converted to a WP_Error by WP_Abilities_Registry::register().
*
* @since 6.9.0
*
* @see WP_Abilities_Registry::register()
*
* @param array $args {
* An associative array of arguments used to instantiate the ability class.
*
* @type string $label The human-readable label for the ability.
* @type string $description A detailed description of what the ability does.
* @type string $category The ability category slug this ability belongs to.
* @type callable $execute_callback A callback function to execute when the ability is invoked.
* Receives optional mixed input and returns mixed result or WP_Error.
* @type callable $permission_callback A callback function to check permissions before execution.
* Receives optional mixed input and returns bool or WP_Error.
* @type array $input_schema Optional. JSON Schema definition for the ability's input. Required if ability accepts an input.
* @type array $output_schema Optional. JSON Schema definition for the ability's output.
* @type array $meta {
* Optional. Additional metadata for the ability.
*
* @type array $annotations {
* Optional. Semantic annotations describing the ability's behavioral characteristics.
* These annotations are hints for tooling and documentation.
*
* @type bool|null $readonly Optional. If true, the ability does not modify its environment.
* @type bool|null $destructive Optional. If true, the ability may perform destructive updates to its environment.
* If false, the ability performs only additive updates.
* @type bool|null $idempotent Optional. If true, calling the ability repeatedly with the same arguments
* will have no additional effect on its environment.
* }
* @type bool $public Optional. Whether the ability is meant to be available
* to clients such as the REST API, MCP, or AI agents.
* Seeds the default for per-channel flags like
* `$show_in_rest`. Defaults to false.
* @type bool $show_in_rest Optional. Whether to expose this ability in the REST API.
* Default is the value of `$public` when set, false otherwise.
* }
* }
* @return array {
* An associative array of arguments with validated and prepared properties for the ability class.
*
* @type string $label The human-readable label for the ability.
* @type string $description A detailed description of what the ability does.
* @type string $category The ability category slug this ability belongs to.
* @type callable $execute_callback A callback function to execute when the ability is invoked.
* Receives optional mixed input and returns mixed result or WP_Error.
* @type callable $permission_callback A callback function to check permissions before execution.
* Receives optional mixed input and returns bool or WP_Error.
* @type array $input_schema Optional. JSON Schema definition for the ability's input.
* @type array $output_schema Optional. JSON Schema definition for the ability's output.
* @type array $meta {
* Additional metadata for the ability.
*
* @type array $annotations {
* Semantic annotations describing the ability's behavioral characteristics.
* These annotations are hints for tooling and documentation.
*
* @type bool|null $readonly If true, the ability does not modify its environment.
* @type bool|null $destructive If true, the ability may perform destructive updates to its environment.
* If false, the ability performs only additive updates.
* @type bool|null $idempotent If true, calling the ability repeatedly with the same arguments
* will have no additional effect on its environment.
* }
* @type bool $public Whether the ability is meant to be available to clients
* such as the REST API, MCP, or AI agents. Defaults to
* false.
* @type bool $show_in_rest Whether to expose this ability in the REST API.
* }
* }
* @throws InvalidArgumentException if an argument is invalid.
*/
protected function prepare_properties( array $args ): array {
// Required args must be present and of the correct type.
if ( empty( $args['label'] ) || ! is_string( $args['label'] ) ) {
throw new InvalidArgumentException(
__( 'The ability properties must contain a `label` string.' )
);
}
if ( empty( $args['description'] ) || ! is_string( $args['description'] ) ) {
throw new InvalidArgumentException(
__( 'The ability properties must contain a `description` string.' )
);
}
if ( empty( $args['category'] ) || ! is_string( $args['category'] ) ) {
throw new InvalidArgumentException(
__( 'The ability properties must contain a `category` string.' )
);
}
// If we are not overriding `ability_class` parameter during instantiation, then we need to validate the execute_callback.
if ( get_class( $this ) === self::class && ( empty( $args['execute_callback'] ) || ! is_callable( $args['execute_callback'] ) ) ) {
throw new InvalidArgumentException(
__( 'The ability properties must contain a valid `execute_callback` function.' )
);
}
// If we are not overriding `ability_class` parameter during instantiation, then we need to validate the permission_callback.
if ( get_class( $this ) === self::class && ( empty( $args['permission_callback'] ) || ! is_callable( $args['permission_callback'] ) ) ) {
throw new InvalidArgumentException(
__( 'The ability properties must provide a valid `permission_callback` function.' )
);
}
// Optional args only need to be of the correct type if they are present.
if ( isset( $args['input_schema'] ) && ! is_array( $args['input_schema'] ) ) {
throw new InvalidArgumentException(
__( 'The ability properties should provide a valid `input_schema` definition.' )
);
}
if ( isset( $args['output_schema'] ) && ! is_array( $args['output_schema'] ) ) {
throw new InvalidArgumentException(
__( 'The ability properties should provide a valid `output_schema` definition.' )
);
}
if ( isset( $args['meta'] ) && ! is_array( $args['meta'] ) ) {
throw new InvalidArgumentException(
__( 'The ability properties should provide a valid `meta` array.' )
);
}
if ( isset( $args['meta']['annotations'] ) && ! is_array( $args['meta']['annotations'] ) ) {
throw new InvalidArgumentException(
__( 'The ability meta should provide a valid `annotations` array.' )
);
}
if ( isset( $args['meta']['show_in_rest'] ) && ! is_bool( $args['meta']['show_in_rest'] ) ) {
throw new InvalidArgumentException(
__( 'The ability meta should provide a valid `show_in_rest` boolean.' )
);
}
if ( isset( $args['meta']['public'] ) && ! is_bool( $args['meta']['public'] ) ) {
throw new InvalidArgumentException(
__( 'The ability meta should provide a valid `public` boolean.' )
);
}
// Set defaults for optional meta.
$args['meta'] = wp_parse_args(
$args['meta'] ?? array(),
array(
'annotations' => static::$default_annotations,
)
);
$args['meta']['annotations'] = wp_parse_args(
$args['meta']['annotations'],
static::$default_annotations
);
/*
* Resolve `show_in_rest` from most specific to least specific: an explicit
* `show_in_rest` value wins, then the high-level `public` flag seeds the
* default, then the built-in default applies.
*/
$args['meta']['show_in_rest'] = $args['meta']['show_in_rest'] ?? $args['meta']['public'] ?? self::DEFAULT_SHOW_IN_REST;
$args['meta']['public'] = $args['meta']['public'] ?? self::DEFAULT_PUBLIC;
return $args;
}
/**
* Retrieves the name of the ability, with its namespace.
* Example: `my-plugin/my-ability`.
*
* @since 6.9.0
*
* @return string The ability name, with its namespace.
*/
public function get_name(): string {
return $this->name;
}
/**
* Retrieves the human-readable label for the ability.
*
* @since 6.9.0
*
* @return string The human-readable ability label.
*/
public function get_label(): string {
return $this->label;
}
/**
* Retrieves the detailed description for the ability.
*
* @since 6.9.0
*
* @return string The detailed description for the ability.
*/
public function get_description(): string {
return $this->description;
}
/**
* Retrieves the ability category for the ability.
*
* @since 6.9.0
*
* @return string The ability category for the ability.
*/
public function get_category(): string {
return $this->category;
}
/**
* Retrieves the input schema for the ability.
*
* @since 6.9.0
*
* @return array The input schema for the ability.
*/
public function get_input_schema(): array {
return $this->input_schema;
}
/**
* Retrieves the output schema for the ability.
*
* @since 6.9.0
*
* @return array The output schema for the ability.
*/
public function get_output_schema(): array {
return $this->output_schema;
}
/**
* Retrieves the metadata for the ability.
*
* @since 6.9.0
*
* @return array The metadata for the ability.
*/
public function get_meta(): array {
return $this->meta;
}
/**
* Retrieves a specific metadata item for the ability.
*
* @since 6.9.0
*
* @param string $key The metadata key to retrieve.
* @param mixed $default_value Optional. The default value to return if the metadata item is not found. Default `null`.
* @return mixed The value of the metadata item, or the default value if not found.
*/
public function get_meta_item( string $key, $default_value = null ) {
return array_key_exists( $key, $this->meta ) ? $this->meta[ $key ] : $default_value;
}
/**
* Normalizes the input for the ability, applying the default value from the input schema when needed.
*
* When no input is provided and the input schema is defined with a top-level `default` key, this method returns
* the value of that key. If the input schema does not define a `default`, or if the input schema is empty,
* this method returns null. If input is provided, it is returned as-is.
*
* The {@see 'wp_ability_normalize_input'} filter fires after the built-in default-value handling,
* allowing plugins to transform the result.
*
* @since 6.9.0
* @since 7.1.0 Added the `wp_ability_normalize_input` filter.
*
* @param mixed $input Optional. The raw input provided for the ability. Default `null`.
* @return mixed The normalized input, or a `WP_Error` if a filter returned one.
*/
public function normalize_input( $input = null ) {
if ( null === $input ) {
$input_schema = $this->get_input_schema();
if ( array_key_exists( 'default', $input_schema ) ) {
$input = $input_schema['default'];
}
}
/**
* Filters the normalized input for an ability.
*
* Fires after `normalize_input()` has applied any default value declared in the input schema,
* giving plugins a chance to adjust the input before it is consumed downstream. Common uses
* include defaulting beyond what JSON Schema can express, prompt enrichment, and injecting
* caller metadata.
*
* Returning a `WP_Error` causes callers that propagate it (such as `execute()`) to halt
* before validation, permission checks, and the registered execute callback.
*
* @since 7.1.0
*
* @param mixed $input The normalized input data.
* @param string $ability_name The name of the ability.
* @param WP_Ability $ability The ability instance.
*/
return apply_filters( 'wp_ability_normalize_input', $input, $this->name, $this );
}
/**
* Validates input data against the input schema.
*
* @since 6.9.0
*
* @param mixed $input Optional. The input data to validate. Default `null`.
* @return true|WP_Error Returns true if valid or the WP_Error object if validation fails.
*/
public function validate_input( $input = null ) {
$input_schema = $this->get_input_schema();
if ( empty( $input_schema ) ) {
if ( null === $input ) {
return true;
}
return new WP_Error(
'ability_missing_input_schema',
sprintf(
/* translators: %s ability name. */
__( 'Ability "%s" does not define an input schema required to validate the provided input.' ),
$this->name
)
);
}
$valid_input = rest_validate_value_from_schema( $input, $input_schema, 'input' );
if ( is_wp_error( $valid_input ) ) {
$is_valid = new WP_Error(
'ability_invalid_input',
sprintf(
/* translators: %1$s ability name, %2$s error message. */
__( 'Ability "%1$s" has invalid input. Reason: %2$s' ),
$this->name,
$valid_input->get_error_message()
)
);
} else {
$is_valid = true;
}
/**
* Filters the input validation result for an ability.
*
* Allows developers to add custom validation logic on top of the default
* JSON Schema validation. If default validation already failed, the filter
* receives the WP_Error object and can add additional error information or
* override it. If default validation passed, the filter can add additional
* validation checks and return a WP_Error if those checks fail.
*
* @since 7.1.0
*
* @param true|WP_Error $is_valid The validation result from default validation.
* @param mixed $input The input data being validated.
* @param string $ability_name The name of the ability.
*/
$validity = apply_filters( 'wp_ability_validate_input', $is_valid, $input, $this->name );
if ( false === $validity ) {
return new WP_Error( 'ability_invalid_input', __( 'Invalid input.' ) );
}
if ( is_wp_error( $validity ) && $validity->has_errors() ) {
return $validity;
}
return true;
}
/**
* Invokes a callable, ensuring the input is passed through only if the input schema is defined.
*
* @since 6.9.0
*
* @param callable $callback The callable to invoke.
* @param mixed $input Optional. The input data for the ability. Default `null`.
* @return mixed The result of the callable execution, or a `WP_Error` if the callback threw.
*/
protected function invoke_callback( callable $callback, $input = null ) {
$args = array();
if ( ! empty( $this->get_input_schema() ) ) {
$args[] = $input;
}
try {
return $callback( ...$args );
} catch ( Throwable $e ) {
return new WP_Error(
'ability_callback_exception',
sprintf(
/* translators: 1: Ability name, 2: Exception message. */
__( 'Ability "%1$s" callback threw an exception: %2$s' ),
$this->name,
esc_html( $e->getMessage() )
)
);
}
}
/**
* Checks whether the ability has the necessary permissions.
*
* Please note that input is not automatically validated against the input schema.
* Use `validate_input()` method to validate input before calling this method if needed.
*
* The {@see 'wp_ability_permission_result'} filter fires after the registered
* `permission_callback` returns, allowing plugins to override the result.
*
* @since 6.9.0
* @since 7.1.0 Added the `wp_ability_permission_result` filter.
*
* @see validate_input()
*
* @param mixed $input Optional. The valid input data for permission checking. Default `null`.
* @return bool|WP_Error Whether the ability has the necessary permission.
*/
public function check_permissions( $input = null ) {
if ( ! is_callable( $this->permission_callback ) ) {
return new WP_Error(
'ability_invalid_permission_callback',
/* translators: %s ability name. */
sprintf( __( 'Ability "%s" does not have a valid permission callback.' ), $this->name )
);
}
$permission = $this->invoke_callback( $this->permission_callback, $input );
/**
* Filters the result of an ability's permission check.
*
* Fires after the registered `permission_callback` returns. Plugins can use this to layer
* additional authorization rules on top of the ability's own permission logic — for example,
* multi-factor authorization gates or temporary permission elevation for trusted contexts.
*
* Filters can return `true` to grant, `false` to deny, or a `WP_Error` to deny with a specific
* error code and message. The filter receives whatever the `permission_callback` produced.
* Any other return value is coerced to `false`.
*
* @since 7.1.0
*
* @param bool|WP_Error $permission The permission result returned by `permission_callback`.
* @param string $ability_name The name of the ability.
* @param mixed $input The input data for the permission check.
* @param WP_Ability $ability The ability instance.
*/
$result = apply_filters( 'wp_ability_permission_result', $permission, $this->name, $input, $this );
if ( ! is_bool( $result ) && ! is_wp_error( $result ) ) {
$result = false;
}
return $result;
}
/**
* Executes the ability callback.
*
* The {@see 'wp_ability_execute_result'} filter fires before this method returns, allowing
* plugins to transform the result produced by the registered `execute_callback`.
*
* @since 6.9.0
* @since 7.1.0 Added the `wp_ability_execute_result` filter.
*
* @param mixed $input Optional. The input data for the ability. Default `null`.
* @return mixed|WP_Error The result of the ability execution, or WP_Error on failure.
*/
protected function do_execute( $input = null ) {
if ( ! is_callable( $this->execute_callback ) ) {
$result = new WP_Error(
'ability_invalid_execute_callback',
/* translators: %s ability name. */
sprintf( __( 'Ability "%s" does not have a valid execute callback.' ), $this->name )
);
} else {
$result = $this->invoke_callback( $this->execute_callback, $input );
}
/**
* Filters the result returned by an ability's execute callback.
*
* Fires after the registered execute callback runs. Plugins can use this to transform the
* result — response formatting, stripping internal metadata, content safety filtering,
* response enrichment, or recovering from a failure by returning a successful value.
*
* The filter receives whatever the registered callback produced, including a `WP_Error`
* if execution failed. Filters may pass the `WP_Error` through unchanged, override it with
* a recovered result, or convert a successful result into a `WP_Error`.
*
* @since 7.1.0
*
* @param mixed $result The result returned by the registered `execute_callback`,
* or a `WP_Error` if execution failed.
* @param string $ability_name The name of the ability.
* @param mixed $input The normalized input data.
* @param WP_Ability $ability The ability instance.
*/
return apply_filters( 'wp_ability_execute_result', $result, $this->name, $input, $this );
}
/**
* Validates output data against the output schema.
*
* @since 6.9.0
*
* @param mixed $output The output data to validate.
* @return true|WP_Error Returns true if valid, or a WP_Error object if validation fails.
*/
protected function validate_output( $output ) {
$output_schema = $this->get_output_schema();
if ( empty( $output_schema ) ) {
$is_valid = true;
} else {
$valid_output = rest_validate_value_from_schema( $output, $output_schema, 'output' );
if ( is_wp_error( $valid_output ) ) {
$is_valid = new WP_Error(
'ability_invalid_output',
sprintf(
/* translators: %1$s ability name, %2$s error message. */
__( 'Ability "%1$s" has invalid output. Reason: %2$s' ),
$this->name,
$valid_output->get_error_message()
)
);
} else {
$is_valid = true;
}
}
/**
* Filters the output validation result for an ability.
*
* Allows developers to add custom validation logic on top of the default
* JSON Schema validation. If default validation already failed, the filter
* receives the WP_Error object and can add additional error information or
* override it. If default validation passed, the filter can add additional
* validation checks and return a WP_Error if those checks fail.
*
* @since 7.1.0
*
* @param true|WP_Error $is_valid The validation result from default validation.
* @param mixed $output The output data being validated.
* @param string $ability_name The name of the ability.
*/
$validity = apply_filters( 'wp_ability_validate_output', $is_valid, $output, $this->name );
if ( false === $validity ) {
return new WP_Error( 'ability_invalid_output', __( 'Invalid output.' ) );
}
if ( is_wp_error( $validity ) && $validity->has_errors() ) {
return $validity;
}
return true;
}
/**
* Executes the ability after input validation and running a permission check.
* Before returning the return value, it also validates the output.
*
* @since 6.9.0
* @since 7.1.0 Added the `wp_ability_invoked` action.
* @since 7.1.0 Added the `wp_pre_execute_ability` filter.
*
* @param mixed $input Optional. The input data for the ability. Default `null`.
* @return mixed|WP_Error The result of the ability execution, or WP_Error on failure.
*/
public function execute( $input = null ) {
/**
* Fires when an ability is invoked, before any processing takes place.
*
* This action fires for every call regardless of outcome (validation failure,
* permission denial, short-circuit, or successful execution), and before input
* normalization so the raw input is captured as-is.
*
* @since 7.1.0
*
* @param string $ability_name The name of the ability.
* @param mixed $input The raw input data for the ability, before normalization.
* @param WP_Ability $ability The ability instance.
*/
do_action( 'wp_ability_invoked', $this->name, $input, $this );
$pre_execute_sentinel = new WP_Filter_Sentinel();
/**
* Filters whether to short-circuit ability execution.
*
* Returning a value other than the received default bypasses the rest of `execute()` —
* input normalization, input validation, permission checks, the registered execute callback,
* output validation, and the surrounding actions — and the value is returned to the caller
* as-is. Useful for cached responses, rate limiting, maintenance mode, and test mocking.
*
* To continue with normal execution, return `$pre` unchanged. This preserves any value
* (including `null`, `false`, or arbitrary objects) as a valid short-circuit result.
*
* Because validation is bypassed, callers that short-circuit are responsible for the
* integrity of any value they consume from `$input`.
*
* @since 7.1.0
*
* @param mixed $pre The pre-computed result. Return this value unchanged to continue execution.
* Default `WP_Filter_Sentinel` instance unique to this invocation.
* @param string $ability_name The name of the ability.
* @param mixed $input The raw input passed to `execute()`.
* @param WP_Ability $ability The ability instance.
*/
$pre = apply_filters( 'wp_pre_execute_ability', $pre_execute_sentinel, $this->name, $input, $this );
if ( $pre !== $pre_execute_sentinel ) {
return $pre;
}
$input = $this->normalize_input( $input );
if ( is_wp_error( $input ) ) {
return $input;
}
$is_valid = $this->validate_input( $input );
if ( is_wp_error( $is_valid ) ) {
return $is_valid;
}
$has_permissions = $this->check_permissions( $input );
if ( true !== $has_permissions ) {
if ( is_wp_error( $has_permissions ) ) {
// Don't leak the permission check error to someone without the correct perms.
_doing_it_wrong(
__METHOD__,
esc_html( $has_permissions->get_error_message() ),
'6.9.0'
);
}
return new WP_Error(
'ability_invalid_permissions',
/* translators: %s ability name. */
sprintf( __( 'Ability "%s" does not have necessary permission.' ), $this->name )
);
}
/**
* Fires before an ability gets executed, after input validation and permissions check.
*
* @since 6.9.0
* @since 7.1.0 Added the `$ability` parameter.
*
* @param string $ability_name The name of the ability.
* @param mixed $input The input data for the ability.
* @param WP_Ability $ability The ability instance.
*/
do_action( 'wp_before_execute_ability', $this->name, $input, $this );
$result = $this->do_execute( $input );
if ( is_wp_error( $result ) ) {
return $result;
}
$is_valid = $this->validate_output( $result );
if ( is_wp_error( $is_valid ) ) {
return $is_valid;
}
/**
* Fires immediately after an ability finished executing.
*
* @since 6.9.0
* @since 7.1.0 Added the `$ability` parameter.
*
* @param string $ability_name The name of the ability.
* @param mixed $input The input data for the ability.
* @param mixed $result The result of the ability execution.
* @param WP_Ability $ability The ability instance.
*/
do_action( 'wp_after_execute_ability', $this->name, $input, $result, $this );
return $result;
}
/**
* Wakeup magic method.
*
* @since 6.9.0
* @throws LogicException If the ability object is unserialized.
* This is a security hardening measure to prevent unserialization of the ability.
*/
public function __wakeup(): void {
throw new LogicException( __CLASS__ . ' should never be unserialized.' );
}
/**
* Sleep magic method.
*
* @since 6.9.0
* @throws LogicException If the ability object is serialized.
* This is a security hardening measure to prevent serialization of the ability.
*/
public function __sleep(): array {
throw new LogicException( __CLASS__ . ' should never be serialized.' );
}
}
round browser/client
* compatibility issues. Essentially, it converts the full HTTP response to
* data instead.
*
* @since 4.4.0
* @since 6.0.0 The `$embed` parameter can now contain a list of link relations to include.
*
* @param WP_REST_Response $response Response object.
* @param bool|string[] $embed Whether to embed all links, a filtered list of link relations, or no links.
* @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(),
);
/**
* Filters the enveloped form of a REST API response.
*
* @since 4.4.0
*
* @param array $envelope {
* Envelope data.
*
* @type array $body Response data.
* @type int $status The 3-digit HTTP status code.
* @type array $headers Map of header name to header value.
* }
* @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
*
* @param string $route_namespace Namespace.
* @param string $route The REST route.
* @param array $route_args Route arguments.
* @param bool $override Optional. Whether the route should be overridden if it already exists.
* Default false.
*/
public function register_route( $route_namespace, $route, $route_args, $override = false ) {
if ( ! isset( $this->namespaces[ $route_namespace ] ) ) {
$this->namespaces[ $route_namespace ] = array();
$this->register_route(
$route_namespace,
'/' . $route_namespace,
array(
array(
'methods' => self::READABLE,
'callback' => array( $this, 'get_namespace_index' ),
'args' => array(
'namespace' => array(
'default' => $route_namespace,
),
'context' => array(
'default' => 'view',
),
),
),
)
);
}
// Associative to avoid double-registration.
$this->namespaces[ $route_namespace ][ $route ] = true;
$route_args['namespace'] = $route_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
* @since 5.4.0 Added `$route_namespace` parameter.
*
* @param string $route_namespace Optionally, only return routes in the given namespace.
* @return array `'/path/regex' => array( $callback, $bitmask )` or
* `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
*/
public function get_routes( $route_namespace = '' ) {
$endpoints = $this->endpoints;
if ( $route_namespace ) {
$endpoints = wp_list_filter( $endpoints, array( 'namespace' => $route_namespace ) );
}
/**
* Filters the array of available REST API 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', $endpoints );
// Normalize 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'] );
} elseif ( 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
*
* @return string[] List of registered namespaces.
*/
public function get_namespaces() {
return array_keys( $this->namespaces );
}
/**
* Retrieves specified options for a route.
*
* @since 4.4.0
*
* @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
*
* @param WP_REST_Request $request Request to attempt dispatching.
* @return WP_REST_Response Response returned by the callback.
*/
public function dispatch( $request ) {
$this->dispatching_requests[] = $request;
/**
* Filters the pre-calculated result of a REST API 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 $server 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 ) ) {
// 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 );
}
array_pop( $this->dispatching_requests );
return $result;
}
$error = null;
$matched = $this->match_request_to_handler( $request );
if ( is_wp_error( $matched ) ) {
$response = $this->error_to_response( $matched );
array_pop( $this->dispatching_requests );
return $response;
}
list( $route, $handler ) = $matched;
if ( ! is_callable( $handler['callback'] ) ) {
$error = new WP_Error(
'rest_invalid_handler',
__( 'The handler for the route is invalid.' ),
array( 'status' => 500 )
);
}
if ( ! is_wp_error( $error ) ) {
$check_required = $request->has_valid_params();
if ( is_wp_error( $check_required ) ) {
$error = $check_required;
} else {
$check_sanitized = $request->sanitize_params();
if ( is_wp_error( $check_sanitized ) ) {
$error = $check_sanitized;
}
}
}
$response = $this->respond_to_request( $request, $route, $handler, $error );
array_pop( $this->dispatching_requests );
return $response;
}
/**
* Returns whether the REST server is currently dispatching / responding to a request.
*
* This may be a standalone REST API request, or an internal request dispatched from within a regular page load.
*
* @since 6.5.0
*
* @return bool Whether the REST server is currently handling a request.
*/
public function is_dispatching() {
return (bool) $this->dispatching_requests;
}
/**
* Matches a request object to its handler.
*
* @access private
* @since 5.6.0
*
* @param WP_REST_Request $request The request object.
* @return array|WP_Error The route and request handler on success or a WP_Error instance if no handler was found.
*/
protected function match_request_to_handler( $request ) {
$method = $request->get_method();
$path = $request->get_route();
$with_namespace = array();
foreach ( $this->get_namespaces() as $namespace ) {
if ( str_starts_with( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) {
$with_namespace[] = $this->get_routes( $namespace );
}
}
if ( $with_namespace ) {
$routes = array_merge( ...$with_namespace );
} else {
$routes = $this->get_routes();
}
foreach ( $routes as $route => $handlers ) {
$match = preg_match( '@^' . $route . '$@i', $path, $matches );
if ( ! $match ) {
continue;
}
$args = array();
foreach ( $matches as $param => $value ) {
if ( ! is_int( $param ) ) {
$args[ $param ] = $value;
}
}
foreach ( $handlers as $handler ) {
$callback = $handler['callback'];
// Fallback to GET method if no HEAD method is registered.
$checked_method = $method;
if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) {
$checked_method = 'GET';
}
if ( empty( $handler['methods'][ $checked_method ] ) ) {
continue;
}
if ( ! is_callable( $callback ) ) {
return array( $route, $handler );
}
$request->set_url_params( $args );
$request->set_attributes( $handler );
$defaults = array();
foreach ( $handler['args'] as $arg => $options ) {
if ( isset( $options['default'] ) ) {
$defaults[ $arg ] = $options['default'];
}
}
$request->set_default_params( $defaults );
return array( $route, $handler );
}
}
return new WP_Error(
'rest_no_route',
__( 'No route was found matching the URL and request method.' ),
array( 'status' => 404 )
);
}
/**
* Dispatches the request to the callback handler.
*
* @access private
* @since 5.6.0
*
* @param WP_REST_Request $request The request object.
* @param string $route The matched route regex.
* @param array $handler The matched route handler.
* @param WP_Error|null $response The current error object if any.
* @return WP_REST_Response
*/
protected function respond_to_request( $request, $route, $handler, $response ) {
/**
* Filters the response before executing any REST API callbacks.
*
* Allows plugins to perform additional validation after a
* request is initialized and matched to a registered route,
* but before it is executed.
*
* Note that this filter will not be called for requests that
* fail to authenticate or match to a registered route.
*
* @since 4.7.0
*
* @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
* Usually a WP_REST_Response or WP_Error.
* @param array $handler Route handler used for the request.
* @param WP_REST_Request $request Request used to generate the response.
*/
$response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );
// Check permission specified on the route.
if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) {
$permission = call_user_func( $handler['permission_callback'], $request );
if ( is_wp_error( $permission ) ) {
$response = $permission;
} elseif ( false === $permission || null === $permission ) {
$response = new WP_Error(
'rest_forbidden',
__( 'Sorry, you are not allowed to do that.' ),
array( 'status' => rest_authorization_required_code() )
);
}
}
if ( ! is_wp_error( $response ) ) {
/**
* Filters the REST API dispatch request result.
*
* Allow plugins to override dispatching the request.
*
* @since 4.4.0
* @since 4.5.0 Added `$route` and `$handler` parameters.
*
* @param mixed $dispatch_result Dispatch result, will be used if not empty.
* @param WP_REST_Request $request Request used to generate the response.
* @param string $route Route matched for the request.
* @param array $handler Route handler used for the request.
*/
$dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler );
// Allow plugins to halt the request via this filter.
if ( null !== $dispatch_result ) {
$response = $dispatch_result;
} else {
$response = call_user_func( $handler['callback'], $request );
}
}
/**
* Filters the response immediately after executing any REST API
* callbacks.
*
* Allows plugins to perform any needed cleanup, for example,
* to undo changes made during the {@see 'rest_request_before_callbacks'}
* filter.
*
* Note that this filter will not be called for requests that
* fail to authenticate or match to a registered route.
*
* Note that an endpoint's `permission_callback` can still be
* called after this filter - see `rest_send_allow_header()`.
*
* @since 4.7.0
*
* @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client.
* Usually a WP_REST_Response or WP_Error.
* @param array $handler Route handler used for the request.
* @param WP_REST_Request $request Request used to generate the response.
*/
$response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $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;
}
/**
* 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
*
* @return false|string Boolean false or string error message.
*/
protected function get_json_last_error() {
if ( JSON_ERROR_NONE === json_last_error() ) {
return false;
}
return json_last_error_msg();
}
/**
* Retrieves the site index.
*
* This endpoint describes the capabilities of the site.
*
* @since 4.4.0
*
* @param WP_REST_Request $request Request data.
* @return WP_REST_Response The API root index data.
*/
public function get_index( $request ) {
// General site data.
$available = array(
'name' => get_option( 'blogname' ),
'description' => get_option( 'blogdescription' ),
'url' => get_option( 'siteurl' ),
'home' => home_url(),
'gmt_offset' => get_option( 'gmt_offset' ),
'timezone_string' => get_option( 'timezone_string' ),
'page_for_posts' => (int) get_option( 'page_for_posts' ),
'page_on_front' => (int) get_option( 'page_on_front' ),
'show_on_front' => get_option( 'show_on_front' ),
'namespaces' => array_keys( $this->namespaces ),
'authentication' => array(),
'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ),
);
// Add media processing settings for users who can upload files.
if ( wp_is_client_side_media_processing_enabled() && current_user_can( 'upload_files' ) ) {
// Image sizes keyed by name for client-side media processing.
$available['image_sizes'] = array();
foreach ( wp_get_registered_image_subsizes() as $name => $size ) {
$available['image_sizes'][ $name ] = $size;
}
/** This filter is documented in wp-admin/includes/image.php */
$available['image_size_threshold'] = (int) apply_filters( 'big_image_size_threshold', 2560, array( 0, 0 ), '', 0 );
/** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */
$available['image_strip_meta'] = (bool) apply_filters( 'image_strip_meta', true );
/*
* On the server, this filter receives the decoded image's actual bit depth.
* The client path never decodes the image on the server, so the filter is
* applied with 16 (the maximum depth the client encoder can produce) as
* both the value and the current depth. The client caps its output bit
* depth at the filtered value, so a plugin lowering it (e.g. to 8) takes
* effect on client-generated images too.
*/
/** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */
$available['image_max_bit_depth'] = (int) apply_filters( 'image_max_bit_depth', 16, 16 );
}
$response = new WP_REST_Response( $available );
$fields = $request['_fields'] ?? '';
$fields = wp_parse_list( $fields );
if ( empty( $fields ) ) {
$fields[] = '_links';
}
if ( $request->has_param( '_embed' ) ) {
$fields[] = '_embedded';
}
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_link( 'help', 'https://developer.wordpress.org/rest-api/' );
$this->add_active_theme_link_to_index( $response );
$this->add_site_logo_to_index( $response );
$this->add_site_icon_to_index( $response );
} else {
if ( rest_is_field_included( 'site_logo', $fields ) ) {
$this->add_site_logo_to_index( $response );
}
if ( rest_is_field_included( 'site_icon', $fields ) || rest_is_field_included( 'site_icon_url', $fields ) ) {
$this->add_site_icon_to_index( $response );
}
}
/**
* Filters the REST 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
* @since 6.0.0 Added `$request` parameter.
*
* @param WP_REST_Response $response Response data.
* @param WP_REST_Request $request Request data.
*/
return apply_filters( 'rest_index', $response, $request );
}
/**
* Adds a link to the active theme for users who have proper permissions.
*
* @since 5.7.0
*
* @param WP_REST_Response $response REST API response.
*/
protected function add_active_theme_link_to_index( WP_REST_Response $response ) {
$should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' );
if ( ! $should_add && current_user_can( 'edit_posts' ) ) {
$should_add = true;
}
if ( ! $should_add ) {
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
$should_add = true;
break;
}
}
}
if ( $should_add ) {
$theme = wp_get_theme();
$response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) );
}
}
/**
* Exposes the site logo through the WordPress REST API.
*
* This is used for fetching this information when user has no rights
* to update settings.
*
* @since 5.8.0
*
* @param WP_REST_Response $response REST API response.
*/
protected function add_site_logo_to_index( WP_REST_Response $response ) {
$site_logo_id = get_theme_mod( 'custom_logo', 0 );
$this->add_image_to_index( $response, $site_logo_id, 'site_logo' );
}
/**
* Exposes the site icon through the WordPress REST API.
*
* This is used for fetching this information when user has no rights
* to update settings.
*
* @since 5.9.0
*
* @param WP_REST_Response $response REST API response.
*/
protected function add_site_icon_to_index( WP_REST_Response $response ) {
$site_icon_id = get_option( 'site_icon', 0 );
$this->add_image_to_index( $response, $site_icon_id, 'site_icon' );
$response->data['site_icon_url'] = get_site_icon_url();
}
/**
* Exposes an image through the WordPress REST API.
* This is used for fetching this information when user has no rights
* to update settings.
*
* @since 5.9.0
*
* @param WP_REST_Response $response REST API response.
* @param int $image_id Image attachment ID.
* @param string $type Type of Image.
*/
protected function add_image_to_index( WP_REST_Response $response, $image_id, $type ) {
$response->data[ $type ] = (int) $image_id;
if ( $image_id ) {
$response->add_link(
'https://api.w.org/featuredmedia',
rest_url( rest_get_route_for_post( $image_id ) ),
array(
'embeddable' => true,
'type' => $type,
)
);
}
}
/**
* Retrieves the index for a namespace.
*
* @since 4.4.0
*
* @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( '/' ) );
/**
* Filters the REST API 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
*
* @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, keyed by route.
*/
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;
}
/**
* Filters the publicly-visible data for a single REST API route.
*
* @since 4.4.0
*
* @param array $data Publicly-visible data for the route.
*/
$available[ $route ] = apply_filters( 'rest_endpoints_description', $data );
}
/**
* Filters the publicly-visible data for REST API 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 Route data to expose in indexes, keyed by route.
* @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
*
* @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(),
);
$allow_batch = false;
if ( isset( $this->route_options[ $route ] ) ) {
$options = $this->route_options[ $route ];
if ( isset( $options['namespace'] ) ) {
$data['namespace'] = $options['namespace'];
}
$allow_batch = $options['allow_batch'] ?? false;
if ( isset( $options['schema'] ) && 'help' === $context ) {
$data['schema'] = call_user_func( $options['schema'] );
}
}
$allowed_schema_keywords = array_flip( wp_get_json_schema_allowed_keywords( 'rest-api' ) );
$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'] ),
);
$callback_batch = $callback['allow_batch'] ?? $allow_batch;
if ( $callback_batch ) {
$endpoint_data['allow_batch'] = $callback_batch;
}
if ( isset( $callback['args'] ) ) {
$endpoint_data['args'] = array();
foreach ( $callback['args'] as $key => $opts ) {
if ( is_string( $opts ) ) {
$opts = array( $opts => 0 );
} elseif ( ! is_array( $opts ) ) {
$opts = array();
}
$arg_data = array_intersect_key( $opts, $allowed_schema_keywords );
$arg_data['required'] = ! empty( $opts['required'] );
$endpoint_data['args'][ $key ] = $arg_data;
}
}
$data['endpoints'][] = $endpoint_data;
// For non-variable routes, generate links.
if ( ! str_contains( $route, '{' ) ) {
$data['_links'] = array(
'self' => array(
array(
'href' => rest_url( $route ),
),
),
);
}
}
if ( empty( $data['methods'] ) ) {
// No methods supported, hide the route.
return null;
}
return $data;
}
/**
* Gets the maximum number of requests that can be included in a batch.
*
* @since 5.6.0
*
* @return int The maximum requests.
*/
protected function get_max_batch_size() {
/**
* Filters the maximum number of REST API requests that can be included in a batch.
*
* @since 5.6.0
*
* @param int $max_size The maximum size.
*/
return apply_filters( 'rest_get_max_batch_size', 25 );
}
/**
* Serves the batch/v1 request.
*
* @since 5.6.0
*
* @param WP_REST_Request $batch_request The batch request object.
* @return WP_REST_Response The generated response object.
*/
public function serve_batch_request_v1( WP_REST_Request $batch_request ) {
$requests = array();
foreach ( $batch_request['requests'] as $args ) {
$parsed_url = wp_parse_url( $args['path'] );
if ( false === $parsed_url ) {
$requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) );
continue;
}
$single_request = new WP_REST_Request( $args['method'] ?? 'POST', $parsed_url['path'] );
if ( ! empty( $parsed_url['query'] ) ) {
$query_args = array();
wp_parse_str( $parsed_url['query'], $query_args );
$single_request->set_query_params( $query_args );
}
if ( ! empty( $args['body'] ) ) {
$single_request->set_body_params( $args['body'] );
}
if ( ! empty( $args['headers'] ) ) {
$single_request->set_headers( $args['headers'] );
}
$requests[] = $single_request;
}
$matches = array();
$validation = array();
$has_error = false;
foreach ( $requests as $single_request ) {
if ( is_wp_error( $single_request ) ) {
$has_error = true;
$matches[] = $single_request;
$validation[] = $single_request;
continue;
}
$match = $this->match_request_to_handler( $single_request );
$matches[] = $match;
$error = null;
if ( is_wp_error( $match ) ) {
$error = $match;
}
if ( ! $error ) {
list( $route, $handler ) = $match;
if ( isset( $handler['allow_batch'] ) ) {
$allow_batch = $handler['allow_batch'];
} else {
$route_options = $this->get_route_options( $route );
$allow_batch = $route_options['allow_batch'] ?? false;
}
if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) {
$error = new WP_Error(
'rest_batch_not_allowed',
__( 'The requested route does not support batch requests.' ),
array( 'status' => 400 )
);
}
}
if ( ! $error ) {
$check_required = $single_request->has_valid_params();
if ( is_wp_error( $check_required ) ) {
$error = $check_required;
}
}
if ( ! $error ) {
$check_sanitized = $single_request->sanitize_params();
if ( is_wp_error( $check_sanitized ) ) {
$error = $check_sanitized;
}
}
if ( $error ) {
$has_error = true;
$validation[] = $error;
} else {
$validation[] = true;
}
}
$responses = array();
if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) {
foreach ( $validation as $valid ) {
if ( is_wp_error( $valid ) ) {
$responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data();
} else {
$responses[] = null;
}
}
return new WP_REST_Response(
array(
'failed' => 'validation',
'responses' => $responses,
),
WP_Http::MULTI_STATUS
);
}
foreach ( $requests as $i => $single_request ) {
if ( is_wp_error( $single_request ) ) {
$result = $this->error_to_response( $single_request );
$responses[] = $this->envelope_response( $result, false )->get_data();
continue;
}
$clean_request = clone $single_request;
$clean_request->set_url_params( array() );
$clean_request->set_attributes( array() );
$clean_request->set_default_params( array() );
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request );
if ( empty( $result ) ) {
$match = $matches[ $i ];
$error = null;
if ( is_wp_error( $validation[ $i ] ) ) {
$error = $validation[ $i ];
}
if ( is_wp_error( $match ) ) {
$result = $this->error_to_response( $match );
} else {
list( $route, $handler ) = $match;
if ( ! $error && ! is_callable( $handler['callback'] ) ) {
$error = new WP_Error(
'rest_invalid_handler',
__( 'The handler for the route is invalid' ),
array( 'status' => 500 )
);
}
$result = $this->respond_to_request( $single_request, $route, $handler, $error );
}
}
/** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
$result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request );
$responses[] = $this->envelope_response( $result, false )->get_data();
}
return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS );
}
/**
* Sends an HTTP status code.
*
* @since 4.4.0
*
* @param int $code HTTP status.
*/
protected function set_status( $code ) {
status_header( $code );
}
/**
* Sends an HTTP header.
*
* @since 4.4.0
*
* @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
*
* @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 );
}
}
/**
* Removes an HTTP header from the current response.
*
* @since 4.8.0
*
* @param string $key Header key.
*/
public function remove_header( $key ) {
header_remove( $key );
}
/**
* Retrieves the raw request entity (body).
*
* @since 4.4.0
*
* @global string $HTTP_RAW_POST_DATA Raw post data.
*
* @return string Raw request data.
*/
public static function get_raw_data() {
// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
global $HTTP_RAW_POST_DATA;
// $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0.
if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
}
return $HTTP_RAW_POST_DATA;
// phpcs:enable
}
/**
* Extracts headers from a PHP-style $_SERVER array.
*
* @since 4.4.0
*
* @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 ( str_starts_with( $key, 'HTTP_' ) ) {
$headers[ substr( $key, 5 ) ] = $value;
} elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) {
/*
* In some server configurations, the authorization header is passed in this alternate location.
* Since it would not be passed in both places we do not check for both headers and resolve.
*/
$headers['AUTHORIZATION'] = $value;
} elseif ( isset( $additional[ $key ] ) ) {
$headers[ $key ] = $value;
}
}
return $headers;
}
}