PluginProbe
ActivityPub / 5.1.0
ActivityPub v5.1.0
9.3.1 9.3.0 9.2.2 9.2.1 9.2.0 9.1.0 9.0.2 9.0.1 9.0.0 8.3.0 8.2.1 8.2.0 8.1.1 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.2.0 1.3.0 2.0.0 2.0.1 2.1.0 2.1.1 All 160 releases
← All changes | includes/functions.php +1179 -231 2.0.05.1.0 View file →
@@ -1,40 +1,72 @@
1 1 <?php
2 +/**
3 + * Functions file.
4 + *
5 + * @package Activitypub
6 + */
7 +
2 8 namespace Activitypub;
3 9
4 10 use WP_Error;
5 -use WP_Comment_Query;
6 -use Activitypub\Http;
7 -use Activitypub\Webfinger;
8 11 use Activitypub\Activity\Activity;
12 +use Activitypub\Activity\Base_Object;
13 +use Activitypub\Collection\Actors;
14 +use Activitypub\Collection\Outbox;
9 15 use Activitypub\Collection\Followers;
10 -use Activitypub\Collection\Users;
16 +use Activitypub\Transformer\Post;
17 +use Activitypub\Transformer\Factory as Transformer_Factory;
11 18
12 19 /**
13 - * Returns the ActivityPub default JSON-context
20 + * Returns the ActivityPub default JSON-context.
14 21 *
15 - * @return array the activitypub context
22 + * @return array The activitypub context.
16 23 */
17 24 function get_context() {
18 - $context = Activity::CONTEXT;
25 + $context = Activity::JSON_LD_CONTEXT;
19 26
27 + /**
28 + * Filters the ActivityPub JSON-LD context.
29 + *
30 + * This filter allows developers to modify or extend the JSON-LD context used
31 + * in ActivityPub responses. The context defines the vocabulary and terms used
32 + * in the ActivityPub JSON objects.
33 + *
34 + * @param array $context The default ActivityPub JSON-LD context array.
35 + */
20 36 return \apply_filters( 'activitypub_json_context', $context );
21 37 }
22 38
39 +/**
40 + * Send a POST request to a remote server.
41 + *
42 + * @param string $url The URL endpoint.
43 + * @param string $body The Post Body.
44 + * @param int $user_id The WordPress user ID.
45 + *
46 + * @return array|WP_Error The POST Response or an WP_Error.
47 + */
23 48 function safe_remote_post( $url, $body, $user_id ) {
24 49 return Http::post( $url, $body, $user_id );
25 50 }
26 51
52 +/**
53 + * Send a GET request to a remote server.
54 + *
55 + * @param string $url The URL endpoint.
56 + *
57 + * @return array|WP_Error The GET Response or an WP_Error.
58 + */
27 59 function safe_remote_get( $url ) {
28 60 return Http::get( $url );
29 61 }
30 62
31 63 /**
32 - * Returns a users WebFinger "resource"
64 + * Returns a users WebFinger "resource".
33 65 *
34 - * @param int $user_id The User-ID.
66 + * @param int $user_id The user ID.
35 67 *
36 - * @return string The User-Resource.
68 + * @return string The User resource.
37 69 */
38 70 function get_webfinger_resource( $user_id ) {
39 71 return Webfinger::get_user_resource( $user_id );
40 72 }
@@ -39,26 +71,61 @@
39 71 return Webfinger::get_user_resource( $user_id );
40 72 }
41 73
42 74 /**
43 - * Requests the Meta-Data from the Actors profile
75 + * Requests the Meta-Data from the Actors profile.
44 76 *
45 77 * @param string $actor The Actor URL.
46 - * @param bool $cached If the result should be cached.
78 + * @param bool $cached Optional. Whether the result should be cached. Default true.
47 79 *
48 80 * @return array|WP_Error The Actor profile as array or WP_Error on failure.
49 81 */
50 82 function get_remote_metadata_by_actor( $actor, $cached = true ) {
83 + /**
84 + * Filters the metadata before it is retrieved from a remote actor.
85 + *
86 + * Passing a non-false value will effectively short-circuit the remote request,
87 + * returning that value instead.
88 + *
89 + * @param mixed $pre The value to return instead of the remote metadata.
90 + * Default false to continue with the remote request.
91 + * @param string $actor The actor URL.
92 + */
51 93 $pre = apply_filters( 'pre_get_remote_metadata_by_actor', false, $actor );
52 94 if ( $pre ) {
53 95 return $pre;
54 96 }
97 +
98 + if ( is_array( $actor ) ) {
99 + if ( array_key_exists( 'id', $actor ) ) {
100 + $actor = $actor['id'];
101 + } elseif ( array_key_exists( 'url', $actor ) ) {
102 + $actor = $actor['url'];
103 + } else {
104 + return new WP_Error(
105 + 'activitypub_no_valid_actor_identifier',
106 + \__( 'The "actor" identifier is not valid', 'activitypub' ),
107 + array(
108 + 'status' => 404,
109 + 'actor' => $actor,
110 + )
111 + );
112 + }
113 + }
114 +
55 115 if ( preg_match( '/^@?' . ACTIVITYPUB_USERNAME_REGEXP . '$/i', $actor ) ) {
56 116 $actor = Webfinger::resolve( $actor );
57 117 }
58 118
59 119 if ( ! $actor ) {
60 - return new WP_Error( 'activitypub_no_valid_actor_identifier', \__( 'The "actor" identifier is not valid', 'activitypub' ), array( 'status' => 404, 'actor' => $actor ) );
120 + return new WP_Error(
121 + 'activitypub_no_valid_actor_identifier',
122 + \__( 'The "actor" identifier is not valid', 'activitypub' ),
123 + array(
124 + 'status' => 404,
125 + 'actor' => $actor,
126 + )
127 + );
61 128 }
62 129
63 130 if ( is_wp_error( $actor ) ) {
64 131 return $actor;
@@ -65,9 +132,9 @@
65 132 }
66 133
67 134 $transient_key = 'activitypub_' . $actor;
68 135
69 - // only check the cache if needed.
136 + // Only check the cache if needed.
70 137 if ( $cached ) {
71 138 $metadata = \get_transient( $transient_key );
72 139
73 140 if ( $metadata ) {
@@ -75,9 +142,16 @@
75 142 }
76 143 }
77 144
78 145 if ( ! \wp_http_validate_url( $actor ) ) {
79 - $metadata = new WP_Error( 'activitypub_no_valid_actor_url', \__( 'The "actor" is no valid URL', 'activitypub' ), array( 'status' => 400, 'actor' => $actor ) );
146 + $metadata = new WP_Error(
147 + 'activitypub_no_valid_actor_url',
148 + \__( 'The "actor" is no valid URL', 'activitypub' ),
149 + array(
150 + 'status' => 400,
151 + 'actor' => $actor,
152 + )
153 + );
80 154 return $metadata;
81 155 }
82 156
83 157 $response = Http::get( $actor );
@@ -89,9 +163,16 @@
89 163 $metadata = \wp_remote_retrieve_body( $response );
90 164 $metadata = \json_decode( $metadata, true );
91 165
92 166 if ( ! $metadata ) {
93 - $metadata = new WP_Error( 'activitypub_invalid_json', \__( 'No valid JSON data', 'activitypub' ), array( 'status' => 400, 'actor' => $actor ) );
167 + $metadata = new WP_Error(
168 + 'activitypub_invalid_json',
169 + \__( 'No valid JSON data', 'activitypub' ),
170 + array(
171 + 'status' => 400,
172 + 'actor' => $actor,
173 + )
174 + );
94 175 return $metadata;
95 176 }
96 177
97 178 \set_transient( $transient_key, $metadata, WEEK_IN_SECONDS );
@@ -101,9 +182,9 @@
101 182
102 183 /**
103 184 * Returns the followers of a given user.
104 185 *
105 - * @param int $user_id The User-ID.
186 + * @param int $user_id The user ID.
106 187 *
107 188 * @return array The followers.
108 189 */
109 190 function get_followers( $user_id ) {
@@ -112,9 +193,9 @@
112 193
113 194 /**
114 195 * Count the number of followers for a given user.
115 196 *
116 - * @param int $user_id The User-ID.
197 + * @param int $user_id The user ID.
117 198 *
118 199 * @return int The number of followers.
119 200 */
120 201 function count_followers( $user_id ) {
@@ -127,39 +208,36 @@
127 208 * Checks are supposedly from the hosted site blog.
128 209 *
129 210 * @param string $url Permalink to check.
130 211 *
131 - * @return int User ID, or 0 on failure.
212 + * @return int|null User ID, or null on failure.
132 213 */
133 214 function url_to_authorid( $url ) {
134 215 global $wp_rewrite;
135 216
136 - // check if url hase the same host
137 - if ( \wp_parse_url( \site_url(), \PHP_URL_HOST ) !== \wp_parse_url( $url, \PHP_URL_HOST ) ) {
138 - return 0;
217 + // Check if url hase the same host.
218 + if ( \wp_parse_url( \home_url(), \PHP_URL_HOST ) !== \wp_parse_url( $url, \PHP_URL_HOST ) ) {
219 + return null;
139 220 }
140 221
141 - // first, check to see if there is a 'author=N' to match against
222 + // First, check to see if there is a 'author=N' to match against.
142 223 if ( \preg_match( '/[?&]author=(\d+)/i', $url, $values ) ) {
143 - $id = \absint( $values[1] );
144 - if ( $id ) {
145 - return $id;
146 - }
224 + return \absint( $values[1] );
147 225 }
148 226
149 - // check to see if we are using rewrite rules
227 + // Check to see if we are using rewrite rules.
150 228 $rewrite = $wp_rewrite->wp_rewrite_rules();
151 229
152 - // not using rewrite rules, and 'author=N' method failed, so we're out of options
230 + // Not using rewrite rules, and 'author=N' method failed, so we're out of options.
153 231 if ( empty( $rewrite ) ) {
154 - return 0;
232 + return null;
155 233 }
156 234
157 - // generate rewrite rule for the author url
235 + // Generate rewrite rule for the author url.
158 236 $author_rewrite = $wp_rewrite->get_author_permastruct();
159 - $author_regexp = \str_replace( '%author%', '', $author_rewrite );
237 + $author_regexp = \str_replace( '%author%', '', $author_rewrite );
160 238
161 - // match the rewrite rule with the passed url
239 + // Match the rewrite rule with the passed url.
162 240 if ( \preg_match( '/https?:\/\/(.+)' . \preg_quote( $author_regexp, '/' ) . '([^\/]+)/i', $url, $match ) ) {
163 241 $user = \get_user_by( 'slug', $match[2] );
164 242 if ( $user ) {
165 243 return $user->ID;
@@ -165,16 +243,15 @@
165 243 return $user->ID;
166 244 }
167 245 }
168 246
169 - return 0;
247 + return null;
170 248 }
171 249
172 250 /**
173 - * Verify if url is a wp_ap_comment,
174 - * Or if it is a previously received remote comment
251 + * Verify that url is a wp_ap_comment or a previously received remote comment.
175 252 *
176 - * @return int comment_id
253 + * @return int|bool Comment ID or false if not found.
177 254 */
178 255 function is_comment() {
179 256 $comment_id = get_query_var( 'c', null );
180 257
@@ -180,10 +257,9 @@
180 257
181 258 if ( ! is_null( $comment_id ) ) {
182 259 $comment = \get_comment( $comment_id );
183 260
184 - // Only return local origin comments
185 - if ( $comment && $comment->user_id ) {
261 + if ( $comment ) {
186 262 return $comment_id;
187 263 }
188 264 }
189 265
@@ -190,15 +266,15 @@
190 266 return false;
191 267 }
192 268
193 269 /**
194 - * Check for Tombstone Objects
270 + * Check for Tombstone Objects.
195 271 *
196 272 * @see https://www.w3.org/TR/activitypub/#delete-activity-outbox
197 273 *
198 - * @param WP_Error $wp_error A WP_Error-Response of an HTTP-Request
274 + * @param WP_Error $wp_error A WP_Error-Response of an HTTP-Request.
199 275 *
200 - * @return boolean true if HTTP-Code is 410 or 404
276 + * @return boolean True if HTTP-Code is 410 or 404.
201 277 */
202 278 function is_tombstone( $wp_error ) {
203 279 if ( ! is_wp_error( $wp_error ) ) {
204 280 return false;
@@ -213,15 +289,15 @@
213 289
214 290 /**
215 291 * Get the REST URL relative to this plugin's namespace.
216 292 *
217 - * @param string $path Optional. REST route path. Otherwise this plugin's namespaced root.
293 + * @param string $path Optional. REST route path. Default ''.
218 294 *
219 295 * @return string REST URL relative to this plugin's namespace.
220 296 */
221 297 function get_rest_url_by_path( $path = '' ) {
222 - // we'll handle the leading slash.
223 - $path = ltrim( $path, '/' );
298 + // We'll handle the leading slash.
299 + $path = ltrim( $path, '/' );
224 300 $namespaced_path = sprintf( '/%s/%s', ACTIVITYPUB_REST_NAMESPACE, $path );
225 301 return \get_rest_url( null, $namespaced_path );
226 302 }
227 303
@@ -227,39 +303,37 @@
227 303
228 304 /**
229 305 * Convert a string from camelCase to snake_case.
230 306 *
231 - * @param string $string The string to convert.
307 + * @param string $input The string to convert.
232 308 *
233 309 * @return string The converted string.
234 310 */
235 -// phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound
236 -function camel_to_snake_case( $string ) {
237 - return strtolower( preg_replace( '/(?<!^)[A-Z]/', '_$0', $string ) );
311 +function camel_to_snake_case( $input ) {
312 + return strtolower( preg_replace( '/(?<!^)[A-Z]/', '_$0', $input ) );
238 313 }
239 314
240 315 /**
241 316 * Convert a string from snake_case to camelCase.
242 317 *
243 - * @param string $string The string to convert.
318 + * @param string $input The string to convert.
244 319 *
245 320 * @return string The converted string.
246 321 */
247 -// phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound
248 -function snake_to_camel_case( $string ) {
249 - return lcfirst( str_replace( '_', '', ucwords( $string, '_' ) ) );
322 +function snake_to_camel_case( $input ) {
323 + return lcfirst( str_replace( '_', '', ucwords( $input, '_' ) ) );
250 324 }
251 325
252 326 /**
253 327 * Escapes a Tag, to be used as a hashtag.
254 328 *
255 - * @param string $string The string to escape.
329 + * @param string $input The string to escape.
256 330 *
257 - * @return string The escaped hastag.
331 + * @return string The escaped hashtag.
258 332 */
259 -function esc_hashtag( $string ) {
333 +function esc_hashtag( $input ) {
260 334
261 - $hashtag = \wp_specialchars_decode( $string, ENT_QUOTES );
335 + $hashtag = \wp_specialchars_decode( $input, ENT_QUOTES );
262 336 // Remove all characters that are not letters, numbers, or underscores.
263 337 $hashtag = \preg_replace( '/emoji-regex(*SKIP)(?!)|[^\p{L}\p{Nd}_]+/u', '_', $hashtag );
264 338
265 339 // Capitalize every letter that is preceded by an underscore.
@@ -265,9 +339,9 @@
265 339 // Capitalize every letter that is preceded by an underscore.
266 340 $hashtag = preg_replace_callback(
267 341 '/_(.)/',
268 342 function ( $matches ) {
269 - return '' . strtoupper( $matches[1] );
343 + return strtoupper( $matches[1] );
270 344 },
271 345 $hashtag
272 346 );
273 347
@@ -278,11 +352,11 @@
278 352 /**
279 353 * Allow defining your own custom hashtag generation rules.
280 354 *
281 355 * @param string $hashtag The hashtag to be returned.
282 - * @param string $string The original string.
356 + * @param string $input The original string.
283 357 */
284 - $hashtag = apply_filters( 'activitypub_esc_hashtag', $hashtag, $string );
358 + $hashtag = apply_filters( 'activitypub_esc_hashtag', $hashtag, $input );
285 359
286 360 return esc_html( $hashtag );
287 361 }
288 362
@@ -291,104 +365,101 @@
291 365 *
292 366 * @return bool False by default.
293 367 */
294 368 function is_activitypub_request() {
295 - global $wp_query;
369 + return Query::get_instance()->is_activitypub_request();
370 +}
296 371
297 - /*
298 - * ActivityPub requests are currently only made for
299 - * author archives, singular posts, and the homepage.
300 - */
301 - if ( ! \is_author() && ! \is_singular() && ! \is_home() && ! defined( '\REST_REQUEST' ) ) {
302 - return false;
303 - }
372 +/**
373 + * Check if a post is disabled for ActivityPub.
374 + *
375 + * This function checks if the post type supports ActivityPub and if the post is set to be local.
376 + *
377 + * @param mixed $post The post object or ID.
378 + *
379 + * @return boolean True if the post is disabled, false otherwise.
380 + */
381 +function is_post_disabled( $post ) {
382 + $post = \get_post( $post );
383 + $disabled = false;
304 384
305 - // Check if the current post type supports ActivityPub.
306 - if ( \is_singular() ) {
307 - $queried_object = \get_queried_object();
308 - $post_type = \get_post_type( $queried_object );
309 -
310 - if ( ! \post_type_supports( $post_type, 'activitypub' ) ) {
311 - return false;
312 - }
313 - }
314 -
315 - // One can trigger an ActivityPub request by adding ?activitypub to the URL.
316 - // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.VariableRedeclaration
317 - global $wp_query;
318 - if ( isset( $wp_query->query_vars['activitypub'] ) ) {
385 + if ( ! $post ) {
319 386 return true;
320 387 }
321 388
322 - /*
323 - * The other (more common) option to make an ActivityPub request
324 - * is to send an Accept header.
325 - */
326 - if ( isset( $_SERVER['HTTP_ACCEPT'] ) ) {
327 - $accept = sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) );
389 + $visibility = \get_post_meta( $post->ID, 'activitypub_content_visibility', true );
328 390
329 - /*
330 - * $accept can be a single value, or a comma separated list of values.
331 - * We want to support both scenarios,
332 - * and return true when the header includes at least one of the following:
333 - * - application/activity+json
334 - * - application/ld+json
335 - * - application/json
336 - */
337 - if ( preg_match( '/(application\/(ld\+json|activity\+json|json))/i', $accept ) ) {
338 - return true;
339 - }
391 + if (
392 + ACTIVITYPUB_CONTENT_VISIBILITY_LOCAL === $visibility ||
393 + ACTIVITYPUB_CONTENT_VISIBILITY_PRIVATE === $visibility ||
394 + ! \post_type_supports( $post->post_type, 'activitypub' ) ||
395 + 'private' === $post->post_status ||
396 + ! empty( $post->post_password )
397 + ) {
398 + $disabled = true;
340 399 }
341 400
342 - return false;
401 + /**
402 + * Allow plugins to disable posts for ActivityPub.
403 + *
404 + * @param boolean $disabled True if the post is disabled, false otherwise.
405 + * @param \WP_Post $post The post object.
406 + */
407 + return \apply_filters( 'activitypub_is_post_disabled', $disabled, $post );
343 408 }
344 409
345 410 /**
346 411 * This function checks if a user is disabled for ActivityPub.
347 412 *
348 - * @param int $user_id The User-ID.
413 + * @param int $user_id The user ID.
349 414 *
350 415 * @return boolean True if the user is disabled, false otherwise.
351 416 */
352 417 function is_user_disabled( $user_id ) {
353 - $return = false;
418 + $disabled = false;
354 419
355 420 switch ( $user_id ) {
356 421 // if the user is the application user, it's always enabled.
357 - case \Activitypub\Collection\Users::APPLICATION_USER_ID:
358 - $return = false;
422 + case \Activitypub\Collection\Actors::APPLICATION_USER_ID:
423 + $disabled = false;
359 424 break;
360 425 // if the user is the blog user, it's only enabled in single-user mode.
361 - case \Activitypub\Collection\Users::BLOG_USER_ID:
426 + case \Activitypub\Collection\Actors::BLOG_USER_ID:
362 427 if ( is_user_type_disabled( 'blog' ) ) {
363 - $return = true;
428 + $disabled = true;
364 429 break;
365 430 }
366 431
367 - $return = false;
432 + $disabled = false;
368 433 break;
369 434 // if the user is any other user, it's enabled if it can publish posts.
370 435 default:
371 436 if ( ! \get_user_by( 'id', $user_id ) ) {
372 - $return = true;
437 + $disabled = true;
373 438 break;
374 439 }
375 440
376 441 if ( is_user_type_disabled( 'user' ) ) {
377 - $return = true;
442 + $disabled = true;
378 443 break;
379 444 }
380 445
381 - if ( ! \user_can( $user_id, 'publish_posts' ) ) {
382 - $return = true;
446 + if ( ! \user_can( $user_id, 'activitypub' ) ) {
447 + $disabled = true;
383 448 break;
384 449 }
385 450
386 - $return = false;
451 + $disabled = false;
387 452 break;
388 453 }
389 454
390 - return apply_filters( 'activitypub_is_user_disabled', $return, $user_id );
455 + /**
456 + * Allow plugins to disable users for ActivityPub.
457 + *
458 + * @param boolean $disabled True if the user is disabled, false otherwise.
459 + * @param int $user_id The User-ID.
460 + */
461 + return apply_filters( 'activitypub_is_user_disabled', $disabled, $user_id );
391 462 }
392 463
393 464 /**
394 465 * Checks if a User-Type is disabled for ActivityPub.
@@ -395,9 +466,9 @@
395 466 *
396 467 * This function is used to check if the 'blog' or 'user'
397 468 * type is disabled for ActivityPub.
398 469 *
399 - * @param enum $type Can be 'blog' or 'user'.
470 + * @param string $type User type. 'blog' or 'user'.
400 471 *
401 472 * @return boolean True if the user type is disabled, false otherwise.
402 473 */
403 474 function is_user_type_disabled( $type ) {
@@ -404,51 +475,61 @@
404 475 switch ( $type ) {
405 476 case 'blog':
406 477 if ( \defined( 'ACTIVITYPUB_SINGLE_USER_MODE' ) ) {
407 478 if ( ACTIVITYPUB_SINGLE_USER_MODE ) {
408 - $return = false;
479 + $disabled = false;
409 480 break;
410 481 }
411 482 }
412 483
413 484 if ( \defined( 'ACTIVITYPUB_DISABLE_BLOG_USER' ) ) {
414 - $return = ACTIVITYPUB_DISABLE_BLOG_USER;
485 + $disabled = ACTIVITYPUB_DISABLE_BLOG_USER;
415 486 break;
416 487 }
417 488
418 - if ( '1' !== \get_option( 'activitypub_enable_blog_user', '0' ) ) {
419 - $return = true;
489 + if ( ACTIVITYPUB_ACTOR_MODE === \get_option( 'activitypub_actor_mode', ACTIVITYPUB_ACTOR_MODE ) ) {
490 + $disabled = true;
420 491 break;
421 492 }
422 493
423 - $return = false;
494 + $disabled = false;
424 495 break;
425 496 case 'user':
426 497 if ( \defined( 'ACTIVITYPUB_SINGLE_USER_MODE' ) ) {
427 498 if ( ACTIVITYPUB_SINGLE_USER_MODE ) {
428 - $return = true;
499 + $disabled = true;
429 500 break;
430 501 }
431 502 }
432 503
433 504 if ( \defined( 'ACTIVITYPUB_DISABLE_USER' ) ) {
434 - $return = ACTIVITYPUB_DISABLE_USER;
505 + $disabled = ACTIVITYPUB_DISABLE_USER;
435 506 break;
436 507 }
437 508
438 - if ( '1' !== \get_option( 'activitypub_enable_users', '1' ) ) {
439 - $return = true;
509 + if ( ACTIVITYPUB_BLOG_MODE === \get_option( 'activitypub_actor_mode', ACTIVITYPUB_ACTOR_MODE ) ) {
510 + $disabled = true;
440 511 break;
441 512 }
442 513
443 - $return = false;
514 + $disabled = false;
444 515 break;
445 516 default:
446 - $return = new WP_Error( 'activitypub_wrong_user_type', __( 'Wrong user type', 'activitypub' ), array( 'status' => 400 ) );
517 + $disabled = new WP_Error(
518 + 'activitypub_wrong_user_type',
519 + __( 'Wrong user type', 'activitypub' ),
520 + array( 'status' => 400 )
521 + );
447 522 break;
448 523 }
449 524
450 - return apply_filters( 'activitypub_is_user_type_disabled', $return, $type );
525 + /**
526 + * Allow plugins to disable user types for ActivityPub.
527 + *
528 + * @param boolean $disabled True if the user type is disabled, false otherwise.
529 + * @param string $type The User-Type.
530 + */
531 + return apply_filters( 'activitypub_is_user_type_disabled', $disabled, $type );
451 532 }
452 533
453 534 /**
454 535 * Check if the blog is in single-user mode.
@@ -475,9 +556,12 @@
475 556 if ( \version_compare( \get_bloginfo( 'version' ), '5.9', '<' ) ) {
476 557 return false;
477 558 }
478 559
479 - if ( ! \function_exists( 'register_block_type_from_metadata' ) ) {
560 + if (
561 + ! \function_exists( 'register_block_type_from_metadata' ) ||
562 + ! \function_exists( 'do_blocks' )
563 + ) {
480 564 return false;
481 565 }
482 566
483 567 /**
@@ -500,22 +584,27 @@
500 584 return \is_array( \json_decode( $data, true ) ) ? true : false;
501 585 }
502 586
503 587 /**
504 - * Check if a blog is public based on the `blog_public` option
588 + * Check whether a blog is public based on the `blog_public` option.
505 589 *
506 - * @return bollean True if public, false if not
590 + * @return bool True if public, false if not
507 591 */
508 592 function is_blog_public() {
593 + /**
594 + * Filter whether the blog is public.
595 + *
596 + * @param bool $public Whether the blog is public.
597 + */
509 598 return (bool) apply_filters( 'activitypub_is_blog_public', \get_option( 'blog_public', 1 ) );
510 599 }
511 600
512 601 /**
513 - * Sanitize a URL
602 + * Sanitize a URL.
514 603 *
515 - * @param string $value The URL to sanitize
604 + * @param string $value The URL to sanitize.
516 605 *
517 - * @return string|null The sanitized URL or null if invalid
606 + * @return string|null The sanitized URL or null if invalid.
518 607 */
519 608 function sanitize_url( $value ) {
520 609 if ( filter_var( $value, FILTER_VALIDATE_URL ) === false ) {
521 610 return null;
@@ -524,13 +613,13 @@
524 613 return esc_url_raw( $value );
525 614 }
526 615
527 616 /**
528 - * Extract recipient URLs from Activity object
617 + * Extract recipient URLs from Activity object.
529 618 *
530 - * @param array $data
619 + * @param array $data The Activity object as array.
531 620 *
532 - * @return array The list of user URLs
621 + * @return array The list of user URLs.
533 622 */
534 623 function extract_recipients_from_activity( $data ) {
535 624 $recipient_items = array();
536 625
@@ -555,12 +644,12 @@
555 644 }
556 645
557 646 $recipients = array();
558 647
559 - // flatten array
648 + // Flatten array.
560 649 foreach ( $recipient_items as $recipient ) {
561 650 if ( is_array( $recipient ) ) {
562 - // check if recipient is an object
651 + // Check if recipient is an object.
563 652 if ( array_key_exists( 'id', $recipient ) ) {
564 653 $recipients[] = $recipient['id'];
565 654 }
566 655 } else {
@@ -571,13 +660,13 @@
571 660 return array_unique( $recipients );
572 661 }
573 662
574 663 /**
575 - * Check if passed Activity is Public
664 + * Check if passed Activity is Public.
576 665 *
577 - * @param array $data The Activity object as array
666 + * @param array $data The Activity object as array.
578 667 *
579 - * @return boolean True if public, false if not
668 + * @return boolean True if public, false if not.
580 669 */
581 670 function is_activity_public( $data ) {
582 671 $recipients = extract_recipients_from_activity( $data );
583 672
@@ -584,55 +673,71 @@
584 673 return in_array( 'https://www.w3.org/ns/activitystreams#Public', $recipients, true );
585 674 }
586 675
587 676 /**
588 - * Get active users based on a given duration
677 + * Check if passed Activity is a reply.
589 678 *
590 - * @param int $duration The duration to check in month(s)
679 + * @param array $data The Activity object as array.
591 680 *
592 - * @return int The number of active users
681 + * @return boolean True if a reply, false if not.
593 682 */
683 +function is_activity_reply( $data ) {
684 + return ! empty( $data['object']['inReplyTo'] );
685 +}
686 +
687 +/**
688 + * Get active users based on a given duration.
689 + *
690 + * @param int $duration Optional. The duration to check in month(s). Default 1.
691 + *
692 + * @return int The number of active users.
693 + */
594 694 function get_active_users( $duration = 1 ) {
595 695
596 - $duration = intval( $duration );
696 + $duration = intval( $duration );
597 697 $transient_key = sprintf( 'monthly_active_users_%d', $duration );
598 - $count = get_transient( $transient_key );
698 + $count = get_transient( $transient_key );
599 699
600 700 if ( false === $count ) {
601 701 global $wpdb;
602 - $query = "SELECT COUNT( DISTINCT post_author ) FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date <= DATE_SUB( NOW(), INTERVAL %d MONTH )";
603 - $query = $wpdb->prepare( $query, $duration );
604 - $count = $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
605 702
703 + // phpcs:ignore WordPress.DB.DirectDatabaseQuery
704 + $count = $wpdb->get_var(
705 + $wpdb->prepare(
706 + "SELECT COUNT( DISTINCT post_author ) FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date <= DATE_SUB( NOW(), INTERVAL %d MONTH )",
707 + $duration
708 + )
709 + );
710 +
606 711 set_transient( $transient_key, $count, DAY_IN_SECONDS );
607 712 }
608 713
609 - // if 0 authors where active
714 + // If 0 authors where active.
610 715 if ( 0 === $count ) {
611 716 return 0;
612 717 }
613 718
614 - // if single user mode
719 + // If single user mode.
615 720 if ( is_single_user() ) {
616 721 return 1;
617 722 }
618 723
619 - // if blog user is disabled
620 - if ( is_user_disabled( Users::BLOG_USER_ID ) ) {
621 - return $count;
724 + // If blog user is disabled.
725 + if ( is_user_disabled( Actors::BLOG_USER_ID ) ) {
726 + return (int) $count;
622 727 }
623 728
624 - // also count blog user
625 - return $count + 1;
729 + // Also count blog user.
730 + return (int) $count + 1;
626 731 }
627 732
628 733 /**
629 - * Get the total number of users
734 + * Get the total number of users.
630 735 *
631 - * @return int The total number of users
736 + * @return int The total number of users.
632 737 */
633 738 function get_total_users() {
634 - // if single user mode
739 + // If single user mode.
635 740 if ( is_single_user() ) {
636 741 return 1;
637 742 }
638 743
@@ -637,9 +742,9 @@
637 742 }
638 743
639 744 $users = \get_users(
640 745 array(
641 - 'capability__in' => array( 'publish_posts' ),
746 + 'capability__in' => array( 'activitypub' ),
642 747 )
643 748 );
644 749
645 750 if ( is_array( $users ) ) {
@@ -647,14 +752,14 @@
647 752 } else {
648 753 $users = 1;
649 754 }
650 755
651 - // if blog user is disabled
652 - if ( is_user_disabled( Users::BLOG_USER_ID ) ) {
653 - return $users;
756 + // If blog user is disabled.
757 + if ( is_user_disabled( Actors::BLOG_USER_ID ) ) {
758 + return (int) $users;
654 759 }
655 760
656 - return $users + 1;
761 + return (int) $users + 1;
657 762 }
658 763
659 764 /**
660 765 * Examine a comment ID and look up an existing comment it represents.
@@ -660,117 +765,960 @@
660 765 * Examine a comment ID and look up an existing comment it represents.
661 766 *
662 767 * @param string $id ActivityPub object ID (usually a URL) to check.
663 768 *
664 - * @return int|boolean Comment ID, or false on failure.
769 + * @return \WP_Comment|boolean Comment, or false on failure.
665 770 */
666 771 function object_id_to_comment( $id ) {
667 - $comment_query = new WP_Comment_Query(
668 - array(
669 - 'meta_key' => 'source_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
670 - 'meta_value' => $id, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
671 - )
772 + return Comment::object_id_to_comment( $id );
773 +}
774 +
775 +/**
776 + * Verify that URL is a local comment or a previously received remote comment.
777 + * (For threading comments locally)
778 + *
779 + * @param string $url The URL to check.
780 + *
781 + * @return string|null Comment ID or null if not found
782 + */
783 +function url_to_commentid( $url ) {
784 + return Comment::url_to_commentid( $url );
785 +}
786 +
787 +/**
788 + * Get the URI of an ActivityPub object.
789 + *
790 + * @param array|string $data The ActivityPub object.
791 + *
792 + * @return string The URI of the ActivityPub object
793 + */
794 +function object_to_uri( $data ) {
795 + // Check whether it is already simple.
796 + if ( ! $data || is_string( $data ) ) {
797 + return $data;
798 + }
799 +
800 + /*
801 + * Check if it is a list, then take first item.
802 + * This plugin does not support collections.
803 + */
804 + if ( array_is_list( $data ) ) {
805 + $data = $data[0];
806 + }
807 +
808 + // Check if it is simplified now.
809 + if ( is_string( $data ) ) {
810 + return $data;
811 + }
812 +
813 + $type = 'Object';
814 + if ( isset( $data['type'] ) ) {
815 + $type = $data['type'];
816 + }
817 +
818 + // Return part of Object that makes most sense.
819 + switch ( $type ) {
820 + case 'Image':
821 + $data = $data['url'];
822 + break;
823 + case 'Link':
824 + $data = $data['href'];
825 + break;
826 + default:
827 + $data = $data['id'];
828 + break;
829 + }
830 +
831 + return $data;
832 +}
833 +
834 +/**
835 + * Check if a comment should be federated.
836 + *
837 + * We consider a comment should be federated if it is authored by a user that is
838 + * not disabled for federation and if it is a reply directly to the post or to a
839 + * federated comment.
840 + *
841 + * @param mixed $comment Comment object or ID.
842 + *
843 + * @return boolean True if the comment should be federated, false otherwise.
844 + */
845 +function should_comment_be_federated( $comment ) {
846 + return Comment::should_be_federated( $comment );
847 +}
848 +
849 +/**
850 + * Check if a comment was federated.
851 + *
852 + * This function checks if a comment was federated via ActivityPub.
853 + *
854 + * @param mixed $comment Comment object or ID.
855 + *
856 + * @return boolean True if the comment was federated, false otherwise.
857 + */
858 +function was_comment_sent( $comment ) {
859 + return Comment::was_sent( $comment );
860 +}
861 +
862 +/**
863 + * Check if a comment is federated.
864 + *
865 + * We consider a comment federated if comment was received via ActivityPub.
866 + *
867 + * Use this function to check if it is comment that was received via ActivityPub.
868 + *
869 + * @param mixed $comment Comment object or ID.
870 + *
871 + * @return boolean True if the comment is federated, false otherwise.
872 + */
873 +function was_comment_received( $comment ) {
874 + return Comment::was_received( $comment );
875 +}
876 +
877 +/**
878 + * Check if a comment is local only.
879 + *
880 + * This function checks if a comment is local only and was not sent or received via ActivityPub.
881 + *
882 + * @param mixed $comment Comment object or ID.
883 + *
884 + * @return boolean True if the comment is local only, false otherwise.
885 + */
886 +function is_local_comment( $comment ) {
887 + return Comment::is_local( $comment );
888 +}
889 +
890 +/**
891 + * Mark a WordPress object as federated.
892 + *
893 + * @param \WP_Comment|\WP_Post $wp_object The WordPress object.
894 + * @param string $state The state of the object.
895 + */
896 +function set_wp_object_state( $wp_object, $state ) {
897 + $meta_key = 'activitypub_status';
898 +
899 + if ( $wp_object instanceof \WP_Post ) {
900 + \update_post_meta( $wp_object->ID, $meta_key, $state );
901 + } elseif ( $wp_object instanceof \WP_Comment ) {
902 + \update_comment_meta( $wp_object->comment_ID, $meta_key, $state );
903 + } else {
904 + /**
905 + * Allow plugins to mark WordPress objects as federated.
906 + *
907 + * @param \WP_Comment|\WP_Post $wp_object The WordPress object.
908 + * @param string $state The state of the object.
909 + */
910 + \apply_filters( 'activitypub_mark_wp_object_as_federated', $wp_object );
911 + }
912 +}
913 +
914 +/**
915 + * Get the federation state of a WordPress object.
916 + *
917 + * @param \WP_Comment|\WP_Post $wp_object The WordPress object.
918 + *
919 + * @return string|false The state of the object or false if not found.
920 + */
921 +function get_wp_object_state( $wp_object ) {
922 + $meta_key = 'activitypub_status';
923 +
924 + if ( $wp_object instanceof \WP_Post ) {
925 + return \get_post_meta( $wp_object->ID, $meta_key, true );
926 + } elseif ( $wp_object instanceof \WP_Comment ) {
927 + return \get_comment_meta( $wp_object->comment_ID, $meta_key, true );
928 + } else {
929 + /**
930 + * Allow plugins to get the federation state of a WordPress object.
931 + *
932 + * @param \WP_Comment|\WP_Post $wp_object The WordPress object.
933 + */
934 + return \apply_filters( 'activitypub_get_wp_object_state', false, $wp_object );
935 + }
936 +}
937 +
938 +/**
939 + * Get the description of a post type.
940 + *
941 + * Set some default descriptions for the default post types.
942 + *
943 + * @param \WP_Post_Type $post_type The post type object.
944 + *
945 + * @return string The description of the post type.
946 + */
947 +function get_post_type_description( $post_type ) {
948 + $description = '';
949 +
950 + switch ( $post_type->name ) {
951 + case 'post':
952 + $description = '';
953 + break;
954 + case 'page':
955 + $description = '';
956 + break;
957 + case 'attachment':
958 + $description = ' - ' . __( 'The attachments that you have uploaded to a post (images, videos, documents or other files).', 'activitypub' );
959 + break;
960 + default:
961 + if ( ! empty( $post_type->description ) ) {
962 + $description = ' - ' . $post_type->description;
963 + }
964 + }
965 +
966 + /**
967 + * Allow plugins to get the description of a post type.
968 + *
969 + * @param string $description The description of the post type.
970 + * @param \WP_Post_Type $post_type The post type object.
971 + */
972 + return apply_filters( 'activitypub_post_type_description', $description, $post_type->name, $post_type );
973 +}
974 +
975 +/**
976 + * Get the masked WordPress version to only show the major and minor version.
977 + *
978 + * @return string The masked version.
979 + */
980 +function get_masked_wp_version() {
981 + // Only show the major and minor version.
982 + $version = get_bloginfo( 'version' );
983 + // Strip the RC or beta part.
984 + $version = preg_replace( '/-.*$/', '', $version );
985 + $version = explode( '.', $version );
986 + $version = array_slice( $version, 0, 2 );
987 +
988 + return implode( '.', $version );
989 +}
990 +
991 +/**
992 + * Get the enclosures of a post.
993 + *
994 + * @param int $post_id The post ID.
995 + *
996 + * @return array The enclosures.
997 + */
998 +function get_enclosures( $post_id ) {
999 + $enclosures = get_post_meta( $post_id, 'enclosure', false );
1000 +
1001 + if ( ! $enclosures ) {
1002 + return array();
1003 + }
1004 +
1005 + $enclosures = array_map(
1006 + function ( $enclosure ) {
1007 + // Check if the enclosure is a string.
1008 + if ( ! $enclosure || ! is_string( $enclosure ) ) {
1009 + return false;
1010 + }
1011 +
1012 + $attributes = explode( "\n", $enclosure );
1013 +
1014 + if ( ! isset( $attributes[0] ) || ! \wp_http_validate_url( $attributes[0] ) ) {
1015 + return false;
1016 + }
1017 +
1018 + return array(
1019 + 'url' => $attributes[0],
1020 + 'length' => $attributes[1] ?? null,
1021 + 'mediaType' => $attributes[2] ?? 'application/octet-stream',
1022 + );
1023 + },
1024 + $enclosures
672 1025 );
673 1026
674 - if ( ! $comment_query->comments ) {
1027 + return array_filter( $enclosures );
1028 +}
1029 +
1030 +/**
1031 + * Retrieves the IDs of the ancestors of a comment.
1032 + *
1033 + * Adaption of `get_post_ancestors` from WordPress core.
1034 + *
1035 + * @see https://developer.wordpress.org/reference/functions/get_post_ancestors/
1036 + *
1037 + * @param int|\WP_Comment $comment Comment ID or comment object.
1038 + *
1039 + * @return int[] Array of ancestor IDs.
1040 + */
1041 +function get_comment_ancestors( $comment ) {
1042 + $comment = \get_comment( $comment );
1043 +
1044 + if ( ! $comment || empty( $comment->comment_parent ) || (int) $comment->comment_parent === (int) $comment->comment_ID ) {
1045 + return array();
1046 + }
1047 +
1048 + $ancestors = array();
1049 +
1050 + $id = (int) $comment->comment_parent;
1051 + $ancestors[] = $id;
1052 +
1053 + while ( $id > 0 ) {
1054 + $ancestor = \get_comment( $id );
1055 + $parent_id = (int) $ancestor->comment_parent;
1056 +
1057 + // Loop detection: If the ancestor has been seen before, break.
1058 + if ( empty( $parent_id ) || ( $parent_id === (int) $comment->comment_ID ) || in_array( $parent_id, $ancestors, true ) ) {
1059 + break;
1060 + }
1061 +
1062 + $id = $parent_id;
1063 + $ancestors[] = $id;
1064 + }
1065 +
1066 + return $ancestors;
1067 +}
1068 +
1069 +/**
1070 + * Change the display of large numbers on the site.
1071 + *
1072 + * @author Jeremy Herve
1073 + *
1074 + * @see https://wordpress.org/support/topic/abbreviate-numbers-with-k/
1075 + *
1076 + * @param string $formatted Converted number in string format.
1077 + * @param float $number The number to convert based on locale.
1078 + * @param int $decimals Precision of the number of decimal places.
1079 + *
1080 + * @return string Converted number in string format.
1081 + */
1082 +function custom_large_numbers( $formatted, $number, $decimals ) {
1083 + global $wp_locale;
1084 +
1085 + $decimals = 0;
1086 + $decimal_point = '.';
1087 + $thousands_sep = ',';
1088 +
1089 + if ( isset( $wp_locale ) ) {
1090 + $decimals = (int) $wp_locale->number_format['decimal_point'];
1091 + $decimal_point = $wp_locale->number_format['decimal_point'];
1092 + $thousands_sep = $wp_locale->number_format['thousands_sep'];
1093 + }
1094 +
1095 + if ( $number < 1000 ) { // Any number less than a Thousand.
1096 + return \number_format( $number, $decimals, $decimal_point, $thousands_sep );
1097 + } elseif ( $number < 1000000 ) { // Any number less than a million.
1098 + return \number_format( $number / 1000, $decimals, $decimal_point, $thousands_sep ) . 'K';
1099 + } elseif ( $number < 1000000000 ) { // Any number less than a billion.
1100 + return \number_format( $number / 1000000, $decimals, $decimal_point, $thousands_sep ) . 'M';
1101 + } else { // At least a billion.
1102 + return \number_format( $number / 1000000000, $decimals, $decimal_point, $thousands_sep ) . 'B';
1103 + }
1104 +
1105 + // Default fallback. We should not get here.
1106 + return $formatted;
1107 +}
1108 +
1109 +/**
1110 + * Registers a ActivityPub comment type.
1111 + *
1112 + * @param string $comment_type Key for comment type.
1113 + * @param array $args Optional. Array of arguments for registering a comment type. Default empty array.
1114 + *
1115 + * @return array The registered Activitypub comment type.
1116 + */
1117 +function register_comment_type( $comment_type, $args = array() ) {
1118 + global $activitypub_comment_types;
1119 +
1120 + if ( ! is_array( $activitypub_comment_types ) ) {
1121 + $activitypub_comment_types = array();
1122 + }
1123 +
1124 + // Sanitize comment type name.
1125 + $comment_type = sanitize_key( $comment_type );
1126 +
1127 + $activitypub_comment_types[ $comment_type ] = $args;
1128 +
1129 + /**
1130 + * Fires after a ActivityPub comment type is registered.
1131 + *
1132 + * @param string $comment_type Comment type.
1133 + * @param array $args Arguments used to register the comment type.
1134 + */
1135 + do_action( 'activitypub_registered_comment_type', $comment_type, $args );
1136 +
1137 + return $args;
1138 +}
1139 +
1140 +/**
1141 + * Normalize a URL.
1142 + *
1143 + * @param string $url The URL.
1144 + *
1145 + * @return string The normalized URL.
1146 + */
1147 +function normalize_url( $url ) {
1148 + $url = \untrailingslashit( $url );
1149 + $url = \str_replace( 'https://', '', $url );
1150 + $url = \str_replace( 'http://', '', $url );
1151 + $url = \str_replace( 'www.', '', $url );
1152 +
1153 + return $url;
1154 +}
1155 +
1156 +/**
1157 + * Normalize a host.
1158 + *
1159 + * @param string $host The host.
1160 + *
1161 + * @return string The normalized host.
1162 + */
1163 +function normalize_host( $host ) {
1164 + return \str_replace( 'www.', '', $host );
1165 +}
1166 +
1167 +/**
1168 + * Get the reply intent URI as a JavaScript URI.
1169 + *
1170 + * @return string The reply intent URI.
1171 + */
1172 +function get_reply_intent_js() {
1173 + return sprintf(
1174 + 'javascript:(()=>{window.open(\'%s\'+encodeURIComponent(window.location.href));})();',
1175 + get_reply_intent_url()
1176 + );
1177 +}
1178 +
1179 +/**
1180 + * Get the reply intent URI.
1181 + *
1182 + * @return string The reply intent URI.
1183 + */
1184 +function get_reply_intent_url() {
1185 + /**
1186 + * Filters the reply intent parameters.
1187 + *
1188 + * @param array $params The reply intent parameters.
1189 + */
1190 + $params = \apply_filters( 'activitypub_reply_intent_params', array() );
1191 +
1192 + $params += array( 'in_reply_to' => '' );
1193 + $query = \http_build_query( $params );
1194 + $path = 'post-new.php?' . $query;
1195 + $url = \admin_url( $path );
1196 +
1197 + /**
1198 + * Filters the reply intent URL.
1199 + *
1200 + * @param string $url The reply intent URL.
1201 + */
1202 + $url = \apply_filters( 'activitypub_reply_intent_url', $url );
1203 +
1204 + return esc_url_raw( $url );
1205 +}
1206 +
1207 +/**
1208 + * Replace content with links, mentions or hashtags by Regex callback and not affect protected tags.
1209 + *
1210 + * @param string $content The content that should be changed.
1211 + * @param string $regex The regex to use.
1212 + * @param callable $regex_callback Callback for replacement logic.
1213 + *
1214 + * @return string The content with links, mentions, hashtags, etc.
1215 + */
1216 +function enrich_content_data( $content, $regex, $regex_callback ) {
1217 + // Small protection against execution timeouts: limit to 1 MB.
1218 + if ( mb_strlen( $content ) > MB_IN_BYTES ) {
1219 + return $content;
1220 + }
1221 + $tag_stack = array();
1222 + $protected_tags = array(
1223 + 'pre',
1224 + 'code',
1225 + 'textarea',
1226 + 'style',
1227 + 'a',
1228 + );
1229 + $content_with_links = '';
1230 + $in_protected_tag = false;
1231 + foreach ( wp_html_split( $content ) as $chunk ) {
1232 + if ( preg_match( '#^<!--[\s\S]*-->$#i', $chunk, $m ) ) {
1233 + $content_with_links .= $chunk;
1234 + continue;
1235 + }
1236 +
1237 + if ( preg_match( '#^<(/)?([a-z-]+)\b[^>]*>$#i', $chunk, $m ) ) {
1238 + $tag = strtolower( $m[2] );
1239 + if ( '/' === $m[1] ) {
1240 + // Closing tag.
1241 + $i = array_search( $tag, $tag_stack, true );
1242 + // We can only remove the tag from the stack if it is in the stack.
1243 + if ( false !== $i ) {
1244 + $tag_stack = array_slice( $tag_stack, 0, $i );
1245 + }
1246 + } else {
1247 + // Opening tag, add it to the stack.
1248 + $tag_stack[] = $tag;
1249 + }
1250 +
1251 + // If we're in a protected tag, the tag_stack contains at least one protected tag string.
1252 + // The protected tag state can only change when we encounter a start or end tag.
1253 + $in_protected_tag = array_intersect( $tag_stack, $protected_tags );
1254 +
1255 + // Never inspect tags.
1256 + $content_with_links .= $chunk;
1257 + continue;
1258 + }
1259 +
1260 + if ( $in_protected_tag ) {
1261 + // Don't inspect a chunk inside an inspected tag.
1262 + $content_with_links .= $chunk;
1263 + continue;
1264 + }
1265 +
1266 + // Only reachable when there is no protected tag in the stack.
1267 + $content_with_links .= \preg_replace_callback( $regex, $regex_callback, $chunk );
1268 + }
1269 +
1270 + return $content_with_links;
1271 +}
1272 +
1273 +/**
1274 + * Generate a summary of a post.
1275 + *
1276 + * This function generates a summary of a post by extracting:
1277 + *
1278 + * 1. The post excerpt if it exists.
1279 + * 2. The first part of the post content if it contains the <!--more--> tag.
1280 + * 3. An excerpt of the post content if it is longer than the specified length.
1281 + *
1282 + * @param int|\WP_Post $post The post ID or post object.
1283 + * @param integer $length The maximum length of the summary.
1284 + * Default is 500. It will be ignored if the post excerpt
1285 + * and the content above the <!--more--> tag.
1286 + *
1287 + * @return string The generated post summary.
1288 + */
1289 +function generate_post_summary( $post, $length = 500 ) {
1290 + $post = get_post( $post );
1291 +
1292 + if ( ! $post ) {
1293 + return '';
1294 + }
1295 +
1296 + $content = \sanitize_post_field( 'post_excerpt', $post->post_excerpt, $post->ID );
1297 +
1298 + if ( $content ) {
1299 + /** This filter is documented in wp-includes/post-template.php */
1300 + return \apply_filters( 'the_excerpt', $content );
1301 + }
1302 +
1303 + $content = \sanitize_post_field( 'post_content', $post->post_content, $post->ID );
1304 + $content_parts = \get_extended( $content );
1305 +
1306 + /**
1307 + * Filters the excerpt more value.
1308 + *
1309 + * @param string $excerpt_more The excerpt more.
1310 + */
1311 + $excerpt_more = \apply_filters( 'activitypub_excerpt_more', '[…]' );
1312 + $length = $length - strlen( $excerpt_more );
1313 +
1314 + // Check for the <!--more--> tag.
1315 + if (
1316 + ! empty( $content_parts['extended'] ) &&
1317 + ! empty( $content_parts['main'] )
1318 + ) {
1319 + $content = $content_parts['main'] . ' ' . $excerpt_more;
1320 + $length = null;
1321 + }
1322 +
1323 + $content = \html_entity_decode( $content );
1324 + $content = \wp_strip_all_tags( $content );
1325 + $content = \trim( $content );
1326 + $content = \preg_replace( '/\R+/m', "\n\n", $content );
1327 + $content = \preg_replace( '/[\r\t]/', '', $content );
1328 +
1329 + if ( $length && \strlen( $content ) > $length ) {
1330 + $content = \wordwrap( $content, $length, '</activitypub-summary>' );
1331 + $content = \explode( '</activitypub-summary>', $content, 2 );
1332 + $content = $content[0] . ' ' . $excerpt_more;
1333 + }
1334 +
1335 + /*
1336 + Removed until this is merged: https://github.com/mastodon/mastodon/pull/28629
1337 + /** This filter is documented in wp-includes/post-template.php
1338 + return \apply_filters( 'the_excerpt', $content );
1339 + */
1340 + return $content;
1341 +}
1342 +
1343 +/**
1344 + * Get the content warning of a post.
1345 + *
1346 + * @param int|\WP_Post $post_id The post ID or post object.
1347 + *
1348 + * @return string|false The content warning or false if not found.
1349 + */
1350 +function get_content_warning( $post_id ) {
1351 + $post = get_post( $post_id );
1352 + if ( ! $post ) {
675 1353 return false;
676 1354 }
677 1355
678 - if ( count( $comment_query->comments ) > 1 ) {
1356 + $warning = get_post_meta( $post->ID, 'activitypub_content_warning', true );
1357 + if ( empty( $warning ) ) {
679 1358 return false;
680 1359 }
681 1360
682 - return $comment_query->comments[0];
1361 + return $warning;
683 1362 }
684 1363
685 1364 /**
686 - * Verify if URL is a local comment,
687 - * Or if it is a previously received remote comment
688 - * (For threading comments locally)
1365 + * Get the ActivityPub ID of a User by the WordPress User ID.
689 1366 *
1367 + * @param int $id The WordPress User ID.
1368 + *
1369 + * @return string The ActivityPub ID (a URL) of the User.
1370 + */
1371 +function get_user_id( $id ) {
1372 + $user = Actors::get_by_id( $id );
1373 +
1374 + if ( ! $user ) {
1375 + return false;
1376 + }
1377 +
1378 + return $user->get_id();
1379 +}
1380 +
1381 +/**
1382 + * Get the ActivityPub ID of a Post by the WordPress Post ID.
1383 + *
1384 + * @param int $id The WordPress Post ID.
1385 + *
1386 + * @return string The ActivityPub ID (a URL) of the Post.
1387 + */
1388 +function get_post_id( $id ) {
1389 + $post = get_post( $id );
1390 +
1391 + if ( ! $post ) {
1392 + return false;
1393 + }
1394 +
1395 + $transformer = new Post( $post );
1396 + return $transformer->get_id();
1397 +}
1398 +
1399 +/**
1400 + * Check if a URL is from the same domain as the site.
1401 + *
690 1402 * @param string $url The URL to check.
691 1403 *
692 - * @return int comment_ID or null if not found
1404 + * @return boolean True if the URL is from the same domain, false otherwise.
693 1405 */
694 -function url_to_commentid( $url ) {
695 - if ( ! $url || ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
1406 +function is_same_domain( $url ) {
1407 + $remote = \wp_parse_url( $url, PHP_URL_HOST );
1408 +
1409 + if ( ! $remote ) {
1410 + return false;
1411 + }
1412 +
1413 + $remote = normalize_host( $remote );
1414 + $self = normalize_host( home_host() );
1415 +
1416 + return $remote === $self;
1417 +}
1418 +
1419 +/**
1420 + * Get the visibility of a post.
1421 + *
1422 + * @param int $post_id The post ID.
1423 + *
1424 + * @return string|false The visibility of the post or false if not found.
1425 + */
1426 +function get_content_visibility( $post_id ) {
1427 + $post = get_post( $post_id );
1428 + if ( ! $post ) {
1429 + return false;
1430 + }
1431 +
1432 + $visibility = \get_post_meta( $post->ID, 'activitypub_content_visibility', true );
1433 + $_visibility = ACTIVITYPUB_CONTENT_VISIBILITY_PUBLIC;
1434 + $options = array(
1435 + ACTIVITYPUB_CONTENT_VISIBILITY_QUIET_PUBLIC,
1436 + ACTIVITYPUB_CONTENT_VISIBILITY_PRIVATE,
1437 + ACTIVITYPUB_CONTENT_VISIBILITY_LOCAL,
1438 + );
1439 +
1440 + if ( in_array( $visibility, $options, true ) ) {
1441 + $_visibility = $visibility;
1442 + }
1443 +
1444 + /**
1445 + * Filters the visibility of a post.
1446 + *
1447 + * @param string $_visibility The visibility of the post. Possible values are:
1448 + * - 'public': Post is public and federated.
1449 + * - 'quiet_public': Post is public but not federated.
1450 + * - 'local': Post is only visible locally.
1451 + * @param \WP_Post $post The post object.
1452 + */
1453 + return \apply_filters( 'activitypub_content_visibility', $_visibility, $post );
1454 +}
1455 +
1456 +/**
1457 + * Retrieves the Host for the current site where the front end is accessible.
1458 + *
1459 + * @return string The host for the current site.
1460 + */
1461 +function home_host() {
1462 + return \wp_parse_url( \home_url(), PHP_URL_HOST );
1463 +}
1464 +
1465 +/**
1466 + * Returns the website hosts allowed to credit this blog.
1467 + *
1468 + * @return array|null The attribution domains or null if not found.
1469 + */
1470 +function get_attribution_domains() {
1471 + if ( '1' !== \get_option( 'activitypub_use_opengraph', '1' ) ) {
696 1472 return null;
697 1473 }
698 1474
699 - // check for local comment
700 - if ( \wp_parse_url( \site_url(), \PHP_URL_HOST ) === \wp_parse_url( $url, \PHP_URL_HOST ) ) {
701 - $query = \wp_parse_url( $url, PHP_URL_QUERY );
1475 + $domains = \get_option( 'activitypub_attribution_domains', home_host() );
1476 + $domains = explode( PHP_EOL, $domains );
702 1477
703 - if ( $query ) {
704 - parse_str( $query, $params );
1478 + if ( ! $domains ) {
1479 + $domains = null;
1480 + }
705 1481
706 - if ( ! empty( $params['c'] ) ) {
707 - $comment = \get_comment( $params['c'] );
1482 + return $domains;
1483 +}
708 1484
709 - if ( $comment ) {
710 - return $comment->comment_ID;
711 - }
712 - }
1485 +/**
1486 + * Get the base URL for uploads.
1487 + *
1488 + * @return string The upload base URL.
1489 + */
1490 +function get_upload_baseurl() {
1491 + /**
1492 + * Early filter to allow plugins to set the upload base URL.
1493 + *
1494 + * @param string|false $maybe_upload_dir The upload base URL or false if not set.
1495 + */
1496 + $maybe_upload_dir = apply_filters( 'pre_activitypub_get_upload_baseurl', false );
1497 + if ( false !== $maybe_upload_dir ) {
1498 + return $maybe_upload_dir;
1499 + }
1500 +
1501 + $upload_dir = \wp_get_upload_dir();
1502 +
1503 + /**
1504 + * Filters the upload base URL.
1505 + *
1506 + * @param string $upload_dir The upload base URL. Default \wp_get_upload_dir()['baseurl']
1507 + */
1508 + return apply_filters( 'activitypub_get_upload_baseurl', $upload_dir['baseurl'] );
1509 +}
1510 +
1511 +/**
1512 + * Check if Authorized-Fetch is enabled.
1513 + *
1514 + * @see https://docs.joinmastodon.org/admin/config/#authorized_fetch
1515 + *
1516 + * @return boolean True if Authorized-Fetch is enabled, false otherwise.
1517 + */
1518 +function use_authorized_fetch() {
1519 + $use = false;
1520 +
1521 + // Prefer the constant over the option.
1522 + if ( \defined( 'ACTIVITYPUB_AUTHORIZED_FETCH' ) ) {
1523 + $use = ACTIVITYPUB_AUTHORIZED_FETCH;
1524 + } else {
1525 + $use = (bool) \get_option( 'activitypub_authorized_fetch', '0' );
1526 + }
1527 +
1528 + /**
1529 + * Filters whether to use Authorized-Fetch.
1530 + *
1531 + * @param boolean $use_authorized_fetch True if Authorized-Fetch is enabled, false otherwise.
1532 + */
1533 + return apply_filters( 'activitypub_use_authorized_fetch', $use );
1534 +}
1535 +
1536 +/**
1537 + * Check if an ID is from the same domain as the site.
1538 + *
1539 + * @param string $id The ID URI to check.
1540 + *
1541 + * @return boolean True if the ID is a self-pint, false otherwise.
1542 + */
1543 +function is_self_ping( $id ) {
1544 + $query_string = \wp_parse_url( $id, PHP_URL_QUERY );
1545 +
1546 + if ( ! $query_string ) {
1547 + return false;
1548 + }
1549 +
1550 + $query = array();
1551 + \parse_str( $query_string, $query );
1552 +
1553 + if (
1554 + is_same_domain( $id ) &&
1555 + in_array( 'c', array_keys( $query ), true )
1556 + ) {
1557 + return true;
1558 + }
1559 +
1560 + return false;
1561 +}
1562 +
1563 +/**
1564 + * Add an object to the outbox.
1565 + *
1566 + * @param mixed $data The object to add to the outbox.
1567 + * @param string $activity_type The type of the Activity.
1568 + * @param integer $user_id The User-ID.
1569 + * @param string $content_visibility The visibility of the content. See `constants.php` for possible values: `ACTIVITYPUB_CONTENT_VISIBILITY_*`.
1570 + *
1571 + * @return boolean|int The ID of the outbox item or false on failure.
1572 + */
1573 +function add_to_outbox( $data, $activity_type = 'Create', $user_id = 0, $content_visibility = null ) {
1574 + $transformer = Transformer_Factory::get_transformer( $data );
1575 +
1576 + if ( ! $transformer || is_wp_error( $transformer ) ) {
1577 + return false;
1578 + }
1579 +
1580 + if ( $content_visibility ) {
1581 + $transformer->set_content_visibility( $content_visibility );
1582 + } else {
1583 + $content_visibility = $transformer->get_content_visibility();
1584 + }
1585 +
1586 + $activity_object = $transformer->to_object();
1587 +
1588 + if ( ! $activity_object || \is_wp_error( $activity_object ) ) {
1589 + return false;
1590 + }
1591 +
1592 + // If the user is disabled, fall back to the blog user when available.
1593 + if ( is_user_disabled( $user_id ) ) {
1594 + if ( is_user_disabled( Actors::BLOG_USER_ID ) ) {
1595 + return false;
1596 + } else {
1597 + $user_id = Actors::BLOG_USER_ID;
713 1598 }
714 1599 }
715 1600
716 - $args = array(
717 - // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
718 - 'meta_query' => array(
719 - 'relation' => 'OR',
720 - array(
721 - 'key' => 'source_url',
722 - 'value' => $url,
723 - ),
724 - array(
725 - 'key' => 'source_id',
726 - 'value' => $url,
727 - ),
728 - ),
1601 + $outbox_activity_id = Outbox::add( $activity_object, $activity_type, $user_id, $content_visibility );
1602 +
1603 + if ( ! $outbox_activity_id ) {
1604 + return false;
1605 + }
1606 +
1607 + /**
1608 + * Action triggered after an object has been added to the outbox.
1609 + *
1610 + * @param int $outbox_activity_id The ID of the outbox item.
1611 + * @param \Activitypub\Activity\Base_Object $activity_object The activity object.
1612 + * @param int $user_id The User-ID.
1613 + * @param string $content_visibility The visibility of the content. See `constants.php` for possible values: `ACTIVITYPUB_CONTENT_VISIBILITY_*`.
1614 + */
1615 + \do_action( 'post_activitypub_add_to_outbox', $outbox_activity_id, $activity_object, $user_id, $content_visibility );
1616 +
1617 + set_wp_object_state( $data, 'federated' );
1618 +
1619 + return $outbox_activity_id;
1620 +}
1621 +
1622 +/**
1623 + * Check if an `$data` is an Activity.
1624 + *
1625 + * @see https://www.w3.org/ns/activitystreams#activities
1626 + *
1627 + * @param array|object|string $data The data to check.
1628 + *
1629 + * @return boolean True if the `$data` is an Activity, false otherwise.
1630 + */
1631 +function is_activity( $data ) {
1632 + /**
1633 + * Filters the activity types.
1634 + *
1635 + * @param array $types The activity types.
1636 + */
1637 + $types = apply_filters(
1638 + 'activitypub_activity_types',
1639 + array(
1640 + 'Accept',
1641 + 'Add',
1642 + 'Announce',
1643 + 'Arrive',
1644 + 'Block',
1645 + 'Create',
1646 + 'Delete',
1647 + 'Dislike',
1648 + 'Follow',
1649 + 'Flag',
1650 + 'Ignore',
1651 + 'Invite',
1652 + 'Join',
1653 + 'Leave',
1654 + 'Like',
1655 + 'Listen',
1656 + 'Move',
1657 + 'Offer',
1658 + 'Read',
1659 + 'Reject',
1660 + 'Remove',
1661 + 'TentativeAccept',
1662 + 'TentativeReject',
1663 + 'Travel',
1664 + 'Undo',
1665 + 'Update',
1666 + 'View',
1667 + )
729 1668 );
730 1669
731 - $query = new \WP_Comment_Query();
732 - $comments = $query->query( $args );
1670 + if ( is_string( $data ) ) {
1671 + return in_array( $data, $types, true );
1672 + }
733 1673
734 - if ( $comments && is_array( $comments ) ) {
735 - return $comments[0]->comment_ID;
1674 + if ( is_array( $data ) && isset( $data['type'] ) ) {
1675 + return in_array( $data['type'], $types, true );
736 1676 }
737 1677
738 - return null;
1678 + if ( is_object( $data ) && $data instanceof Base_Object ) {
1679 + return in_array( $data->get_type(), $types, true );
1680 + }
1681 +
1682 + return false;
739 1683 }
740 1684
741 1685 /**
742 - * Get the URI of an ActivityPub object
1686 + * Check if an `$data` is an Actor.
743 1687 *
744 - * @param array $object The ActivityPub object
1688 + * @see https://www.w3.org/ns/activitystreams#actor
745 1689 *
746 - * @return string The URI of the ActivityPub object
1690 + * @param array|object|string $data The data to check.
1691 + *
1692 + * @return boolean True if the `$data` is an Actor, false otherwise.
747 1693 */
748 -function object_to_uri( $object ) {
749 - // check if it is already simple
750 - if ( ! $object || is_string( $object ) ) {
751 - return $object;
752 - }
1694 +function is_actor( $data ) {
1695 + /**
1696 + * Filters the actor types.
1697 + *
1698 + * @param array $types The actor types.
1699 + */
1700 + $types = apply_filters(
1701 + 'activitypub_actor_types',
1702 + array(
1703 + 'Application',
1704 + 'Group',
1705 + 'Organization',
1706 + 'Person',
1707 + 'Service',
1708 + )
1709 + );
753 1710
754 - // check if it is a list, then take first item
755 - // this plugin does not support collections
756 - if ( array_is_list( $object ) ) {
757 - $object = $object[0];
1711 + if ( is_string( $data ) ) {
1712 + return in_array( $data, $types, true );
758 1713 }
759 1714
760 - // check if it is simplified now
761 - if ( is_string( $object ) ) {
762 - return $object;
1715 + if ( is_array( $data ) && isset( $data['type'] ) ) {
1716 + return in_array( $data['type'], $types, true );
763 1717 }
764 1718
765 - // return part of Object that makes most sense
766 - switch ( $object['type'] ) {
767 - case 'Link':
768 - $object = $object['href'];
769 - break;
770 - default:
771 - $object = $object['id'];
772 - break;
1719 + if ( is_object( $data ) && $data instanceof Base_Object ) {
1720 + return in_array( $data->get_type(), $types, true );
773 1721 }
774 1722
775 - return $object;
1723 + return false;
776 1724 }