-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathfunctions.php
More file actions
445 lines (391 loc) · 13.3 KB
/
Copy pathfunctions.php
File metadata and controls
445 lines (391 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
<?php
/**
* Functions file.
*
* General utility functions for the ActivityPub plugin.
*
* @package Activitypub
*/
namespace Activitypub;
/**
* Get the ActivityPub ID for a WordPress object.
*
* Returns the canonical ActivityPub URI for a WP_Post or WP_Comment.
*
* @param \WP_Post|\WP_Comment $wp_object The WordPress post or comment.
*
* @return string|null The ActivityPub ID (a URL), or null if unsupported type.
*/
function get_object_id( $wp_object ) {
if ( $wp_object instanceof \WP_Post ) {
return get_post_id( $wp_object->ID );
}
if ( $wp_object instanceof \WP_Comment ) {
return get_comment_id( $wp_object );
}
return null;
}
/**
* Return the canonical ActivityPub URL for a WordPress attachment.
*
* The URL points at the plugin's media REST endpoint, which serves the
* AP-JSON representation of the attachment. Used as the `id` of an
* uploaded media object and as the value of the `Location` header on
* a successful `uploadMedia` response.
*
* @since unreleased
*
* @param int $attachment_id The WordPress attachment ID.
* @return string|false The canonical URL, or false if $attachment_id is not an attachment.
*/
function get_attachment_ap_id( $attachment_id ) {
$attachment_id = (int) $attachment_id;
if ( $attachment_id <= 0 ) {
return false;
}
if ( 'attachment' !== \get_post_type( $attachment_id ) ) {
return false;
}
return get_rest_url_by_path( 'media/' . $attachment_id );
}
/**
* Convert a string from camelCase to snake_case.
*
* @param string $input The string to convert.
*
* @return string The converted string.
*/
function camel_to_snake_case( $input ) {
return strtolower( preg_replace( '/(?<!^)[A-Z]/', '_$0', $input ) );
}
/**
* Convert a string from snake_case to camelCase.
*
* @param string $input The string to convert.
*
* @return string The converted string.
*/
function snake_to_camel_case( $input ) {
return lcfirst( str_replace( '_', '', ucwords( $input, '_' ) ) );
}
/**
* Convert seconds to ISO 8601 duration format.
*
* @param int $seconds The duration in seconds.
*
* @return string The duration in ISO 8601 format (e.g., "PT1H23M45S").
*/
function seconds_to_iso8601( $seconds ) {
$seconds = (int) $seconds;
if ( $seconds <= 0 ) {
return 'PT0S';
}
$hours = floor( $seconds / 3600 );
$minutes = floor( ( $seconds % 3600 ) / 60 );
$secs = $seconds % 60;
$duration = 'PT';
if ( $hours > 0 ) {
$duration .= $hours . 'H';
}
if ( $minutes > 0 ) {
$duration .= $minutes . 'M';
}
if ( $secs > 0 || ( 0 === $hours && 0 === $minutes ) ) {
$duration .= $secs . 'S';
}
return $duration;
}
/**
* Check if a site supports the block editor.
*
* @return boolean True if the site supports the block editor, false otherwise.
*/
function site_supports_blocks() {
/**
* Allow plugins to disable block editor support,
* thus disabling blocks registered by the ActivityPub plugin.
*
* @param boolean $supports_blocks True if the site supports the block editor, false otherwise.
*/
return apply_filters( 'activitypub_site_supports_blocks', true );
}
/**
* Check whether a blog is public based on the `blog_public` option.
*
* @return bool True if public, false if not
*/
function is_blog_public() {
/**
* Filter whether the blog is public.
*
* @param bool $public Whether the blog is public.
*/
return (bool) apply_filters( 'activitypub_is_blog_public', \get_option( 'blog_public', 1 ) );
}
/**
* Get the masked WordPress version to only show the major and minor version.
*
* @return string The masked version.
*/
function get_masked_wp_version() {
// Only show the major and minor version.
$version = get_bloginfo( 'version' );
// Strip the RC or beta part.
$version = preg_replace( '/-.*$/', '', $version );
$version = explode( '.', $version );
$version = array_slice( $version, 0, 2 );
return implode( '.', $version );
}
/**
* Check if a plugin is active, loading plugin.php if necessary.
*
* This is a wrapper around the core is_plugin_active() function that ensures
* the function is available by loading wp-admin/includes/plugin.php if needed.
* This is useful when checking plugin status outside of the admin context.
*
* @param string $plugin Plugin basename (e.g., 'plugin-folder/plugin-file.php').
*
* @return bool True if the plugin is active, false otherwise.
*/
function is_plugin_active( $plugin ) {
// Include plugin.php if not already loaded (needed for core is_plugin_active).
if ( ! \function_exists( 'is_plugin_active' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
return \is_plugin_active( $plugin );
}
/**
* Returns the website hosts allowed to credit this blog.
*
* @return array|null The attribution domains or null if not found.
*/
function get_attribution_domains() {
if ( '1' !== \get_option( 'activitypub_use_opengraph', '1' ) ) {
return null;
}
$domains = \get_option( 'activitypub_attribution_domains', home_host() );
$domains = explode( PHP_EOL, $domains );
if ( ! $domains ) {
$domains = null;
}
return $domains;
}
/**
* Change the display of large numbers on the site.
*
* @author Jeremy Herve
*
* @see https://wordpress.org/support/topic/abbreviate-numbers-with-k/
*
* @param string $formatted Converted number in string format.
* @param float $number The number to convert based on locale.
*
* @return string Converted number in string format.
*/
function custom_large_numbers( $formatted, $number ) {
global $wp_locale;
$decimals = 0;
$decimal_point = '.';
$thousands_sep = ',';
if ( isset( $wp_locale ) ) {
$decimals = (int) $wp_locale->number_format['decimal_point'];
$decimal_point = $wp_locale->number_format['decimal_point'];
$thousands_sep = $wp_locale->number_format['thousands_sep'];
}
if ( $number < 1000 ) { // Any number less than a Thousand.
return \number_format( $number, $decimals, $decimal_point, $thousands_sep );
} elseif ( $number < 1000000 ) { // Any number less than a million.
return \number_format( $number / 1000, $decimals, $decimal_point, $thousands_sep ) . 'K';
} elseif ( $number < 1000000000 ) { // Any number less than a billion.
return \number_format( $number / 1000000, $decimals, $decimal_point, $thousands_sep ) . 'M';
} else { // At least a billion.
return \number_format( $number / 1000000000, $decimals, $decimal_point, $thousands_sep ) . 'B';
}
}
/**
* Escapes a Tag, to be used as a hashtag.
*
* @param string $input The string to escape.
*
* @return string The escaped hashtag.
*/
function esc_hashtag( $input ) {
$hashtag = \wp_specialchars_decode( $input, ENT_QUOTES );
// Remove all characters that are not letters, numbers, or hyphens.
$hashtag = \preg_replace( '/[^\p{L}\p{Nd}-]+/u', '-', $hashtag );
// Capitalize every letter that is preceded by a hyphen.
$hashtag = preg_replace_callback(
'/-+(.)/',
static function ( $matches ) {
return strtoupper( $matches[1] );
},
$hashtag
);
// Add a hashtag to the beginning of the string.
$hashtag = ltrim( $hashtag, '#' );
$hashtag = trim( $hashtag, '-' );
$hashtag = '#' . $hashtag;
/**
* Allow defining your own custom hashtag generation rules.
*
* @param string $hashtag The hashtag to be returned.
* @param string $input The original string.
*/
$hashtag = apply_filters( 'activitypub_esc_hashtag', $hashtag, $input );
return esc_html( $hashtag );
}
/**
* Replace content with links, mentions or hashtags by Regex callback and not affect protected tags.
*
* @param string $content The content that should be changed.
* @param string $regex The regex to use.
* @param callable $regex_callback Callback for replacement logic.
*
* @return string The content with links, mentions, hashtags, etc.
*/
function enrich_content_data( $content, $regex, $regex_callback ) {
// Small protection against execution timeouts: limit to 1 MB.
if ( mb_strlen( $content ) > MB_IN_BYTES ) {
return $content;
}
$tag_stack = array();
$protected_tags = array(
'pre',
'code',
'textarea',
'style',
'a',
);
$content_with_links = '';
$in_protected_tag = false;
foreach ( wp_html_split( $content ) as $chunk ) {
if ( preg_match( '#^<!--[\s\S]*-->$#i', $chunk, $m ) ) {
$content_with_links .= $chunk;
continue;
}
if ( preg_match( '#^<(/)?([a-z-]+)\b[^>]*>$#i', $chunk, $m ) ) {
$tag = strtolower( $m[2] );
if ( '/' === $m[1] ) {
// Closing tag.
$i = array_search( $tag, $tag_stack, true );
// We can only remove the tag from the stack if it is in the stack.
if ( false !== $i ) {
$tag_stack = array_slice( $tag_stack, 0, $i );
}
} else {
// Opening tag, add it to the stack.
$tag_stack[] = $tag;
}
// If we're in a protected tag, the tag_stack contains at least one protected tag string.
// The protected tag state can only change when we encounter a start or end tag.
$in_protected_tag = array_intersect( $tag_stack, $protected_tags );
// Never inspect tags.
$content_with_links .= $chunk;
continue;
}
if ( $in_protected_tag ) {
// Don't inspect a chunk inside an inspected tag.
$content_with_links .= $chunk;
continue;
}
// Only reachable when there is no protected tag in the stack.
$content_with_links .= \preg_replace_callback( $regex, $regex_callback, $chunk );
}
return $content_with_links;
}
/**
* Get an ActivityPub embed HTML for a URL.
*
* @param string $url The URL to get the embed for.
* @param boolean $inline_css Whether to inline CSS. Default true.
*
* @return string|false The embed HTML or false if not found.
*/
function get_embed_html( $url, $inline_css = true ) {
return Embed::get_html( $url, $inline_css );
}
/**
* Get the client IP address for rate-limiting purposes.
*
* Walks the ordered list of $_SERVER keys returned by the
* `activitypub_client_ip_sources` filter (default: `['REMOTE_ADDR']`) and
* returns the first value that parses as a valid IP literal, validated via
* `filter_var( ..., FILTER_VALIDATE_IP )`. The result can be overridden
* outright via the `activitypub_client_ip` filter; that filter's output is
* also validated and replaced with `''` when it isn't a valid IP, so a
* misbehaving filter can't collide all callers into the same rate-limit
* bucket.
*
* Trusting any source other than `REMOTE_ADDR` is only safe behind a
* reverse proxy that sets and overwrites the corresponding header — see
* the `activitypub_client_ip_sources` filter docblock for guidance.
*
* Callers using the return value as a rate-limit key should treat an
* empty return as "client unidentifiable" and fail closed rather than
* share a single bucket across every such request.
*
* @since 8.1.0
*
* @return string A valid IP address, or '' when no IP could be determined.
*/
function get_client_ip() {
// phpcs:disable WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders
$ip = '';
/**
* Filter the ordered list of $_SERVER keys to consult as a source for the
* client IP. The first key whose value parses as a valid IP wins.
*
* Default: array( 'REMOTE_ADDR' ) — the actual TCP peer, the only value
* that an HTTP client cannot spoof. Trusting any other $_SERVER key is
* only safe when a reverse proxy in front of the site sets that key and
* overwrites any client-supplied version; otherwise an attacker can spoof
* the value and bypass the per-IP rate limits that depend on it.
*
* Common operator overrides:
* array( 'HTTP_CF_CONNECTING_IP' ) on Cloudflare.
* array( 'HTTP_TRUE_CLIENT_IP', 'REMOTE_ADDR' ) Akamai with a fallback.
* array( 'HTTP_X_REAL_IP' ) nginx that strips the client copy.
*
* X-Forwarded-For pitfall: even with a trusted proxy, an attacker can
* prepend their own value before the proxy appends the real client IP.
* This helper takes the leftmost entry, which is correct only when the
* trusted proxy fully overwrites the header. If you trust X-Forwarded-For
* end-to-end, prefer to resolve from the right by your known proxy count
* via the activitypub_client_ip filter.
*
* @since 8.2.0
*
* @param string[] $sources $_SERVER keys to consult, in priority order.
*/
$sources = \apply_filters( 'activitypub_client_ip_sources', array( 'REMOTE_ADDR' ) );
if ( ! \is_array( $sources ) ) {
$sources = array( 'REMOTE_ADDR' );
}
foreach ( $sources as $source ) {
if ( ! \is_string( $source ) || empty( $_SERVER[ $source ] ) ) {
continue;
}
// Some headers (e.g. X-Forwarded-For) may contain a comma-separated list; use the first IP.
$ip_list = \sanitize_text_field( \wp_unslash( $_SERVER[ $source ] ) );
$candidate = \trim( \explode( ',', $ip_list )[0] );
if ( \filter_var( $candidate, FILTER_VALIDATE_IP ) ) {
$ip = $candidate;
break;
}
}
// phpcs:enable WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders
/**
* Filter the client IP address used for rate limiting.
*
* @since 8.1.0
*
* @param string $ip The detected client IP address (empty when none could be determined).
*/
$ip = \apply_filters( 'activitypub_client_ip', $ip );
// Tolerate surrounding whitespace from filter callbacks; FILTER_VALIDATE_IP would otherwise reject it.
if ( \is_string( $ip ) ) {
$ip = \trim( $ip );
}
// Re-validate so a misbehaving filter can't return a sentinel string that would collapse all callers into one bucket.
return \is_string( $ip ) && \filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '';
}