- md5
- 7852ae28855033ab4928c646dc85c654
- sha1
- f4cff739a708242a17114de5cdfc84c7b7a6a47e
- sha256
- df443577f9592a0cb5374cb0d2b95ba5aa70696c7d6870f97b62cdd459388dbd
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
<?php
/**
* REST API run controller for Abilities API.
*
* @package WordPress
* @subpackage Abilities_API
* @since 6.9.0
*/
declare( strict_types = 1 );
/**
* Core controller used to execute abilities via the REST API.
*
* @since 6.9.0
*
* @see WP_REST_Controller
*/
class WP_REST_Abilities_V1_Run_Controller extends WP_REST_Controller {
/**
* REST API namespace.
*
* @since 6.9.0
* @var string
*/
protected $namespace = 'wp-abilities/v1';
/**
* REST API base route.
*
* @since 6.9.0
* @var string
*/
protected $rest_base = 'abilities';
/**
* Registers the routes for ability execution.
*
* @since 6.9.0
*
* @see register_rest_route()
*/
public function register_routes(): void {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<name>[a-zA-Z0-9\-\/]+?)/run',
array(
'args' => array(
'name' => array(
'description' => __( 'Unique identifier for the ability.' ),
'type' => 'string',
'pattern' => '^[a-zA-Z0-9\-\/]+$',
),
),
// TODO: We register ALLMETHODS because at route registration time, we don't know which abilities
// exist or their annotations (`destructive`, `idempotent`, `readonly`). This is due to WordPress
// load order - routes are registered early, before plugins have registered their abilities.
// This approach works but could be improved with lazy route registration or a different
// architecture that allows type-specific routes after abilities are registered.
// This was the same issue that we ended up seeing with the Feature API.
array(
'methods' => WP_REST_Server::ALLMETHODS,
'callback' => array( $this, 'execute_ability' ),
'permission_callback' => array( $this, 'check_ability_permissions' ),
'args' => $this->get_run_args(),
/*
* Serve the ability result as returned, so it follows the ability's output
* schema whether it is an object, an array, or a scalar value: `_fields`,
* `_embed` and response links leave it unchanged.
*/
'data_processing' => false,
),
'schema' => array( $this, 'get_run_schema' ),
)
);
}
/**
* Executes an ability.
*
* @since 6.9.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function execute_ability( $request ) {
$ability = wp_has_ability( $request['name'] ) ? wp_get_ability( $request['name'] ) : null;
if ( ! $ability ) {
return new WP_Error(
'rest_ability_not_found',
__( 'Ability not found.' ),
array( 'status' => 404 )
);
}
$input = $this->get_input_from_request( $request );
$result = $ability->execute( $input );
if ( is_wp_error( $result ) ) {
return $result;
}
/*
* Preserve empty objects when encoding the result as JSON. Preparation can
* convert empty PHP arrays to stdClass, also within object results.
*/
$result = wp_prepare_json_value_for_client( $result, $ability->get_output_schema() );
return rest_ensure_response( $result );
}
/**
* Validates if the HTTP method matches the expected method for the ability based on its annotations.
*
* @since 6.9.0
*
* @param string $request_method The HTTP method of the request.
* @param array<string, (null|bool)> $annotations The ability annotations.
* @return true|WP_Error True on success, or WP_Error object on failure.
*/
public function validate_request_method( string $request_method, array $annotations ) {
$expected_method = 'POST';
if ( ! empty( $annotations['readonly'] ) ) {
$expected_method = 'GET';
} elseif ( ! empty( $annotations['destructive'] ) && ! empty( $annotations['idempotent'] ) ) {
$expected_method = 'DELETE';
}
if ( $expected_method === $request_method ) {
return true;
}
$error_message = __( 'Abilities that perform updates require POST method.' );
if ( 'GET' === $expected_method ) {
$error_message = __( 'Read-only abilities require GET method.' );
} elseif ( 'DELETE' === $expected_method ) {
$error_message = __( 'Abilities that perform destructive actions require DELETE method.' );
}
return new WP_Error(
'rest_ability_invalid_method',
$error_message,
array( 'status' => 405 )
);
}
/**
* Checks if a given request has permission to execute a specific ability.
*
* @since 6.9.0
*
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True if the request has execution permission, WP_Error object otherwise.
*/
public function check_ability_permissions( $request ) {
$ability = wp_has_ability( $request['name'] ) ? wp_get_ability( $request['name'] ) : null;
if ( ! $ability || ! $ability->get_meta_item( 'show_in_rest' ) ) {
return new WP_Error(
'rest_ability_not_found',
__( 'Ability not found.' ),
array( 'status' => 404 )
);
}
$is_valid = $this->validate_request_method(
$request->get_method(),
$ability->get_meta_item( 'annotations' )
);
if ( is_wp_error( $is_valid ) ) {
return $is_valid;
}
$input = $this->get_input_from_request( $request );
$input = $ability->normalize_input( $input );
if ( is_wp_error( $input ) ) {
return $this->ensure_error_status( $input, 400 );
}
$is_valid = $ability->validate_input( $input );
if ( is_wp_error( $is_valid ) ) {
return $this->ensure_error_status( $is_valid, 400 );
}
$input = $ability->coerce_input( $input );
if ( is_wp_error( $input ) ) {
return $this->ensure_error_status( $input, 400 );
}
$result = $ability->check_permissions( $input );
if ( is_wp_error( $result ) ) {
$result->add_data( array( 'status' => rest_authorization_required_code() ) );
return $result;
}
if ( ! $result ) {
return new WP_Error(
'rest_ability_cannot_execute',
__( 'Sorry, you are not allowed to execute this ability.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
/**
* Ensures a WP_Error object carries an HTTP status, adding a default when none is set.
*
* @since 7.1.0
*
* @param WP_Error $error Error object to update.
* @param int $status HTTP status code to add if not already present.
* @return WP_Error The error object, with a default status when needed.
*/
private function ensure_error_status( WP_Error $error, int $status ): WP_Error {
$error_data = $error->get_error_data();
if ( ! is_array( $error_data ) || ! isset( $error_data['status'] ) ) {
$error->add_data( array( 'status' => $status ) );
}
return $error;
}
/**
* Extracts input parameters from the request.
*
* @since 6.9.0
*
* @param WP_REST_Request $request The request object.
* @return mixed|null The input parameters.
*/
private function get_input_from_request( $request ) {
if ( in_array( $request->get_method(), array( 'GET', 'DELETE' ), true ) ) {
// For GET and DELETE requests, look for 'input' query parameter.
$query_params = $request->get_query_params();
return $query_params['input'] ?? null;
}
// For POST requests, look for 'input' in JSON body.
$json_params = $request->get_json_params();
return $json_params['input'] ?? null;
}
/**
* Sanitizes the run input by coercing it to the ability's input schema.
*
* Registered as the `input` argument `sanitize_callback` so request input is coerced
* before any route callback runs, regardless of transport. `check_ability_permissions()`
* and `WP_Ability::execute()` coerce the input again after normalization and validation,
* so schema defaults and values from normalization filters are coerced too.
*
* @since 7.1.0
*
* @see WP_Ability::coerce_input()
*
* @param mixed $input Raw input extracted from the request.
* @param WP_REST_Request $request The request object.
* @return mixed|WP_Error Coerced input, raw input when validation fails, or WP_Error when coercion fails.
*/
public function sanitize_input_for_ability( $input, $request ) {
$ability = wp_has_ability( $request['name'] ) ? wp_get_ability( $request['name'] ) : null;
if ( ! $ability instanceof WP_Ability ) {
return $input;
}
// Validate before coercion so sanitization cannot rescue invalid input.
if ( null === $input || empty( $ability->get_input_schema() ) || is_wp_error( $ability->validate_input( $input ) ) ) {
return $input;
}
return $ability->coerce_input( $input );
}
/**
* Retrieves the arguments for ability execution endpoint.
*
* @since 6.9.0
*
* @return array<string, mixed> Arguments for the run endpoint.
*/
public function get_run_args(): array {
return array(
'input' => array(
'description' => __( 'Input parameters for the ability execution.' ),
'type' => array( 'integer', 'number', 'boolean', 'string', 'array', 'object', 'null' ),
'default' => null,
'sanitize_callback' => array( $this, 'sanitize_input_for_ability' ),
),
);
}
/**
* Retrieves the schema for ability execution endpoint.
*
* @since 6.9.0
*
* @return array<string, mixed> Schema for the run endpoint.
*/
public function get_run_schema(): array {
return array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'ability-execution',
'type' => 'object',
'properties' => array(
'result' => array(
'description' => __( 'The result of the ability execution.' ),
'type' => array( 'integer', 'number', 'boolean', 'string', 'array', 'object', 'null' ),
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
),
);
}
}
No other release has this exact content. See every version of this file.