Repository navigation
Expand file tree
/
Copy pathclass-wp-rest-abilities-v1-run-controller.php
More file actions
304 lines (277 loc) · 9.38 KB
/
Copy pathclass-wp-rest-abilities-v1-run-controller.php
File metadata and controls
304 lines (277 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
<?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.
*
* Read-only abilities require GET. Destructive and idempotent abilities require PUT, and also
* accept PATCH and DELETE. All other abilities require POST.
*
* @since 6.9.0
* @since 7.3.0 Destructive and idempotent abilities require PUT, and also accept PATCH and DELETE.
*
* @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';
$accepted_methods = array();
if ( ! empty( $annotations['readonly'] ) ) {
$expected_method = 'GET';
} elseif ( ! empty( $annotations['destructive'] ) && ! empty( $annotations['idempotent'] ) ) {
/*
* Updates and deletes share these annotations. PUT is idempotent by definition
* and carries the input in a JSON body. PATCH also suits partial updates, and
* DELETE stays accepted for clients written before PUT was supported.
*/
$expected_method = 'PUT';
$accepted_methods = array( 'PATCH', 'DELETE' );
}
if ( $expected_method === $request_method || in_array( $request_method, $accepted_methods, true ) ) {
return true;
}
$error_message = __( 'Abilities that perform updates require POST method.' );
if ( 'GET' === $expected_method ) {
$error_message = __( 'Read-only abilities require GET method.' );
} elseif ( 'PUT' === $expected_method ) {
$error_message = __( 'Idempotent destructive abilities require PUT 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
* @since 7.2.0 Prepares the input read from the raw request.
*
* @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 = $ability->prepare_input( $this->get_input_from_request( $request ) );
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, PUT and PATCH requests, look for 'input' in JSON body.
$json_params = $request->get_json_params();
return $json_params['input'] ?? null;
}
/**
* Returns run input unchanged for backward compatibility.
*
* This method is no longer registered as the input argument sanitizer.
*
* @since 7.1.0
* @deprecated 7.2.0 Input is prepared by `check_ability_permissions()` and `WP_Ability::execute()`.
*
* @param mixed $input Raw input extracted from the request.
* @param WP_REST_Request $request Unused. The request object.
* @return mixed The unchanged input.
*/
public function sanitize_input_for_ability( $input, $request ) {
_deprecated_function( __METHOD__, '7.2.0' );
return $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,
// Keep the raw input for the permission check and execution. This disables default REST coercion.
'sanitize_callback' => null,
),
);
}
/**
* 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,
),
),
);
}
}