PluginProbe
ActivityPub / 9.2.1
ActivityPub v9.2.1
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 +302 -621 2.0.09.2.1 View file →
@@ -1,776 +1,457 @@
1 1 <?php
2 -namespace Activitypub;
3 -
4 -use WP_Error;
5 -use WP_Comment_Query;
6 -use Activitypub\Http;
7 -use Activitypub\Webfinger;
8 -use Activitypub\Activity\Activity;
9 -use Activitypub\Collection\Followers;
10 -use Activitypub\Collection\Users;
11 -
12 2 /**
13 - * Returns the ActivityPub default JSON-context
3 + * Functions file.
14 4 *
15 - * @return array the activitypub context
5 + * General utility functions for the ActivityPub plugin.
6 + *
7 + * @package Activitypub
16 8 */
17 -function get_context() {
18 - $context = Activity::CONTEXT;
19 9
20 - return \apply_filters( 'activitypub_json_context', $context );
21 -}
10 +namespace Activitypub;
22 11
23 -function safe_remote_post( $url, $body, $user_id ) {
24 - return Http::post( $url, $body, $user_id );
25 -}
26 -
27 -function safe_remote_get( $url ) {
28 - return Http::get( $url );
29 -}
30 -
31 12 /**
32 - * Returns a users WebFinger "resource"
13 + * Get the ActivityPub ID for a WordPress object.
33 14 *
34 - * @param int $user_id The User-ID.
15 + * Returns the canonical ActivityPub URI for a WP_Post or WP_Comment.
35 16 *
36 - * @return string The User-Resource.
37 - */
38 -function get_webfinger_resource( $user_id ) {
39 - return Webfinger::get_user_resource( $user_id );
40 -}
41 -
42 -/**
43 - * Requests the Meta-Data from the Actors profile
17 + * @param \WP_Post|\WP_Comment $wp_object The WordPress post or comment.
44 18 *
45 - * @param string $actor The Actor URL.
46 - * @param bool $cached If the result should be cached.
47 - *
48 - * @return array|WP_Error The Actor profile as array or WP_Error on failure.
19 + * @return string|null The ActivityPub ID (a URL), or null if unsupported type.
49 20 */
50 -function get_remote_metadata_by_actor( $actor, $cached = true ) {
51 - $pre = apply_filters( 'pre_get_remote_metadata_by_actor', false, $actor );
52 - if ( $pre ) {
53 - return $pre;
21 +function get_object_id( $wp_object ) {
22 + if ( $wp_object instanceof \WP_Post ) {
23 + return get_post_id( $wp_object->ID );
54 24 }
55 - if ( preg_match( '/^@?' . ACTIVITYPUB_USERNAME_REGEXP . '$/i', $actor ) ) {
56 - $actor = Webfinger::resolve( $actor );
57 - }
58 25
59 - if ( ! $actor ) {
60 - return new WP_Error( 'activitypub_no_valid_actor_identifier', \__( 'The "actor" identifier is not valid', 'activitypub' ), array( 'status' => 404, 'actor' => $actor ) );
26 + if ( $wp_object instanceof \WP_Comment ) {
27 + return get_comment_id( $wp_object );
61 28 }
62 29
63 - if ( is_wp_error( $actor ) ) {
64 - return $actor;
65 - }
66 -
67 - $transient_key = 'activitypub_' . $actor;
68 -
69 - // only check the cache if needed.
70 - if ( $cached ) {
71 - $metadata = \get_transient( $transient_key );
72 -
73 - if ( $metadata ) {
74 - return $metadata;
75 - }
76 - }
77 -
78 - 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 ) );
80 - return $metadata;
81 - }
82 -
83 - $response = Http::get( $actor );
84 -
85 - if ( \is_wp_error( $response ) ) {
86 - return $response;
87 - }
88 -
89 - $metadata = \wp_remote_retrieve_body( $response );
90 - $metadata = \json_decode( $metadata, true );
91 -
92 - if ( ! $metadata ) {
93 - $metadata = new WP_Error( 'activitypub_invalid_json', \__( 'No valid JSON data', 'activitypub' ), array( 'status' => 400, 'actor' => $actor ) );
94 - return $metadata;
95 - }
96 -
97 - \set_transient( $transient_key, $metadata, WEEK_IN_SECONDS );
98 -
99 - return $metadata;
30 + return null;
100 31 }
101 32
102 33 /**
103 - * Returns the followers of a given user.
34 + * Convert a string from camelCase to snake_case.
104 35 *
105 - * @param int $user_id The User-ID.
36 + * @param string $input The string to convert.
106 37 *
107 - * @return array The followers.
38 + * @return string The converted string.
108 39 */
109 -function get_followers( $user_id ) {
110 - return Followers::get_followers( $user_id );
40 +function camel_to_snake_case( $input ) {
41 + return \strtolower( \preg_replace( '/(?<!^)[A-Z]/', '_$0', $input ) );
111 42 }
112 43
113 44 /**
114 - * Count the number of followers for a given user.
45 + * Convert a string from snake_case to camelCase.
115 46 *
116 - * @param int $user_id The User-ID.
47 + * @param string $input The string to convert.
117 48 *
118 - * @return int The number of followers.
49 + * @return string The converted string.
119 50 */
120 -function count_followers( $user_id ) {
121 - return Followers::count_followers( $user_id );
51 +function snake_to_camel_case( $input ) {
52 + return \lcfirst( \str_replace( '_', '', \ucwords( $input, '_' ) ) );
122 53 }
123 54
124 55 /**
125 - * Examine a url and try to determine the author ID it represents.
56 + * Convert seconds to ISO 8601 duration format.
126 57 *
127 - * Checks are supposedly from the hosted site blog.
58 + * @param int $seconds The duration in seconds.
128 59 *
129 - * @param string $url Permalink to check.
130 - *
131 - * @return int User ID, or 0 on failure.
60 + * @return string The duration in ISO 8601 format (e.g., "PT1H23M45S").
132 61 */
133 -function url_to_authorid( $url ) {
134 - global $wp_rewrite;
62 +function seconds_to_iso8601( $seconds ) {
63 + $seconds = (int) $seconds;
135 64
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;
65 + if ( $seconds <= 0 ) {
66 + return 'PT0S';
139 67 }
140 68
141 - // first, check to see if there is a 'author=N' to match against
142 - if ( \preg_match( '/[?&]author=(\d+)/i', $url, $values ) ) {
143 - $id = \absint( $values[1] );
144 - if ( $id ) {
145 - return $id;
146 - }
147 - }
69 + $hours = \floor( $seconds / 3600 );
70 + $minutes = \floor( ( $seconds % 3600 ) / 60 );
71 + $secs = $seconds % 60;
148 72
149 - // check to see if we are using rewrite rules
150 - $rewrite = $wp_rewrite->wp_rewrite_rules();
73 + $duration = 'PT';
151 74
152 - // not using rewrite rules, and 'author=N' method failed, so we're out of options
153 - if ( empty( $rewrite ) ) {
154 - return 0;
75 + if ( $hours > 0 ) {
76 + $duration .= $hours . 'H';
155 77 }
156 78
157 - // generate rewrite rule for the author url
158 - $author_rewrite = $wp_rewrite->get_author_permastruct();
159 - $author_regexp = \str_replace( '%author%', '', $author_rewrite );
79 + if ( $minutes > 0 ) {
80 + $duration .= $minutes . 'M';
81 + }
160 82
161 - // match the rewrite rule with the passed url
162 - if ( \preg_match( '/https?:\/\/(.+)' . \preg_quote( $author_regexp, '/' ) . '([^\/]+)/i', $url, $match ) ) {
163 - $user = \get_user_by( 'slug', $match[2] );
164 - if ( $user ) {
165 - return $user->ID;
166 - }
83 + if ( $secs > 0 || ( 0 === $hours && 0 === $minutes ) ) {
84 + $duration .= $secs . 'S';
167 85 }
168 86
169 - return 0;
87 + return $duration;
170 88 }
171 89
172 90 /**
173 - * Verify if url is a wp_ap_comment,
174 - * Or if it is a previously received remote comment
91 + * Check if a site supports the block editor.
175 92 *
176 - * @return int comment_id
93 + * @return boolean True if the site supports the block editor, false otherwise.
177 94 */
178 -function is_comment() {
179 - $comment_id = get_query_var( 'c', null );
180 -
181 - if ( ! is_null( $comment_id ) ) {
182 - $comment = \get_comment( $comment_id );
183 -
184 - // Only return local origin comments
185 - if ( $comment && $comment->user_id ) {
186 - return $comment_id;
187 - }
188 - }
189 -
190 - return false;
95 +function site_supports_blocks() {
96 + /**
97 + * Allow plugins to disable block editor support,
98 + * thus disabling blocks registered by the ActivityPub plugin.
99 + *
100 + * @param boolean $supports_blocks True if the site supports the block editor, false otherwise.
101 + */
102 + return \apply_filters( 'activitypub_site_supports_blocks', true );
191 103 }
192 104
193 105 /**
194 - * Check for Tombstone Objects
106 + * Get the icon Image object for site-wide ActivityPub actors.
195 107 *
196 - * @see https://www.w3.org/TR/activitypub/#delete-activity-outbox
108 + * Tries the site icon first, then the custom logo, and falls back to the
109 + * bundled WordPress logo.
197 110 *
198 - * @param WP_Error $wp_error A WP_Error-Response of an HTTP-Request
111 + * @since 9.1.0
199 112 *
200 - * @return boolean true if HTTP-Code is 410 or 404
113 + * @return array The icon array with 'type' and 'url'.
201 114 */
202 -function is_tombstone( $wp_error ) {
203 - if ( ! is_wp_error( $wp_error ) ) {
204 - return false;
115 +function site_icon() {
116 + // Try site icon first.
117 + $icon_id = \get_option( 'site_icon' );
118 +
119 + // Try custom logo second.
120 + if ( ! $icon_id ) {
121 + $icon_id = \get_theme_mod( 'custom_logo' );
205 122 }
206 123
207 - if ( in_array( (int) $wp_error->get_error_code(), array( 404, 410 ), true ) ) {
208 - return true;
124 + $icon_url = false;
125 +
126 + if ( $icon_id ) {
127 + $icon = \wp_get_attachment_image_src( $icon_id, 'full' );
128 + if ( $icon ) {
129 + $icon_url = $icon[0];
130 + }
209 131 }
210 132
211 - return false;
133 + if ( ! $icon_url ) {
134 + // Fallback to default icon.
135 + $icon_url = \plugins_url( '/assets/img/wp-logo.png', ACTIVITYPUB_PLUGIN_FILE );
136 + }
137 +
138 + return array(
139 + 'type' => 'Image',
140 + 'url' => \esc_url_raw( $icon_url ),
141 + );
212 142 }
213 143
214 144 /**
215 - * Get the REST URL relative to this plugin's namespace.
145 + * Check whether a blog is public based on the `blog_public` option.
216 146 *
217 - * @param string $path Optional. REST route path. Otherwise this plugin's namespaced root.
218 - *
219 - * @return string REST URL relative to this plugin's namespace.
147 + * @return bool True if public, false if not
220 148 */
221 -function get_rest_url_by_path( $path = '' ) {
222 - // we'll handle the leading slash.
223 - $path = ltrim( $path, '/' );
224 - $namespaced_path = sprintf( '/%s/%s', ACTIVITYPUB_REST_NAMESPACE, $path );
225 - return \get_rest_url( null, $namespaced_path );
149 +function is_blog_public() {
150 + /**
151 + * Filter whether the blog is public.
152 + *
153 + * @param bool $public Whether the blog is public.
154 + */
155 + return (bool) \apply_filters( 'activitypub_is_blog_public', \get_option( 'blog_public', 1 ) );
226 156 }
227 157
228 158 /**
229 - * Convert a string from camelCase to snake_case.
159 + * Get the masked WordPress version to only show the major and minor version.
230 160 *
231 - * @param string $string The string to convert.
232 - *
233 - * @return string The converted string.
161 + * @return string The masked version.
234 162 */
235 -// phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound
236 -function camel_to_snake_case( $string ) {
237 - return strtolower( preg_replace( '/(?<!^)[A-Z]/', '_$0', $string ) );
163 +function get_masked_wp_version() {
164 + // Only show the major and minor version.
165 + $version = \get_bloginfo( 'version' );
166 + // Strip the RC or beta part.
167 + $version = \preg_replace( '/-.*$/', '', $version );
168 + $version = \explode( '.', $version );
169 + $version = \array_slice( $version, 0, 2 );
170 +
171 + return \implode( '.', $version );
238 172 }
239 173
240 174 /**
241 - * Convert a string from snake_case to camelCase.
175 + * Check if a plugin is active, loading plugin.php if necessary.
242 176 *
243 - * @param string $string The string to convert.
177 + * This is a wrapper around the core is_plugin_active() function that ensures
178 + * the function is available by loading wp-admin/includes/plugin.php if needed.
179 + * This is useful when checking plugin status outside of the admin context.
244 180 *
245 - * @return string The converted string.
246 - */
247 -// phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound
248 -function snake_to_camel_case( $string ) {
249 - return lcfirst( str_replace( '_', '', ucwords( $string, '_' ) ) );
250 -}
251 -
252 -/**
253 - * Escapes a Tag, to be used as a hashtag.
181 + * @param string $plugin Plugin basename (e.g., 'plugin-folder/plugin-file.php').
254 182 *
255 - * @param string $string The string to escape.
256 - *
257 - * @return string The escaped hastag.
183 + * @return bool True if the plugin is active, false otherwise.
258 184 */
259 -function esc_hashtag( $string ) {
185 +function is_plugin_active( $plugin ) {
186 + // Include plugin.php if not already loaded (needed for core is_plugin_active).
187 + if ( ! \function_exists( 'is_plugin_active' ) ) {
188 + require_once ABSPATH . 'wp-admin/includes/plugin.php';
189 + }
260 190
261 - $hashtag = \wp_specialchars_decode( $string, ENT_QUOTES );
262 - // Remove all characters that are not letters, numbers, or underscores.
263 - $hashtag = \preg_replace( '/emoji-regex(*SKIP)(?!)|[^\p{L}\p{Nd}_]+/u', '_', $hashtag );
264 -
265 - // Capitalize every letter that is preceded by an underscore.
266 - $hashtag = preg_replace_callback(
267 - '/_(.)/',
268 - function ( $matches ) {
269 - return '' . strtoupper( $matches[1] );
270 - },
271 - $hashtag
272 - );
273 -
274 - // Add a hashtag to the beginning of the string.
275 - $hashtag = ltrim( $hashtag, '#' );
276 - $hashtag = '#' . $hashtag;
277 -
278 - /**
279 - * Allow defining your own custom hashtag generation rules.
280 - *
281 - * @param string $hashtag The hashtag to be returned.
282 - * @param string $string The original string.
283 - */
284 - $hashtag = apply_filters( 'activitypub_esc_hashtag', $hashtag, $string );
285 -
286 - return esc_html( $hashtag );
191 + return \is_plugin_active( $plugin );
287 192 }
288 193
289 194 /**
290 - * Check if a request is for an ActivityPub request.
195 + * Returns the website hosts allowed to credit this blog.
291 196 *
292 - * @return bool False by default.
197 + * @return array|null The attribution domains or null if not found.
293 198 */
294 -function is_activitypub_request() {
295 - global $wp_query;
296 -
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;
199 +function get_attribution_domains() {
200 + if ( '1' !== \get_option( 'activitypub_use_opengraph', '1' ) ) {
201 + return null;
303 202 }
304 203
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 );
204 + $domains = \get_option( 'activitypub_attribution_domains', home_host() );
205 + $domains = \explode( PHP_EOL, $domains );
309 206
310 - if ( ! \post_type_supports( $post_type, 'activitypub' ) ) {
311 - return false;
312 - }
207 + if ( ! $domains ) {
208 + $domains = null;
313 209 }
314 210
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'] ) ) {
319 - return true;
320 - }
321 -
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'] ) );
328 -
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 - }
340 - }
341 -
342 - return false;
211 + return $domains;
343 212 }
344 213
345 214 /**
346 - * This function checks if a user is disabled for ActivityPub.
215 + * Change the display of large numbers on the site.
347 216 *
348 - * @param int $user_id The User-ID.
217 + * @author Jeremy Herve
349 218 *
350 - * @return boolean True if the user is disabled, false otherwise.
351 - */
352 -function is_user_disabled( $user_id ) {
353 - $return = false;
354 -
355 - switch ( $user_id ) {
356 - // if the user is the application user, it's always enabled.
357 - case \Activitypub\Collection\Users::APPLICATION_USER_ID:
358 - $return = false;
359 - break;
360 - // if the user is the blog user, it's only enabled in single-user mode.
361 - case \Activitypub\Collection\Users::BLOG_USER_ID:
362 - if ( is_user_type_disabled( 'blog' ) ) {
363 - $return = true;
364 - break;
365 - }
366 -
367 - $return = false;
368 - break;
369 - // if the user is any other user, it's enabled if it can publish posts.
370 - default:
371 - if ( ! \get_user_by( 'id', $user_id ) ) {
372 - $return = true;
373 - break;
374 - }
375 -
376 - if ( is_user_type_disabled( 'user' ) ) {
377 - $return = true;
378 - break;
379 - }
380 -
381 - if ( ! \user_can( $user_id, 'publish_posts' ) ) {
382 - $return = true;
383 - break;
384 - }
385 -
386 - $return = false;
387 - break;
388 - }
389 -
390 - return apply_filters( 'activitypub_is_user_disabled', $return, $user_id );
391 -}
392 -
393 -/**
394 - * Checks if a User-Type is disabled for ActivityPub.
219 + * @see https://wordpress.org/support/topic/abbreviate-numbers-with-k/
395 220 *
396 - * This function is used to check if the 'blog' or 'user'
397 - * type is disabled for ActivityPub.
221 + * @param string $formatted Converted number in string format.
222 + * @param float $number The number to convert based on locale.
398 223 *
399 - * @param enum $type Can be 'blog' or 'user'.
400 - *
401 - * @return boolean True if the user type is disabled, false otherwise.
224 + * @return string Converted number in string format.
402 225 */
403 -function is_user_type_disabled( $type ) {
404 - switch ( $type ) {
405 - case 'blog':
406 - if ( \defined( 'ACTIVITYPUB_SINGLE_USER_MODE' ) ) {
407 - if ( ACTIVITYPUB_SINGLE_USER_MODE ) {
408 - $return = false;
409 - break;
410 - }
411 - }
226 +function custom_large_numbers( $formatted, $number ) {
227 + global $wp_locale;
412 228
413 - if ( \defined( 'ACTIVITYPUB_DISABLE_BLOG_USER' ) ) {
414 - $return = ACTIVITYPUB_DISABLE_BLOG_USER;
415 - break;
416 - }
229 + $decimals = 0;
230 + $decimal_point = '.';
231 + $thousands_sep = ',';
417 232
418 - if ( '1' !== \get_option( 'activitypub_enable_blog_user', '0' ) ) {
419 - $return = true;
420 - break;
421 - }
233 + if ( isset( $wp_locale ) ) {
234 + $decimals = (int) $wp_locale->number_format['decimal_point'];
235 + $decimal_point = $wp_locale->number_format['decimal_point'];
236 + $thousands_sep = $wp_locale->number_format['thousands_sep'];
237 + }
422 238
423 - $return = false;
424 - break;
425 - case 'user':
426 - if ( \defined( 'ACTIVITYPUB_SINGLE_USER_MODE' ) ) {
427 - if ( ACTIVITYPUB_SINGLE_USER_MODE ) {
428 - $return = true;
429 - break;
430 - }
431 - }
432 -
433 - if ( \defined( 'ACTIVITYPUB_DISABLE_USER' ) ) {
434 - $return = ACTIVITYPUB_DISABLE_USER;
435 - break;
436 - }
437 -
438 - if ( '1' !== \get_option( 'activitypub_enable_users', '1' ) ) {
439 - $return = true;
440 - break;
441 - }
442 -
443 - $return = false;
444 - break;
445 - default:
446 - $return = new WP_Error( 'activitypub_wrong_user_type', __( 'Wrong user type', 'activitypub' ), array( 'status' => 400 ) );
447 - break;
239 + if ( $number < 1000 ) { // Any number less than a Thousand.
240 + return \number_format( $number, $decimals, $decimal_point, $thousands_sep );
241 + } elseif ( $number < 1000000 ) { // Any number less than a million.
242 + return \number_format( $number / 1000, $decimals, $decimal_point, $thousands_sep ) . 'K';
243 + } elseif ( $number < 1000000000 ) { // Any number less than a billion.
244 + return \number_format( $number / 1000000, $decimals, $decimal_point, $thousands_sep ) . 'M';
245 + } else { // At least a billion.
246 + return \number_format( $number / 1000000000, $decimals, $decimal_point, $thousands_sep ) . 'B';
448 247 }
449 -
450 - return apply_filters( 'activitypub_is_user_type_disabled', $return, $type );
451 248 }
452 249
453 250 /**
454 - * Check if the blog is in single-user mode.
251 + * Escapes a Tag, to be used as a hashtag.
455 252 *
456 - * @return boolean True if the blog is in single-user mode, false otherwise.
253 + * @param string $input The string to escape.
254 + *
255 + * @return string The escaped hashtag.
457 256 */
458 -function is_single_user() {
459 - if (
460 - false === is_user_type_disabled( 'blog' ) &&
461 - true === is_user_type_disabled( 'user' )
462 - ) {
463 - return true;
464 - }
257 +function esc_hashtag( $input ) {
258 + $hashtag = \wp_specialchars_decode( $input, ENT_QUOTES );
259 + // Remove all characters that are not letters, numbers, or hyphens.
260 + $hashtag = \preg_replace( '/[^\p{L}\p{Nd}-]+/u', '-', $hashtag );
465 261
466 - return false;
467 -}
262 + // Capitalize every letter that is preceded by a hyphen.
263 + $hashtag = \preg_replace_callback(
264 + '/-+(.)/',
265 + static function ( $matches ) {
266 + return \strtoupper( $matches[1] );
267 + },
268 + $hashtag
269 + );
468 270
469 -/**
470 - * Check if a site supports the block editor.
471 - *
472 - * @return boolean True if the site supports the block editor, false otherwise.
473 - */
474 -function site_supports_blocks() {
475 - if ( \version_compare( \get_bloginfo( 'version' ), '5.9', '<' ) ) {
476 - return false;
477 - }
271 + // Add a hashtag to the beginning of the string.
272 + $hashtag = \ltrim( $hashtag, '#' );
273 + $hashtag = \trim( $hashtag, '-' );
274 + $hashtag = '#' . $hashtag;
478 275
479 - if ( ! \function_exists( 'register_block_type_from_metadata' ) ) {
480 - return false;
481 - }
482 -
483 276 /**
484 - * Allow plugins to disable block editor support,
485 - * thus disabling blocks registered by the ActivityPub plugin.
277 + * Allow defining your own custom hashtag generation rules.
486 278 *
487 - * @param boolean $supports_blocks True if the site supports the block editor, false otherwise.
279 + * @param string $hashtag The hashtag to be returned.
280 + * @param string $input The original string.
488 281 */
489 - return apply_filters( 'activitypub_site_supports_blocks', true );
490 -}
282 + $hashtag = \apply_filters( 'activitypub_esc_hashtag', $hashtag, $input );
491 283
492 -/**
493 - * Check if data is valid JSON.
494 - *
495 - * @param string $data The data to check.
496 - *
497 - * @return boolean True if the data is JSON, false otherwise.
498 - */
499 -function is_json( $data ) {
500 - return \is_array( \json_decode( $data, true ) ) ? true : false;
284 + return \esc_html( $hashtag );
501 285 }
502 286
503 287 /**
504 - * Check if a blog is public based on the `blog_public` option
288 + * Replace content with links, mentions or hashtags by Regex callback and not affect protected tags.
505 289 *
506 - * @return bollean True if public, false if not
507 - */
508 -function is_blog_public() {
509 - return (bool) apply_filters( 'activitypub_is_blog_public', \get_option( 'blog_public', 1 ) );
510 -}
511 -
512 -/**
513 - * Sanitize a URL
290 + * @param string $content The content that should be changed.
291 + * @param string $regex The regex to use.
292 + * @param callable $regex_callback Callback for replacement logic.
514 293 *
515 - * @param string $value The URL to sanitize
516 - *
517 - * @return string|null The sanitized URL or null if invalid
294 + * @return string The content with links, mentions, hashtags, etc.
518 295 */
519 -function sanitize_url( $value ) {
520 - if ( filter_var( $value, FILTER_VALIDATE_URL ) === false ) {
521 - return null;
296 +function enrich_content_data( $content, $regex, $regex_callback ) {
297 + // Small protection against execution timeouts: limit to 1 MB.
298 + if ( \mb_strlen( $content ) > MB_IN_BYTES ) {
299 + return $content;
522 300 }
301 + $tag_stack = array();
302 + $protected_tags = array(
303 + 'pre',
304 + 'code',
305 + 'textarea',
306 + 'style',
307 + 'a',
308 + );
309 + $content_with_links = '';
310 + $in_protected_tag = false;
311 + foreach ( \wp_html_split( $content ) as $chunk ) {
312 + if ( \preg_match( '#^<!--[\s\S]*-->$#i', $chunk, $m ) ) {
313 + $content_with_links .= $chunk;
314 + continue;
315 + }
523 316
524 - return esc_url_raw( $value );
525 -}
317 + if ( \preg_match( '#^<(/)?([a-z-]+)\b[^>]*>$#i', $chunk, $m ) ) {
318 + $tag = \strtolower( $m[2] );
319 + if ( '/' === $m[1] ) {
320 + // Closing tag.
321 + $i = \array_search( $tag, $tag_stack, true );
322 + // We can only remove the tag from the stack if it is in the stack.
323 + if ( false !== $i ) {
324 + $tag_stack = \array_slice( $tag_stack, 0, $i );
325 + }
326 + } else {
327 + // Opening tag, add it to the stack.
328 + $tag_stack[] = $tag;
329 + }
526 330
527 -/**
528 - * Extract recipient URLs from Activity object
529 - *
530 - * @param array $data
531 - *
532 - * @return array The list of user URLs
533 - */
534 -function extract_recipients_from_activity( $data ) {
535 - $recipient_items = array();
331 + // If we're in a protected tag, the tag_stack contains at least one protected tag string.
332 + // The protected tag state can only change when we encounter a start or end tag.
333 + $in_protected_tag = \array_intersect( $tag_stack, $protected_tags );
536 334
537 - foreach ( array( 'to', 'bto', 'cc', 'bcc', 'audience' ) as $i ) {
538 - if ( array_key_exists( $i, $data ) ) {
539 - if ( is_array( $data[ $i ] ) ) {
540 - $recipient = $data[ $i ];
541 - } else {
542 - $recipient = array( $data[ $i ] );
543 - }
544 - $recipient_items = array_merge( $recipient_items, $recipient );
335 + // Never inspect tags.
336 + $content_with_links .= $chunk;
337 + continue;
545 338 }
546 339
547 - if ( is_array( $data['object'] ) && array_key_exists( $i, $data['object'] ) ) {
548 - if ( is_array( $data['object'][ $i ] ) ) {
549 - $recipient = $data['object'][ $i ];
550 - } else {
551 - $recipient = array( $data['object'][ $i ] );
552 - }
553 - $recipient_items = array_merge( $recipient_items, $recipient );
340 + if ( $in_protected_tag ) {
341 + // Don't inspect a chunk inside an inspected tag.
342 + $content_with_links .= $chunk;
343 + continue;
554 344 }
555 - }
556 345
557 - $recipients = array();
558 -
559 - // flatten array
560 - foreach ( $recipient_items as $recipient ) {
561 - if ( is_array( $recipient ) ) {
562 - // check if recipient is an object
563 - if ( array_key_exists( 'id', $recipient ) ) {
564 - $recipients[] = $recipient['id'];
565 - }
566 - } else {
567 - $recipients[] = $recipient;
568 - }
346 + // Only reachable when there is no protected tag in the stack.
347 + $content_with_links .= \preg_replace_callback( $regex, $regex_callback, $chunk );
569 348 }
570 349
571 - return array_unique( $recipients );
350 + return $content_with_links;
572 351 }
573 352
574 353 /**
575 - * Check if passed Activity is Public
354 + * Get an ActivityPub embed HTML for a URL.
576 355 *
577 - * @param array $data The Activity object as array
356 + * @param string $url The URL to get the embed for.
357 + * @param boolean $inline_css Whether to inline CSS. Default true.
578 358 *
579 - * @return boolean True if public, false if not
359 + * @return string|false The embed HTML or false if not found.
580 360 */
581 -function is_activity_public( $data ) {
582 - $recipients = extract_recipients_from_activity( $data );
583 -
584 - return in_array( 'https://www.w3.org/ns/activitystreams#Public', $recipients, true );
361 +function get_embed_html( $url, $inline_css = true ) {
362 + return Embed::get_html( $url, $inline_css );
585 363 }
586 364
587 365 /**
588 - * Get active users based on a given duration
366 + * Get the client IP address for rate-limiting purposes.
589 367 *
590 - * @param int $duration The duration to check in month(s)
368 + * Walks the ordered list of $_SERVER keys returned by the
369 + * `activitypub_client_ip_sources` filter (default: `['REMOTE_ADDR']`) and
370 + * returns the first value that parses as a valid IP literal, validated via
371 + * `filter_var( ..., FILTER_VALIDATE_IP )`. The result can be overridden
372 + * outright via the `activitypub_client_ip` filter; that filter's output is
373 + * also validated and replaced with `''` when it isn't a valid IP, so a
374 + * misbehaving filter can't collide all callers into the same rate-limit
375 + * bucket.
591 376 *
592 - * @return int The number of active users
593 - */
594 -function get_active_users( $duration = 1 ) {
595 -
596 - $duration = intval( $duration );
597 - $transient_key = sprintf( 'monthly_active_users_%d', $duration );
598 - $count = get_transient( $transient_key );
599 -
600 - if ( false === $count ) {
601 - 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 -
606 - set_transient( $transient_key, $count, DAY_IN_SECONDS );
607 - }
608 -
609 - // if 0 authors where active
610 - if ( 0 === $count ) {
611 - return 0;
612 - }
613 -
614 - // if single user mode
615 - if ( is_single_user() ) {
616 - return 1;
617 - }
618 -
619 - // if blog user is disabled
620 - if ( is_user_disabled( Users::BLOG_USER_ID ) ) {
621 - return $count;
622 - }
623 -
624 - // also count blog user
625 - return $count + 1;
626 -}
627 -
628 -/**
629 - * Get the total number of users
377 + * Trusting any source other than `REMOTE_ADDR` is only safe behind a
378 + * reverse proxy that sets and overwrites the corresponding header — see
379 + * the `activitypub_client_ip_sources` filter docblock for guidance.
630 380 *
631 - * @return int The total number of users
632 - */
633 -function get_total_users() {
634 - // if single user mode
635 - if ( is_single_user() ) {
636 - return 1;
637 - }
638 -
639 - $users = \get_users(
640 - array(
641 - 'capability__in' => array( 'publish_posts' ),
642 - )
643 - );
644 -
645 - if ( is_array( $users ) ) {
646 - $users = count( $users );
647 - } else {
648 - $users = 1;
649 - }
650 -
651 - // if blog user is disabled
652 - if ( is_user_disabled( Users::BLOG_USER_ID ) ) {
653 - return $users;
654 - }
655 -
656 - return $users + 1;
657 -}
658 -
659 -/**
660 - * Examine a comment ID and look up an existing comment it represents.
381 + * Callers using the return value as a rate-limit key should treat an
382 + * empty return as "client unidentifiable" and fail closed rather than
383 + * share a single bucket across every such request.
661 384 *
662 - * @param string $id ActivityPub object ID (usually a URL) to check.
385 + * @since 8.1.0
663 386 *
664 - * @return int|boolean Comment ID, or false on failure.
387 + * @return string A valid IP address, or '' when no IP could be determined.
665 388 */
666 -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 - )
672 - );
389 +function get_client_ip() {
390 + // phpcs:disable WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders
391 + $ip = '';
673 392
674 - if ( ! $comment_query->comments ) {
675 - return false;
676 - }
393 + /**
394 + * Filter the ordered list of $_SERVER keys to consult as a source for the
395 + * client IP. The first key whose value parses as a valid IP wins.
396 + *
397 + * Default: array( 'REMOTE_ADDR' ) — the actual TCP peer, the only value
398 + * that an HTTP client cannot spoof. Trusting any other $_SERVER key is
399 + * only safe when a reverse proxy in front of the site sets that key and
400 + * overwrites any client-supplied version; otherwise an attacker can spoof
401 + * the value and bypass the per-IP rate limits that depend on it.
402 + *
403 + * Common operator overrides:
404 + * array( 'HTTP_CF_CONNECTING_IP' ) on Cloudflare.
405 + * array( 'HTTP_TRUE_CLIENT_IP', 'REMOTE_ADDR' ) Akamai with a fallback.
406 + * array( 'HTTP_X_REAL_IP' ) nginx that strips the client copy.
407 + *
408 + * X-Forwarded-For pitfall: even with a trusted proxy, an attacker can
409 + * prepend their own value before the proxy appends the real client IP.
410 + * This helper takes the leftmost entry, which is correct only when the
411 + * trusted proxy fully overwrites the header. If you trust X-Forwarded-For
412 + * end-to-end, prefer to resolve from the right by your known proxy count
413 + * via the activitypub_client_ip filter.
414 + *
415 + * @since 8.2.0
416 + *
417 + * @param string[] $sources $_SERVER keys to consult, in priority order.
418 + */
419 + $sources = \apply_filters( 'activitypub_client_ip_sources', array( 'REMOTE_ADDR' ) );
677 420
678 - if ( count( $comment_query->comments ) > 1 ) {
679 - return false;
421 + if ( ! \is_array( $sources ) ) {
422 + $sources = array( 'REMOTE_ADDR' );
680 423 }
681 424
682 - return $comment_query->comments[0];
683 -}
425 + foreach ( $sources as $source ) {
426 + if ( ! \is_string( $source ) || empty( $_SERVER[ $source ] ) ) {
427 + continue;
428 + }
684 429
685 -/**
686 - * Verify if URL is a local comment,
687 - * Or if it is a previously received remote comment
688 - * (For threading comments locally)
689 - *
690 - * @param string $url The URL to check.
691 - *
692 - * @return int comment_ID or null if not found
693 - */
694 -function url_to_commentid( $url ) {
695 - if ( ! $url || ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
696 - return null;
697 - }
430 + // Some headers (e.g. X-Forwarded-For) may contain a comma-separated list; use the first IP.
431 + $ip_list = \sanitize_text_field( \wp_unslash( $_SERVER[ $source ] ) );
432 + $candidate = \trim( \explode( ',', $ip_list )[0] );
698 433
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 );
702 -
703 - if ( $query ) {
704 - parse_str( $query, $params );
705 -
706 - if ( ! empty( $params['c'] ) ) {
707 - $comment = \get_comment( $params['c'] );
708 -
709 - if ( $comment ) {
710 - return $comment->comment_ID;
711 - }
712 - }
434 + if ( \filter_var( $candidate, FILTER_VALIDATE_IP ) ) {
435 + $ip = $candidate;
436 + break;
713 437 }
714 438 }
439 + // phpcs:enable WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders
715 440
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 - ),
729 - );
441 + /**
442 + * Filter the client IP address used for rate limiting.
443 + *
444 + * @since 8.1.0
445 + *
446 + * @param string $ip The detected client IP address (empty when none could be determined).
447 + */
448 + $ip = \apply_filters( 'activitypub_client_ip', $ip );
730 449
731 - $query = new \WP_Comment_Query();
732 - $comments = $query->query( $args );
733 -
734 - if ( $comments && is_array( $comments ) ) {
735 - return $comments[0]->comment_ID;
450 + // Tolerate surrounding whitespace from filter callbacks; FILTER_VALIDATE_IP would otherwise reject it.
451 + if ( \is_string( $ip ) ) {
452 + $ip = \trim( $ip );
736 453 }
737 454
738 - return null;
739 -}
740 -
741 -/**
742 - * Get the URI of an ActivityPub object
743 - *
744 - * @param array $object The ActivityPub object
745 - *
746 - * @return string The URI of the ActivityPub object
747 - */
748 -function object_to_uri( $object ) {
749 - // check if it is already simple
750 - if ( ! $object || is_string( $object ) ) {
751 - return $object;
752 - }
753 -
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];
758 - }
759 -
760 - // check if it is simplified now
761 - if ( is_string( $object ) ) {
762 - return $object;
763 - }
764 -
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;
773 - }
774 -
775 - return $object;
455 + // Re-validate so a misbehaving filter can't return a sentinel string that would collapse all callers into one bucket.
456 + return \is_string( $ip ) && \filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '';
776 457 }