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 +309 -552 1.3.09.2.1 View file →
@@ -1,700 +1,457 @@
1 1 <?php
2 +/**
3 + * Functions file.
4 + *
5 + * General utility functions for the ActivityPub plugin.
6 + *
7 + * @package Activitypub
8 + */
9 +
2 10 namespace Activitypub;
3 11
4 -use WP_Error;
5 -use WP_Comment_Query;
6 -use Activitypub\Http;
7 -use Activitypub\Activity\Activity;
8 -use Activitypub\Collection\Followers;
9 -use Activitypub\Collection\Users;
10 -
11 12 /**
12 - * Returns the ActivityPub default JSON-context
13 + * Get the ActivityPub ID for a WordPress object.
13 14 *
14 - * @return array the activitypub context
15 + * Returns the canonical ActivityPub URI for a WP_Post or WP_Comment.
16 + *
17 + * @param \WP_Post|\WP_Comment $wp_object The WordPress post or comment.
18 + *
19 + * @return string|null The ActivityPub ID (a URL), or null if unsupported type.
15 20 */
16 -function get_context() {
17 - $context = Activity::CONTEXT;
21 +function get_object_id( $wp_object ) {
22 + if ( $wp_object instanceof \WP_Post ) {
23 + return get_post_id( $wp_object->ID );
24 + }
18 25
19 - return \apply_filters( 'activitypub_json_context', $context );
20 -}
26 + if ( $wp_object instanceof \WP_Comment ) {
27 + return get_comment_id( $wp_object );
28 + }
21 29
22 -function safe_remote_post( $url, $body, $user_id ) {
23 - return Http::post( $url, $body, $user_id );
30 + return null;
24 31 }
25 32
26 -function safe_remote_get( $url ) {
27 - return Http::get( $url );
33 +/**
34 + * Convert a string from camelCase to snake_case.
35 + *
36 + * @param string $input The string to convert.
37 + *
38 + * @return string The converted string.
39 + */
40 +function camel_to_snake_case( $input ) {
41 + return \strtolower( \preg_replace( '/(?<!^)[A-Z]/', '_$0', $input ) );
28 42 }
29 43
30 44 /**
31 - * Returns a users WebFinger "resource"
45 + * Convert a string from snake_case to camelCase.
32 46 *
33 - * @param int $user_id The User-ID.
47 + * @param string $input The string to convert.
34 48 *
35 - * @return string The User-Resource.
49 + * @return string The converted string.
36 50 */
37 -function get_webfinger_resource( $user_id ) {
38 - return Webfinger::get_user_resource( $user_id );
51 +function snake_to_camel_case( $input ) {
52 + return \lcfirst( \str_replace( '_', '', \ucwords( $input, '_' ) ) );
39 53 }
40 54
41 55 /**
42 - * Requests the Meta-Data from the Actors profile
56 + * Convert seconds to ISO 8601 duration format.
43 57 *
44 - * @param string $actor The Actor URL.
45 - * @param bool $cached If the result should be cached.
58 + * @param int $seconds The duration in seconds.
46 59 *
47 - * @return array|WP_Error The Actor profile as array or WP_Error on failure.
60 + * @return string The duration in ISO 8601 format (e.g., "PT1H23M45S").
48 61 */
49 -function get_remote_metadata_by_actor( $actor, $cached = true ) {
50 - $pre = apply_filters( 'pre_get_remote_metadata_by_actor', false, $actor );
51 - if ( $pre ) {
52 - return $pre;
53 - }
54 - if ( preg_match( '/^@?' . ACTIVITYPUB_USERNAME_REGEXP . '$/i', $actor ) ) {
55 - $actor = Webfinger::resolve( $actor );
56 - }
62 +function seconds_to_iso8601( $seconds ) {
63 + $seconds = (int) $seconds;
57 64
58 - if ( ! $actor ) {
59 - return new WP_Error( 'activitypub_no_valid_actor_identifier', \__( 'The "actor" identifier is not valid', 'activitypub' ), array( 'status' => 404, 'actor' => $actor ) );
65 + if ( $seconds <= 0 ) {
66 + return 'PT0S';
60 67 }
61 68
62 - if ( is_wp_error( $actor ) ) {
63 - return $actor;
64 - }
69 + $hours = \floor( $seconds / 3600 );
70 + $minutes = \floor( ( $seconds % 3600 ) / 60 );
71 + $secs = $seconds % 60;
65 72
66 - $transient_key = 'activitypub_' . $actor;
73 + $duration = 'PT';
67 74
68 - // only check the cache if needed.
69 - if ( $cached ) {
70 - $metadata = \get_transient( $transient_key );
71 -
72 - if ( $metadata ) {
73 - return $metadata;
74 - }
75 + if ( $hours > 0 ) {
76 + $duration .= $hours . 'H';
75 77 }
76 78
77 - if ( ! \wp_http_validate_url( $actor ) ) {
78 - $metadata = new WP_Error( 'activitypub_no_valid_actor_url', \__( 'The "actor" is no valid URL', 'activitypub' ), array( 'status' => 400, 'actor' => $actor ) );
79 - return $metadata;
79 + if ( $minutes > 0 ) {
80 + $duration .= $minutes . 'M';
80 81 }
81 82
82 - $response = Http::get( $actor );
83 -
84 - if ( \is_wp_error( $response ) ) {
85 - return $response;
83 + if ( $secs > 0 || ( 0 === $hours && 0 === $minutes ) ) {
84 + $duration .= $secs . 'S';
86 85 }
87 86
88 - $metadata = \wp_remote_retrieve_body( $response );
89 - $metadata = \json_decode( $metadata, true );
90 -
91 - if ( ! $metadata ) {
92 - $metadata = new WP_Error( 'activitypub_invalid_json', \__( 'No valid JSON data', 'activitypub' ), array( 'status' => 400, 'actor' => $actor ) );
93 - return $metadata;
94 - }
95 -
96 - \set_transient( $transient_key, $metadata, WEEK_IN_SECONDS );
97 -
98 - return $metadata;
87 + return $duration;
99 88 }
100 89
101 90 /**
102 - * Returns the followers of a given user.
91 + * Check if a site supports the block editor.
103 92 *
104 - * @param int $user_id The User-ID.
105 - *
106 - * @return array The followers.
93 + * @return boolean True if the site supports the block editor, false otherwise.
107 94 */
108 -function get_followers( $user_id ) {
109 - return Followers::get_followers( $user_id );
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 );
110 103 }
111 104
112 105 /**
113 - * Count the number of followers for a given user.
106 + * Get the icon Image object for site-wide ActivityPub actors.
114 107 *
115 - * @param int $user_id The User-ID.
108 + * Tries the site icon first, then the custom logo, and falls back to the
109 + * bundled WordPress logo.
116 110 *
117 - * @return int The number of followers.
118 - */
119 -function count_followers( $user_id ) {
120 - return Followers::count_followers( $user_id );
121 -}
122 -
123 -/**
124 - * Examine a url and try to determine the author ID it represents.
111 + * @since 9.1.0
125 112 *
126 - * Checks are supposedly from the hosted site blog.
127 - *
128 - * @param string $url Permalink to check.
129 - *
130 - * @return int User ID, or 0 on failure.
113 + * @return array The icon array with 'type' and 'url'.
131 114 */
132 -function url_to_authorid( $url ) {
133 - global $wp_rewrite;
115 +function site_icon() {
116 + // Try site icon first.
117 + $icon_id = \get_option( 'site_icon' );
134 118
135 - // check if url hase the same host
136 - if ( \wp_parse_url( \site_url(), \PHP_URL_HOST ) !== \wp_parse_url( $url, \PHP_URL_HOST ) ) {
137 - return 0;
119 + // Try custom logo second.
120 + if ( ! $icon_id ) {
121 + $icon_id = \get_theme_mod( 'custom_logo' );
138 122 }
139 123
140 - // first, check to see if there is a 'author=N' to match against
141 - if ( \preg_match( '/[?&]author=(\d+)/i', $url, $values ) ) {
142 - $id = \absint( $values[1] );
143 - if ( $id ) {
144 - return $id;
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];
145 130 }
146 131 }
147 132
148 - // check to see if we are using rewrite rules
149 - $rewrite = $wp_rewrite->wp_rewrite_rules();
150 -
151 - // not using rewrite rules, and 'author=N' method failed, so we're out of options
152 - if ( empty( $rewrite ) ) {
153 - return 0;
133 + if ( ! $icon_url ) {
134 + // Fallback to default icon.
135 + $icon_url = \plugins_url( '/assets/img/wp-logo.png', ACTIVITYPUB_PLUGIN_FILE );
154 136 }
155 137
156 - // generate rewrite rule for the author url
157 - $author_rewrite = $wp_rewrite->get_author_permastruct();
158 - $author_regexp = \str_replace( '%author%', '', $author_rewrite );
159 -
160 - // match the rewrite rule with the passed url
161 - if ( \preg_match( '/https?:\/\/(.+)' . \preg_quote( $author_regexp, '/' ) . '([^\/]+)/i', $url, $match ) ) {
162 - $user = \get_user_by( 'slug', $match[2] );
163 - if ( $user ) {
164 - return $user->ID;
165 - }
166 - }
167 -
168 - return 0;
138 + return array(
139 + 'type' => 'Image',
140 + 'url' => \esc_url_raw( $icon_url ),
141 + );
169 142 }
170 143
171 144 /**
172 - * Check for Tombstone Objects
145 + * Check whether a blog is public based on the `blog_public` option.
173 146 *
174 - * @see https://www.w3.org/TR/activitypub/#delete-activity-outbox
175 - *
176 - * @param WP_Error $wp_error A WP_Error-Response of an HTTP-Request
177 - *
178 - * @return boolean true if HTTP-Code is 410 or 404
147 + * @return bool True if public, false if not
179 148 */
180 -function is_tombstone( $wp_error ) {
181 - if ( ! is_wp_error( $wp_error ) ) {
182 - return false;
183 - }
184 -
185 - if ( in_array( (int) $wp_error->get_error_code(), array( 404, 410 ), true ) ) {
186 - return true;
187 - }
188 -
189 - return false;
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 ) );
190 156 }
191 157
192 158 /**
193 - * Get the REST URL relative to this plugin's namespace.
159 + * Get the masked WordPress version to only show the major and minor version.
194 160 *
195 - * @param string $path Optional. REST route path. Otherwise this plugin's namespaced root.
196 - *
197 - * @return string REST URL relative to this plugin's namespace.
161 + * @return string The masked version.
198 162 */
199 -function get_rest_url_by_path( $path = '' ) {
200 - // we'll handle the leading slash.
201 - $path = ltrim( $path, '/' );
202 - $namespaced_path = sprintf( '/%s/%s', ACTIVITYPUB_REST_NAMESPACE, $path );
203 - return \get_rest_url( null, $namespaced_path );
204 -}
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 );
205 170
206 -/**
207 - * Convert a string from camelCase to snake_case.
208 - *
209 - * @param string $string The string to convert.
210 - *
211 - * @return string The converted string.
212 - */
213 -// phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound
214 -function camel_to_snake_case( $string ) {
215 - return strtolower( preg_replace( '/(?<!^)[A-Z]/', '_$0', $string ) );
171 + return \implode( '.', $version );
216 172 }
217 173
218 174 /**
219 - * Convert a string from snake_case to camelCase.
175 + * Check if a plugin is active, loading plugin.php if necessary.
220 176 *
221 - * @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.
222 180 *
223 - * @return string The converted string.
224 - */
225 -// phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames.stringFound
226 -function snake_to_camel_case( $string ) {
227 - return lcfirst( str_replace( '_', '', ucwords( $string, '_' ) ) );
228 -}
229 -
230 -/**
231 - * Escapes a Tag, to be used as a hashtag.
181 + * @param string $plugin Plugin basename (e.g., 'plugin-folder/plugin-file.php').
232 182 *
233 - * @param string $string The string to escape.
234 - *
235 - * @return string The escaped hastag.
183 + * @return bool True if the plugin is active, false otherwise.
236 184 */
237 -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 + }
238 190
239 - $hashtag = \wp_specialchars_decode( $string, ENT_QUOTES );
240 - // Remove all characters that are not letters, numbers, or underscores.
241 - $hashtag = \preg_replace( '/emoji-regex(*SKIP)(?!)|[^\p{L}\p{Nd}_]+/u', '_', $hashtag );
242 -
243 - // Capitalize every letter that is preceded by an underscore.
244 - $hashtag = preg_replace_callback(
245 - '/_(.)/',
246 - function ( $matches ) {
247 - return '' . strtoupper( $matches[1] );
248 - },
249 - $hashtag
250 - );
251 -
252 - // Add a hashtag to the beginning of the string.
253 - $hashtag = ltrim( $hashtag, '#' );
254 - $hashtag = '#' . $hashtag;
255 -
256 - /**
257 - * Allow defining your own custom hashtag generation rules.
258 - *
259 - * @param string $hashtag The hashtag to be returned.
260 - * @param string $string The original string.
261 - */
262 - $hashtag = apply_filters( 'activitypub_esc_hashtag', $hashtag, $string );
263 -
264 - return esc_html( $hashtag );
191 + return \is_plugin_active( $plugin );
265 192 }
266 193
267 194 /**
268 - * Check if a request is for an ActivityPub request.
195 + * Returns the website hosts allowed to credit this blog.
269 196 *
270 - * @return bool False by default.
197 + * @return array|null The attribution domains or null if not found.
271 198 */
272 -function is_activitypub_request() {
273 - global $wp_query;
274 -
275 - /*
276 - * ActivityPub requests are currently only made for
277 - * author archives, singular posts, and the homepage.
278 - */
279 - if ( ! \is_author() && ! \is_singular() && ! \is_home() && ! defined( '\REST_REQUEST' ) ) {
280 - return false;
199 +function get_attribution_domains() {
200 + if ( '1' !== \get_option( 'activitypub_use_opengraph', '1' ) ) {
201 + return null;
281 202 }
282 203
283 - // Check if the current post type supports ActivityPub.
284 - if ( \is_singular() ) {
285 - $queried_object = \get_queried_object();
286 - $post_type = \get_post_type( $queried_object );
204 + $domains = \get_option( 'activitypub_attribution_domains', home_host() );
205 + $domains = \explode( PHP_EOL, $domains );
287 206
288 - if ( ! \post_type_supports( $post_type, 'activitypub' ) ) {
289 - return false;
290 - }
207 + if ( ! $domains ) {
208 + $domains = null;
291 209 }
292 210
293 - // One can trigger an ActivityPub request by adding ?activitypub to the URL.
294 - // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.VariableRedeclaration
295 - global $wp_query;
296 - if ( isset( $wp_query->query_vars['activitypub'] ) ) {
297 - return true;
298 - }
299 -
300 - /*
301 - * The other (more common) option to make an ActivityPub request
302 - * is to send an Accept header.
303 - */
304 - if ( isset( $_SERVER['HTTP_ACCEPT'] ) ) {
305 - $accept = sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) );
306 -
307 - /*
308 - * $accept can be a single value, or a comma separated list of values.
309 - * We want to support both scenarios,
310 - * and return true when the header includes at least one of the following:
311 - * - application/activity+json
312 - * - application/ld+json
313 - * - application/json
314 - */
315 - if ( preg_match( '/(application\/(ld\+json|activity\+json|json))/i', $accept ) ) {
316 - return true;
317 - }
318 - }
319 -
320 - return false;
211 + return $domains;
321 212 }
322 213
323 214 /**
324 - * This function checks if a user is disabled for ActivityPub.
215 + * Change the display of large numbers on the site.
325 216 *
326 - * @param int $user_id The User-ID.
217 + * @author Jeremy Herve
327 218 *
328 - * @return boolean True if the user is disabled, false otherwise.
329 - */
330 -function is_user_disabled( $user_id ) {
331 - $return = false;
332 -
333 - switch ( $user_id ) {
334 - // if the user is the application user, it's always enabled.
335 - case \Activitypub\Collection\Users::APPLICATION_USER_ID:
336 - $return = false;
337 - break;
338 - // if the user is the blog user, it's only enabled in single-user mode.
339 - case \Activitypub\Collection\Users::BLOG_USER_ID:
340 - if ( is_user_type_disabled( 'blog' ) ) {
341 - $return = true;
342 - break;
343 - }
344 -
345 - $return = false;
346 - break;
347 - // if the user is any other user, it's enabled if it can publish posts.
348 - default:
349 - if ( ! \get_user_by( 'id', $user_id ) ) {
350 - $return = true;
351 - break;
352 - }
353 -
354 - if ( is_user_type_disabled( 'user' ) ) {
355 - $return = true;
356 - break;
357 - }
358 -
359 - if ( ! \user_can( $user_id, 'publish_posts' ) ) {
360 - $return = true;
361 - break;
362 - }
363 -
364 - $return = false;
365 - break;
366 - }
367 -
368 - return apply_filters( 'activitypub_is_user_disabled', $return, $user_id );
369 -}
370 -
371 -/**
372 - * Checks if a User-Type is disabled for ActivityPub.
219 + * @see https://wordpress.org/support/topic/abbreviate-numbers-with-k/
373 220 *
374 - * This function is used to check if the 'blog' or 'user'
375 - * 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.
376 223 *
377 - * @param enum $type Can be 'blog' or 'user'.
378 - *
379 - * @return boolean True if the user type is disabled, false otherwise.
224 + * @return string Converted number in string format.
380 225 */
381 -function is_user_type_disabled( $type ) {
382 - switch ( $type ) {
383 - case 'blog':
384 - if ( \defined( 'ACTIVITYPUB_SINGLE_USER_MODE' ) ) {
385 - if ( ACTIVITYPUB_SINGLE_USER_MODE ) {
386 - $return = false;
387 - break;
388 - }
389 - }
226 +function custom_large_numbers( $formatted, $number ) {
227 + global $wp_locale;
390 228
391 - if ( \defined( 'ACTIVITYPUB_DISABLE_BLOG_USER' ) ) {
392 - $return = ACTIVITYPUB_DISABLE_BLOG_USER;
393 - break;
394 - }
229 + $decimals = 0;
230 + $decimal_point = '.';
231 + $thousands_sep = ',';
395 232
396 - if ( '1' !== \get_option( 'activitypub_enable_blog_user', '0' ) ) {
397 - $return = true;
398 - break;
399 - }
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 + }
400 238
401 - $return = false;
402 - break;
403 - case 'user':
404 - if ( \defined( 'ACTIVITYPUB_SINGLE_USER_MODE' ) ) {
405 - if ( ACTIVITYPUB_SINGLE_USER_MODE ) {
406 - $return = true;
407 - break;
408 - }
409 - }
410 -
411 - if ( \defined( 'ACTIVITYPUB_DISABLE_USER' ) ) {
412 - $return = ACTIVITYPUB_DISABLE_USER;
413 - break;
414 - }
415 -
416 - if ( '1' !== \get_option( 'activitypub_enable_users', '1' ) ) {
417 - $return = true;
418 - break;
419 - }
420 -
421 - $return = false;
422 - break;
423 - default:
424 - $return = new WP_Error( 'activitypub_wrong_user_type', __( 'Wrong user type', 'activitypub' ), array( 'status' => 400 ) );
425 - 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';
426 247 }
427 -
428 - return apply_filters( 'activitypub_is_user_type_disabled', $return, $type );
429 248 }
430 249
431 250 /**
432 - * Check if the blog is in single-user mode.
251 + * Escapes a Tag, to be used as a hashtag.
433 252 *
434 - * @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.
435 256 */
436 -function is_single_user() {
437 - if (
438 - false === is_user_type_disabled( 'blog' ) &&
439 - true === is_user_type_disabled( 'user' )
440 - ) {
441 - return true;
442 - }
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 );
443 261
444 - return false;
445 -}
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 + );
446 270
447 -/**
448 - * Check if a site supports the block editor.
449 - *
450 - * @return boolean True if the site supports the block editor, false otherwise.
451 - */
452 -function site_supports_blocks() {
453 - if ( \version_compare( \get_bloginfo( 'version' ), '5.9', '<' ) ) {
454 - return false;
455 - }
271 + // Add a hashtag to the beginning of the string.
272 + $hashtag = \ltrim( $hashtag, '#' );
273 + $hashtag = \trim( $hashtag, '-' );
274 + $hashtag = '#' . $hashtag;
456 275
457 - if ( ! \function_exists( 'register_block_type_from_metadata' ) ) {
458 - return false;
459 - }
460 -
461 276 /**
462 - * Allow plugins to disable block editor support,
463 - * thus disabling blocks registered by the ActivityPub plugin.
277 + * Allow defining your own custom hashtag generation rules.
464 278 *
465 - * @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.
466 281 */
467 - return apply_filters( 'activitypub_site_supports_blocks', true );
468 -}
282 + $hashtag = \apply_filters( 'activitypub_esc_hashtag', $hashtag, $input );
469 283
470 -/**
471 - * Check if data is valid JSON.
472 - *
473 - * @param string $data The data to check.
474 - *
475 - * @return boolean True if the data is JSON, false otherwise.
476 - */
477 -function is_json( $data ) {
478 - return \is_array( \json_decode( $data, true ) ) ? true : false;
284 + return \esc_html( $hashtag );
479 285 }
480 286
481 287 /**
482 - * 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.
483 289 *
484 - * @return bollean True if public, false if not
485 - */
486 -function is_blog_public() {
487 - return (bool) apply_filters( 'activitypub_is_blog_public', \get_option( 'blog_public', 1 ) );
488 -}
489 -
490 -/**
491 - * 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.
492 293 *
493 - * @param string $value The URL to sanitize
494 - *
495 - * @return string|null The sanitized URL or null if invalid
294 + * @return string The content with links, mentions, hashtags, etc.
496 295 */
497 -function sanitize_url( $value ) {
498 - if ( filter_var( $value, FILTER_VALIDATE_URL ) === false ) {
499 - 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;
500 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 + }
501 316
502 - return esc_url_raw( $value );
503 -}
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 + }
504 330
505 -/**
506 - * Extract recipient URLs from Activity object
507 - *
508 - * @param array $data
509 - *
510 - * @return array The list of user URLs
511 - */
512 -function extract_recipients_from_activity( $data ) {
513 - $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 );
514 334
515 - foreach ( array( 'to', 'bto', 'cc', 'bcc', 'audience' ) as $i ) {
516 - if ( array_key_exists( $i, $data ) ) {
517 - if ( is_array( $data[ $i ] ) ) {
518 - $recipient = $data[ $i ];
519 - } else {
520 - $recipient = array( $data[ $i ] );
521 - }
522 - $recipient_items = array_merge( $recipient_items, $recipient );
335 + // Never inspect tags.
336 + $content_with_links .= $chunk;
337 + continue;
523 338 }
524 339
525 - if ( is_array( $data['object'] ) && array_key_exists( $i, $data['object'] ) ) {
526 - if ( is_array( $data['object'][ $i ] ) ) {
527 - $recipient = $data['object'][ $i ];
528 - } else {
529 - $recipient = array( $data['object'][ $i ] );
530 - }
531 - $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;
532 344 }
533 - }
534 345
535 - $recipients = array();
536 -
537 - // flatten array
538 - foreach ( $recipient_items as $recipient ) {
539 - if ( is_array( $recipient ) ) {
540 - // check if recipient is an object
541 - if ( array_key_exists( 'id', $recipient ) ) {
542 - $recipients[] = $recipient['id'];
543 - }
544 - } else {
545 - $recipients[] = $recipient;
546 - }
346 + // Only reachable when there is no protected tag in the stack.
347 + $content_with_links .= \preg_replace_callback( $regex, $regex_callback, $chunk );
547 348 }
548 349
549 - return array_unique( $recipients );
350 + return $content_with_links;
550 351 }
551 352
552 353 /**
553 - * Check if passed Activity is Public
354 + * Get an ActivityPub embed HTML for a URL.
554 355 *
555 - * @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.
556 358 *
557 - * @return boolean True if public, false if not
359 + * @return string|false The embed HTML or false if not found.
558 360 */
559 -function is_activity_public( $data ) {
560 - $recipients = extract_recipients_from_activity( $data );
561 -
562 - 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 );
563 363 }
564 364
565 365 /**
566 - * Get active users based on a given duration
366 + * Get the client IP address for rate-limiting purposes.
567 367 *
568 - * @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.
569 376 *
570 - * @return int The number of active users
571 - */
572 -function get_active_users( $duration = 1 ) {
573 -
574 - $duration = intval( $duration );
575 - $transient_key = sprintf( 'monthly_active_users_%d', $duration );
576 - $count = get_transient( $transient_key );
577 -
578 - if ( false === $count ) {
579 - global $wpdb;
580 - $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 )";
581 - $query = $wpdb->prepare( $query, $duration );
582 - $count = $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
583 -
584 - set_transient( $transient_key, $count, DAY_IN_SECONDS );
585 - }
586 -
587 - // if 0 authors where active
588 - if ( 0 === $count ) {
589 - return 0;
590 - }
591 -
592 - // if single user mode
593 - if ( is_single_user() ) {
594 - return 1;
595 - }
596 -
597 - // if blog user is disabled
598 - if ( is_user_disabled( Users::BLOG_USER_ID ) ) {
599 - return $count;
600 - }
601 -
602 - // also count blog user
603 - return $count + 1;
604 -}
605 -
606 -/**
607 - * 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.
608 380 *
609 - * @return int The total number of users
610 - */
611 -function get_total_users() {
612 - // if single user mode
613 - if ( is_single_user() ) {
614 - return 1;
615 - }
616 -
617 - $users = \get_users(
618 - array(
619 - 'capability__in' => array( 'publish_posts' ),
620 - )
621 - );
622 -
623 - if ( is_array( $users ) ) {
624 - $users = count( $users );
625 - } else {
626 - $users = 1;
627 - }
628 -
629 - // if blog user is disabled
630 - if ( is_user_disabled( Users::BLOG_USER_ID ) ) {
631 - return $users;
632 - }
633 -
634 - return $users + 1;
635 -}
636 -
637 -/**
638 - * 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.
639 384 *
640 - * @param string $id ActivityPub object ID (usually a URL) to check.
385 + * @since 8.1.0
641 386 *
642 - * @return int|boolean Comment ID, or false on failure.
387 + * @return string A valid IP address, or '' when no IP could be determined.
643 388 */
644 -function object_id_to_comment( $id ) {
645 - $comment_query = new WP_Comment_Query(
646 - array(
647 - 'meta_key' => 'source_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
648 - 'meta_value' => $id, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
649 - )
650 - );
389 +function get_client_ip() {
390 + // phpcs:disable WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders
391 + $ip = '';
651 392
652 - if ( ! $comment_query->comments ) {
653 - return false;
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' ) );
420 +
421 + if ( ! \is_array( $sources ) ) {
422 + $sources = array( 'REMOTE_ADDR' );
654 423 }
655 424
656 - if ( count( $comment_query->comments ) > 1 ) {
657 - return false;
658 - }
425 + foreach ( $sources as $source ) {
426 + if ( ! \is_string( $source ) || empty( $_SERVER[ $source ] ) ) {
427 + continue;
428 + }
659 429
660 - return $comment_query->comments[0];
661 -}
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] );
662 433
663 -/**
664 - * Verify if URL is a local comment,
665 - * Or if it is a previously received remote comment
666 - * (For threading comments locally)
667 - *
668 - * @param string $url The URL to check.
669 - *
670 - * @return int comment_ID or null if not found
671 - */
672 -function url_to_commentid( $url ) {
673 - if ( ! $url || ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
674 - return null;
434 + if ( \filter_var( $candidate, FILTER_VALIDATE_IP ) ) {
435 + $ip = $candidate;
436 + break;
437 + }
675 438 }
439 + // phpcs:enable WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders
676 440
677 - $args = array(
678 - // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
679 - 'meta_query' => array(
680 - 'relation' => 'OR',
681 - array(
682 - 'key' => 'source_url',
683 - 'value' => $url,
684 - ),
685 - array(
686 - 'key' => 'source_id',
687 - 'value' => $url,
688 - ),
689 - ),
690 - );
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 );
691 449
692 - $query = new \WP_Comment_Query();
693 - $comments = $query->query( $args );
694 -
695 - if ( $comments && is_array( $comments ) ) {
696 - 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 );
697 453 }
698 454
699 - return null;
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 : '';
700 457 }