-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathclass-actors-inbox-controller.php
More file actions
529 lines (473 loc) · 17.6 KB
/
Copy pathclass-actors-inbox-controller.php
File metadata and controls
529 lines (473 loc) · 17.6 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
<?php
/**
* Actors_Inbox_Controller file.
*
* @package Activitypub
*/
namespace Activitypub\Rest;
use Activitypub\Activity\Activity;
use Activitypub\Activity\Base_Object;
use Activitypub\Collection\Actors;
use Activitypub\Collection\Inbox;
use Activitypub\Moderation;
use function Activitypub\camel_to_snake_case;
use function Activitypub\get_masked_wp_version;
use function Activitypub\get_rest_url_by_path;
use function Activitypub\object_to_uri;
/**
* Actors_Inbox_Controller class.
*
* @author Matthias Pfefferle
*
* @see https://www.w3.org/TR/activitypub/#inbox
*/
class Actors_Inbox_Controller extends Actors_Controller {
use Collection;
use Event_Stream;
use Language_Map;
/**
* Register routes.
*/
public function register_routes() {
\register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/inbox',
array(
'args' => array(
'user_id' => array(
'description' => 'The ID of the actor.',
'type' => 'integer',
'required' => true,
'validate_callback' => array( $this, 'validate_user_id' ),
),
),
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'verify_authentication' ),
'args' => array(
'page' => array(
'description' => 'Current page of the collection.',
'type' => 'integer',
'minimum' => 1,
// No default so we can differentiate between Collection and CollectionPage requests.
),
'per_page' => array(
'description' => 'Maximum number of items to be returned in result set.',
'type' => 'integer',
'default' => 20,
'minimum' => 1,
'maximum' => 100,
),
'item' => $this->get_seek_item_arg(),
),
'schema' => array( $this, 'get_collection_schema' ),
),
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array( $this, 'create_item' ),
'permission_callback' => array( $this, 'verify_signature' ),
'args' => array(
'user_id' => array(
'description' => 'The ID of the actor.',
'type' => 'integer',
'required' => true,
'validate_callback' => array( $this, 'validate_inbox_user_id' ),
),
'id' => array(
'description' => 'The unique identifier for the activity.',
'type' => 'string',
'format' => 'uri',
'required' => true,
),
'actor' => array(
'description' => 'The actor performing the activity.',
'type' => 'string',
'required' => true,
'sanitize_callback' => '\Activitypub\object_to_uri',
),
'type' => array(
'description' => 'The type of the activity.',
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_html_class',
'validate_callback' => static function ( $param ) {
// Reject values that sanitize to empty so dynamic hook names always have a suffix.
return '' !== \sanitize_html_class( (string) $param );
},
),
'object' => array(
'description' => 'The object of the activity.',
'required' => true,
'sanitize_callback' => array( $this, 'localize_language_maps' ),
'validate_callback' => static function ( $param, $request, $key ) {
/**
* Filter the ActivityPub object validation.
*
* @param bool $validate The validation result.
* @param array $param The object data.
* @param \WP_REST_Request $request The request object.
* @param string $key The key.
*/
return \apply_filters( 'activitypub_validate_object', true, $param, $request, $key );
},
),
),
),
'schema' => array( $this, 'get_item_schema' ),
)
);
\register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/inbox/stream',
array(
'args' => array(
'user_id' => array(
'description' => 'The ID of the actor.',
'type' => 'integer',
'required' => true,
'validate_callback' => array( $this, 'validate_user_id' ),
),
),
array(
'methods' => \WP_REST_Server::READABLE,
'callback' => function ( $request ) {
$this->stream_collection( $request->get_param( 'user_id' ), 'inbox' );
},
'permission_callback' => array( $this, 'get_stream_permissions_check' ),
),
)
);
\add_action( 'activitypub_inbox_create_item', array( self::class, 'process_create_item' ) );
}
/**
* Validate the user ID for inbox deliveries.
*
* Also accepts the retired Application ID so remote servers that cached the
* old Application actor document, which advertised this route as its inbox,
* can still deliver to it. Those requests are handed to the shared inbox in
* `create_item()`.
*
* @since 9.1.0
*
* @param int $user_id The user ID.
*
* @return true|\WP_Error True if the user ID is valid, WP_Error otherwise.
*/
public function validate_inbox_user_id( $user_id ) {
if ( Actors::APPLICATION_USER_ID === (int) $user_id ) {
return true;
}
return $this->validate_user_id( $user_id );
}
/**
* Retrieves a collection of inbox items.
*
* @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 get_items( $request ) {
$user_id = $request->get_param( 'user_id' );
$user = Actors::get_by_id( $user_id );
if ( \is_wp_error( $user ) ) {
return $user;
}
/**
* Action triggered prior to the ActivityPub inbox being created and sent to the client.
*
* @param \WP_REST_Request $request The request object.
*/
\do_action( 'activitypub_rest_inbox_pre', $request );
$seek = $this->maybe_seek_item( $request, get_rest_url_by_path( \sprintf( 'actors/%d/inbox', $user_id ) ) );
if ( null !== $seek ) {
return $seek;
}
$args = $this->get_query_args( $request );
$inbox_query = new \WP_Query();
$query_result = $inbox_query->query( $args );
$response = array(
'@context' => Base_Object::JSON_LD_CONTEXT,
'id' => get_rest_url_by_path( \sprintf( 'actors/%d/inbox', $user_id ) ),
'generator' => 'https://wordpress.org/?v=' . get_masked_wp_version(),
'actor' => $user->get_id(),
'type' => 'OrderedCollection',
'totalItems' => (int) $inbox_query->found_posts,
'eventStream' => $this->get_stream_url( $user_id, 'inbox' ),
'orderedItems' => array(),
);
\update_postmeta_cache( \wp_list_pluck( $query_result, 'ID' ) );
foreach ( $query_result as $inbox_item ) {
if ( ! $inbox_item instanceof \WP_Post ) {
continue;
}
$response['orderedItems'][] = $this->prepare_item_for_response( $inbox_item, $request );
}
$response = $this->prepare_collection_response( $response, $request );
if ( \is_wp_error( $response ) ) {
return $response;
}
/**
* Filter the ActivityPub inbox array.
*
* @param array $response The ActivityPub inbox array.
* @param \WP_REST_Request $request The request object.
*/
$response = \apply_filters( 'activitypub_rest_inbox_array', $response, $request );
/**
* Action triggered after the ActivityPub inbox has been created and sent to the client.
*
* @param \WP_REST_Request $request The request object.
*/
\do_action( 'activitypub_rest_inbox_post', $request );
// Fire deprecated hook for backward compatibility.
\do_action_deprecated(
'activitypub_inbox_post',
array( $request ),
'8.1.0',
'activitypub_rest_inbox_post'
);
$response = \rest_ensure_response( $response );
$response->header( 'Content-Type', 'application/activity+json; charset=' . \get_option( 'blog_charset' ) );
return $response;
}
/**
* Build the WP_Query arguments for the inbox collection.
*
* Shared by get_items() and get_item_index(), so the seek index is computed under the
* exact same query rules as the collection itself.
*
* @param \WP_REST_Request $request Full details about the request.
*
* @return array The WP_Query arguments.
*/
private function get_query_args( $request ) {
$args = array(
'posts_per_page' => $request->get_param( 'per_page' ),
'paged' => $request->get_param( 'page' ) ?? 1,
'post_type' => Inbox::POST_TYPE,
'post_status' => 'publish',
// Deterministic ordering: break post_date ties by ID, so pagination and seek agree.
'orderby' => array(
'date' => 'DESC',
'ID' => 'DESC',
),
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
array(
'key' => '_activitypub_user_id',
'value' => $request->get_param( 'user_id' ),
),
),
);
/**
* Filters WP_Query arguments when querying Inbox items via the REST API.
*
* Enables adding extra arguments or setting defaults for an inbox collection request.
*
* @param array $args Array of arguments for WP_Query.
* @param \WP_REST_Request $request The REST API request.
*/
return \apply_filters( 'activitypub_rest_inbox_query', $args, $request );
}
/**
* Get the position of an activity in the inbox, under the collection's own query rules.
*
* The inbox route requires authentication, so unlike the outbox this method needs no seek gate
* of its own: a non-owner is already refused before it runs — unauthenticated with 401, and an
* authenticated non-owner with a 403 that Seek_Controller collapses to the uniform 404 so the
* seek discloses no membership. Any new seek surface must preserve that 403 → 404 collapse.
*
* @since unreleased
*
* @param string $item The ActivityPub activity ID.
* @param \WP_REST_Request $request Full details about the request.
*
* @return int|false|\WP_Error Zero-based index of the item, false or WP_Error when not found.
*/
public function get_item_index( $item, $request ) {
$inbox_item = Inbox::get_by_guid( $item );
if ( \is_wp_error( $inbox_item ) ) {
return $inbox_item;
}
$args = $this->get_query_args( $request );
$args['fields'] = 'ids';
$args['posts_per_page'] = 1;
unset( $args['paged'] );
// Confirm the item is part of this inbox before computing the index.
$membership = new \WP_Query( \array_merge( $args, array( 'post__in' => array( $inbox_item->ID ) ) ) );
if ( ! $membership->found_posts ) {
return false;
}
// Count the activities that sort before the item; that count is the item's zero-based index.
$preceding = $this->with_posts_where(
$this->get_preceding_by_date_where( $inbox_item->post_date, $inbox_item->ID ),
static function () use ( $args ) {
return new \WP_Query( $args );
}
);
return (int) $preceding->found_posts;
}
/**
* Prepares the item for the REST response.
*
* @param mixed $item WordPress representation of the item.
* @param \WP_REST_Request $request Request object.
* @return array Response object on success.
*/
public function prepare_item_for_response( $item, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
$activity = \json_decode( $item->post_content, true );
return $activity;
}
/**
* Handles user-inbox requests.
*
* @param \WP_REST_Request $request The request object.
*
* @return \WP_REST_Response|\WP_Error Response object or WP_Error.
*/
public function create_item( $request ) {
$user_id = $request->get_param( 'user_id' );
/*
* Deliveries to the retired Application actor's inbox come from remote
* servers that cached its actor document from before the Application was
* extracted from the actor system. Hand them to the shared inbox, which
* also rejects Follows aimed at the Application.
*/
if ( Actors::APPLICATION_USER_ID === (int) $user_id ) {
$shared_inbox = new Inbox_Controller();
return $shared_inbox->create_item( $request );
}
$data = $request->get_json_params();
$type = camel_to_snake_case( $request->get_param( 'type' ) );
/* @var Activity $activity Activity object.*/
$activity = Activity::init_from_array( $data );
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput
if ( Moderation::activity_is_blocked( $activity, $user_id ) ) {
/**
* ActivityPub inbox disallowed activity.
*
* @param array $data The data array.
* @param int|null $user_id The user ID.
* @param string $type The type of the activity.
* @param Activity|\WP_Error $activity The Activity object.
*/
\do_action( 'activitypub_rest_inbox_disallowed', $data, $user_id, $type, $activity );
} else {
/**
* ActivityPub inbox action.
*
* @param array $data The data array.
* @param int|null $user_id The user ID.
* @param string $type The type of the activity.
* @param Activity|\WP_Error $activity The Activity object.
* @param string $context The context of the request.
*/
\do_action( 'activitypub_inbox', $data, $user_id, $type, $activity, Inbox::CONTEXT_INBOX );
/**
* ActivityPub inbox action for specific activity types.
*
* @param array $data The data array.
* @param int|null $user_id The user ID.
* @param Activity|\WP_Error $activity The Activity object.
* @param string $context The context of the request.
*/
\do_action( 'activitypub_inbox_' . $type, $data, $user_id, $activity, Inbox::CONTEXT_INBOX );
/**
* Filter to skip inbox storage.
*
* Skip inbox storage for debugging purposes or to reduce load for
* certain Activity-Types, like "Delete".
*
* @param bool $skip Whether to skip inbox storage.
* @param array $data The activity data array.
*
* @return bool Whether to skip inbox storage.
*/
$skip = \apply_filters( 'activitypub_skip_inbox_storage', false, $data );
if ( ! $skip ) {
$activity_id = object_to_uri( $data );
Inbox::add( $activity, (array) $user_id );
\wp_clear_scheduled_hook( 'activitypub_inbox_create_item', array( $activity_id ) );
\wp_schedule_single_event( \time() + 15, 'activitypub_inbox_create_item', array( $activity_id ) );
}
}
$response = \rest_ensure_response(
array(
'type' => 'https://w3id.org/fep/c180#approval-required',
'title' => 'Approval Required',
'status' => '202',
'detail' => 'This activity requires approval before it can be processed.',
)
);
$response->set_status( 202 );
$response->header( 'Content-Type', 'application/activity+json; charset=' . \get_option( 'blog_charset' ) );
return $response;
}
/**
* Retrieves the schema for the inbox collection, conforming to JSON Schema.
*
* @return array Collection schema data.
*/
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$item_schema = array(
'type' => 'object',
);
$schema = $this->get_collection_schema( $item_schema );
// Add inbox-specific properties.
$schema['title'] = 'inbox';
$schema['properties']['generator'] = array(
'description' => 'The software used to generate the collection.',
'type' => 'string',
'format' => 'uri',
);
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
/**
* Process cached inbox activity.
*
* Retrieves all collected user IDs for an activity and processes them together.
*
* @param string $activity_id The activity ID.
*/
public static function process_create_item( $activity_id ) {
// Deduplicate if multiple inbox items were created due to race condition.
$inbox_item = Inbox::deduplicate( $activity_id );
if ( ! $inbox_item ) {
return;
}
$data = \json_decode( $inbox_item->post_content, true );
// Reconstruct activity from inbox post.
$activity = Activity::init_from_array( $data );
// Sanitize again here: the type comes from stored activity JSON, which bypassed REST arg sanitization.
$type = camel_to_snake_case( \sanitize_html_class( (string) $activity->get_type() ) );
$context = Inbox::CONTEXT_INBOX;
$user_ids = Inbox::get_recipients( $inbox_item->ID );
/**
* Fires after any ActivityPub Inbox activity has been handled, regardless of activity type.
*
* This hook is triggered for all activity types processed by the inbox handler.
*
* @param array $data The data array.
* @param array $user_ids The user IDs.
* @param string $type The type of the activity.
* @param Activity $activity The Activity object.
* @param int $result The ID of the inbox item that was created, or WP_Error if failed.
* @param string $context The context of the request ('inbox' or 'shared_inbox').
*/
\do_action( 'activitypub_handled_inbox', $data, $user_ids, $type, $activity, $inbox_item->ID, $context );
/**
* Fires after an ActivityPub Inbox activity has been handled.
*
* @param array $data The data array.
* @param array $user_ids The user IDs.
* @param Activity $activity The Activity object.
* @param int $result The ID of the inbox item that was created, or WP_Error if failed.
* @param string $context The context of the request ('inbox' or 'shared_inbox').
*/
\do_action( 'activitypub_handled_inbox_' . $type, $data, $user_ids, $activity, $inbox_item->ID, $context );
}
}