Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
28.97% covered (danger)
28.97%
93 / 321
28.57% covered (danger)
28.57%
6 / 21
CRAP
n/a
0 / 0
wpcomsh_get_atomic_persistent_data
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
wpcomsh_get_attachment_url
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
wpcomsh_jetpack_sso_auth_cookie_expiration
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
wpcomsh_bypass_jetpack_sso_login
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
30
wpcomsh_modify_jetpack_sso_allowed_actions
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_admin_enqueue_style
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_allow_custom_wp_options
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
check_site_has_pending_automated_transfer
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_jetpack_api_fix_unserializable_track_number
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
wpcomsh_filter_outgoing_user_agent
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcomsh_allowed_redirect_hosts
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
wpcomsh_make_content_clickable
73.33% covered (warning)
73.33%
11 / 15
0.00% covered (danger)
0.00%
0 / 1
7.93
wpcomsh_remove_threats_from_toolbar
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_stats_timezone_string
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
6
wpcomsh_footer_rum_js
88.89% covered (warning)
88.89%
40 / 45
0.00% covered (danger)
0.00%
0 / 1
13.23
wpcomsh_rum_consent_gate_js
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
wpcomsh_get_woo_rum_data
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
wpcomsh_woocommerce_tracker_data
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_record_tracks_event
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
wpcomsh_jetpack_filter_tos_for_tracking
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
wpcomsh_avoid_proxied_v2_banner
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * Plugin Name: WordPress.com Site Helper
4 * Description: A helper for connecting WordPress.com sites to external host infrastructure.
5 * Version: 10.0.0
6 * Author: Automattic
7 * Author URI: http://automattic.com/
8 *
9 * @package wpcomsh
10 */
11
12define( 'WPCOMSH_VERSION', '10.0.0' );
13
14// Loaded first: fatal-error screen filter + one-shot plugin-deactivation endpoint.
15// The deactivator also needs to load before any regular plugin, so in production
16// a stub in wp-content/mu-plugins/ should re-include fatal-plugin-deactivator.php
17// directly (see wpcom-fatal-error/mu-plugin-stub.php).
18require_once __DIR__ . '/wpcom-fatal-error/load.php';
19
20// If true, Typekit fonts will be available in addition to Google fonts
21add_filter( 'jetpack_fonts_enable_typekit', '__return_true' );
22
23// This exists only on the Atomic platform. Blank if migrated elsewhere, so it doesn't fatal.
24if ( ! class_exists( 'Atomic_Persistent_Data' ) ) {
25    require_once __DIR__ . '/class-atomic-persistent-data.php';
26}
27
28/**
29 * Returns a shared Atomic_Persistent_Data instance, as each new instance re-reads and decodes the data file.
30 * Replace this and its calls once Atomic_Persistent_Data has a singleton operation method.
31 *
32 * @return Atomic_Persistent_Data
33 */
34function wpcomsh_get_atomic_persistent_data() {
35    static $persistent_data = null;
36    if ( $persistent_data === null ) {
37        $persistent_data = new Atomic_Persistent_Data();
38    }
39    return $persistent_data;
40}
41
42require_once __DIR__ . '/constants.php';
43require_once __DIR__ . '/wpcom-features/functions-wpcom-features.php';
44require_once __DIR__ . '/wpcom-marketplace/software/class-marketplace-software-manager.php';
45require_once __DIR__ . '/functions.php';
46require_once __DIR__ . '/user-login.php';
47require_once __DIR__ . '/author-slug-redirect.php';
48require_once __DIR__ . '/i18n.php';
49require_once __DIR__ . '/lib/require-lib.php';
50
51require_once __DIR__ . '/plugin-hotfixes.php';
52
53require_once __DIR__ . '/footer-credit/footer-credit.php';
54require_once __DIR__ . '/storefront/storefront.php';
55require_once __DIR__ . '/custom-colors/colors.php';
56require_once __DIR__ . '/storage/storage.php';
57require_once __DIR__ . '/imports/class-backup-import-manager.php';
58
59// Interoperability with the core WordPress data privacy functionality (See also "GDPR")
60require_once __DIR__ . '/privacy/class-wp-privacy-participating-plugins.php';
61
62// Functionality to make sites private and only accessible to members with appropriate capabilities
63require_once __DIR__ . '/private-site/private-site.php';
64
65// Updates customizer Save/Publish labels to avoid confusion on launching vs saving changes on a site.
66require_once __DIR__ . '/customizer-fixes/customizer-fixes.php';
67
68require_once __DIR__ . '/class-wpcomsh-log.php';
69require_once __DIR__ . '/safeguard/plugins.php';
70require_once __DIR__ . '/plugin-conflicts-guardian-rollout.php';
71require_once __DIR__ . '/jetpack-token-error-header/class-atomic-record-jetpack-token-errors.php';
72
73/**
74 * WP.com Widgets (in alphabetical order)
75 */
76require_once __DIR__ . '/widgets/class-gravatar-widget.php';
77require_once __DIR__ . '/widgets/class-jetpack-posts-i-like-widget.php';
78require_once __DIR__ . '/widgets/class-music-player-widget.php';
79require_once __DIR__ . '/widgets/class-widget-authors-grid.php';
80require_once __DIR__ . '/widgets/class-wpcom-freshly-pressed-widget.php';
81require_once __DIR__ . '/widgets/class-wpcom-widget-recent-comments.php';
82require_once __DIR__ . '/widgets/class-wpcom-widget-reservations.php';
83
84// WP.com Category Cloud widget
85require_once __DIR__ . '/widgets/class-wpcom-category-cloud-widget.php';
86// Override core tag cloud widget to add a settable `limit` parameter
87require_once __DIR__ . '/widgets/class-wpcom-tag-cloud-widget.php';
88
89require_once __DIR__ . '/widgets/tlkio/class-tlkio-widget.php';
90require_once __DIR__ . '/widgets/class-widget-top-clicks.php';
91require_once __DIR__ . '/widgets/class-pd-top-rated.php';
92require_once __DIR__ . '/widgets/class-jetpack-widget-twitter.php';
93
94/*
95 * Autoloader check: This ensures the plugin doesn't fatal if activated before
96 * `composer install` has been run. This is a common oversight during development
97 * setup. The admin notice helps developers quickly identify the issue.
98 */
99$jetpack_autoloader = __DIR__ . '/vendor/autoload_packages.php';
100if ( is_readable( $jetpack_autoloader ) ) {
101    require_once $jetpack_autoloader;
102} else {
103    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
104        error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
105            __( 'Error loading autoloader file for WordPress.com Site Helper plugin', 'wpcomsh' )
106        );
107    }
108
109    add_action(
110        'admin_notices',
111        function () {
112            if ( get_current_screen()->id !== 'plugins' ) {
113                return;
114            }
115
116            $message = sprintf(
117                wp_kses(
118                    /* translators: Placeholder is a link to a support document. */
119                    __( 'Your installation of WordPress.com Site Helper is incomplete. If you installed WordPress.com Site Helper from GitHub, please refer to <a href="%1$s" target="_blank" rel="noopener noreferrer">this document</a> to set up your development environment. WordPress.com Site Helper must have Composer dependencies installed and built via the build command.', 'wpcomsh' ),
120                    array(
121                        'a' => array(
122                            'href'   => array(),
123                            'target' => array(),
124                            'rel'    => array(),
125                        ),
126                    )
127                ),
128                'https://github.com/Automattic/jetpack/blob/trunk/docs/development-environment.md#building-your-project'
129            );
130            wp_admin_notice(
131                $message,
132                array(
133                    'type'        => 'error',
134                    'dismissible' => true,
135                )
136            );
137        }
138    );
139
140    return;
141}
142require_once __DIR__ . '/vendor/automattic/custom-fonts/custom-fonts.php';
143require_once __DIR__ . '/vendor/automattic/custom-fonts-typekit/custom-fonts-typekit.php';
144require_once __DIR__ . '/vendor/automattic/text-media-widget-styles/text-media-widget-styles.php';
145
146// REST API
147require_once __DIR__ . '/endpoints/rest-api.php';
148
149// Load feature plugins.
150require_once __DIR__ . '/feature-plugins/activitypub.php';
151require_once __DIR__ . '/feature-plugins/additional-css.php';
152require_once __DIR__ . '/feature-plugins/ai-launchpad.php';
153require_once __DIR__ . '/feature-plugins/autosave-revision.php';
154require_once __DIR__ . '/feature-plugins/blaze.php';
155require_once __DIR__ . '/feature-plugins/coblocks-mods.php';
156require_once __DIR__ . '/feature-plugins/crowdsignal.php';
157require_once __DIR__ . '/feature-plugins/full-site-editing.php';
158require_once __DIR__ . '/feature-plugins/google-fonts.php';
159require_once __DIR__ . '/feature-plugins/gutenberg-mods.php';
160require_once __DIR__ . '/feature-plugins/headstart-util.php';
161require_once __DIR__ . '/feature-plugins/headstart-woocommerce-terms.php';
162require_once __DIR__ . '/feature-plugins/hooks.php';
163require_once __DIR__ . '/feature-plugins/managed-plugins.php';
164require_once __DIR__ . '/feature-plugins/managed-themes.php';
165require_once __DIR__ . '/feature-plugins/marketplace.php';
166require_once __DIR__ . '/feature-plugins/masterbar.php';
167require_once __DIR__ . '/feature-plugins/migrate-guru-canary.php';
168require_once __DIR__ . '/feature-plugins/nav-redesign.php';
169require_once __DIR__ . '/feature-plugins/post-list.php';
170require_once __DIR__ . '/feature-plugins/class-wpcomsh-recovery-mode-sync.php';
171require_once __DIR__ . '/feature-plugins/sensei-pro-mods.php';
172require_once __DIR__ . '/feature-plugins/smtp-email-priority.php';
173require_once __DIR__ . '/feature-plugins/staging-sites.php';
174require_once __DIR__ . '/feature-plugins/stats.php';
175require_once __DIR__ . '/feature-plugins/woocommerce.php';
176require_once __DIR__ . '/feature-plugins/wordpress-mods.php';
177require_once __DIR__ . '/feature-plugins/wpcom-reader-link.php';
178require_once __DIR__ . '/feature-plugins/featured-image-in-email.php';
179
180// Jetpack Connection Handlers (external storage and protected owner).
181// Load this file before jetpack-mu-wpcom, so that the storage provider is in place before its init() reads the blog ID.
182require_once __DIR__ . '/connection/connection-handlers.php';
183
184/**
185 * Conditionally load the jetpack-mu-wpcom package.
186 *
187 * JETPACK_MU_WPCOM_LOAD_VIA_BETA_PLUGIN=true will load the package via the Jetpack Beta Tester plugin, not wpcomsh.
188 */
189if ( ! defined( 'JETPACK_MU_WPCOM_LOAD_VIA_BETA_PLUGIN' ) || ! JETPACK_MU_WPCOM_LOAD_VIA_BETA_PLUGIN ) {
190    if ( class_exists( 'Automattic\Jetpack\Jetpack_Mu_Wpcom' ) ) {
191        Automattic\Jetpack\Jetpack_Mu_Wpcom::init();
192    }
193}
194
195if ( ! class_exists( 'Jetpack_Data' ) ) {
196    require_once __DIR__ . '/feature-plugins/class-jetpack-data.php';
197}
198
199// Front end notices.
200require_once __DIR__ . '/frontend-notices/wpcomsh-frontend-notices.php';
201
202// wp-admin Notices
203require_once __DIR__ . '/notices/plan-notices.php';
204require_once __DIR__ . '/notices/storage-notices.php';
205require_once __DIR__ . '/notices/php-version-notices.php';
206require_once __DIR__ . '/notices/media-library-private-site-cdn-notice.php';
207require_once __DIR__ . '/notices/anyone-can-register-notice.php';
208require_once __DIR__ . '/notices/feature-moved-to-jetpack-notices.php';
209
210// Performance Profiler
211require_once __DIR__ . '/performance-profiler/performance-profiler.php';
212
213if ( defined( 'WP_CLI' ) && WP_CLI ) {
214    require_once __DIR__ . '/class-wpcomsh-cli-commands.php';
215    require_once __DIR__ . '/woa.php';
216}
217
218require_once __DIR__ . '/wpcom-migration-helpers/site-migration-helpers.php';
219
220// We include WPCom Themes results and installation on non-WP_CLI context.
221if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
222    require_once __DIR__ . '/wpcom-themes/themes.php';
223}
224
225require_once __DIR__ . '/class-jetpack-plugin-compatibility.php';
226Jetpack_Plugin_Compatibility::get_instance();
227
228require_once __DIR__ . '/support-session.php';
229
230// Adds fallback behavior for non-Gutenframed sites to be able to use the 'Share Post' functionality from WPCOM Reader.
231require_once __DIR__ . '/share-post/share-post.php';
232
233// Require a Jetpack Connection Owner.
234require_once __DIR__ . '/jetpack-require-connection-owner/class-wpcomsh-require-connection-owner.php';
235
236// Enable MailPoet subscriber stats reports
237require_once __DIR__ . '/mailpoet/class-wpcomsh-mailpoet-subscribers-stats-report.php';
238
239// Force Jetpack to update plugins one-at-a-time to avoid a site-breaking core concurrent update bug
240// https://core.trac.wordpress.org/ticket/53705
241if (
242    ! defined( 'JETPACK_PLUGIN_AUTOUPDATE' ) &&
243    0 === strncmp( $_SERVER['REQUEST_URI'], '/xmlrpc.php?', strlen( '/xmlrpc.php?' ) ) ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
244    define( 'JETPACK_PLUGIN_AUTOUPDATE', true );
245}
246
247/**
248 * Filter attachment URLs if the 'wpcom_attachment_subdomain' option is present.
249 * Local image files will be unaffected, as they will pass a file_exists check.
250 * Files stored remotely will be filtered to have the correct URL.
251 *
252 * Once the files have been transferred, the 'wpcom_attachment_subdomain' will
253 * be removed, preventing further stats.
254 *
255 * @param string $url The attachment URL.
256 * @param int    $post_id The post id.
257 * @return string The filtered attachment URL.
258 */
259function wpcomsh_get_attachment_url( $url, $post_id ) {
260    $attachment_subdomain = get_option( 'wpcom_attachment_subdomain' );
261    if ( $attachment_subdomain ) {
262        $file = get_post_meta( $post_id, '_wp_attached_file', true );
263
264        if ( $file ) {
265            $local_file = WP_CONTENT_DIR . '/uploads/' . $file;
266            if ( ! file_exists( $local_file ) ) {
267                return esc_url( 'https://' . $attachment_subdomain . '/' . $file );
268            }
269        }
270    }
271    return $url;
272}
273add_filter( 'wp_get_attachment_url', 'wpcomsh_get_attachment_url', 11, 2 );
274
275/**
276 * When WordPress.com passes along an expiration for auth cookies and it is smaller
277 * than the value set by Jetpack by default (YEAR_IN_SECONDS), use the smaller value.
278 *
279 * @param int $seconds The cookie expiration in seconds.
280 * @return int The filtered cookie expiration in seconds
281 */
282function wpcomsh_jetpack_sso_auth_cookie_expiration( $seconds ) {
283    if ( isset( $_GET['expires'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
284        $expires = absint( $_GET['expires'] ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
285
286        if ( ! empty( $expires ) && $expires < $seconds ) {
287            $seconds = $expires;
288        }
289    }
290    return intval( $seconds );
291}
292add_filter( 'jetpack_sso_auth_cookie_expiration', 'wpcomsh_jetpack_sso_auth_cookie_expiration' );
293
294/**
295 * Determine if users should be enforced to log in with their WP.com account.
296 *
297 * Sites without local users:
298 * - WP.com login, always.
299 *
300 * Sites with local users:
301 * - If user comes from Calypso: WP.com login
302 * - Otherwise: Jetpack SSO login, so they can decide whether to use a WP.com account or a local account.
303 */
304function wpcomsh_bypass_jetpack_sso_login() {
305    $calypso_domains = array(
306        'https://wordpress.com/',
307        'https://horizon.wordpress.com/',
308        'https://wpcalypso.wordpress.com/',
309        'http://calypso.localhost:3000/',
310        'http://127.0.0.1:41050/', // Desktop App.
311    );
312    if ( in_array( wp_get_referer(), $calypso_domains, true ) ) {
313        return true;
314    }
315
316    if ( class_exists( '\Automattic\Jetpack\Connection\Manager' ) ) {
317        $connection_manager = new \Automattic\Jetpack\Connection\Manager( 'jetpack' );
318
319        // Fetching an extra field to overcome the caching bug: https://core.trac.wordpress.org/ticket/62003
320        $users = get_users( array( 'fields' => array( 'ID', 'user_login' ) ) );
321        foreach ( $users as $user ) {
322            if ( ! $connection_manager->is_user_connected( $user->ID ) ) {
323                return false;
324            }
325        }
326    }
327
328    return true;
329}
330add_filter( 'jetpack_sso_bypass_login_forward_wpcom', 'wpcomsh_bypass_jetpack_sso_login' );
331
332/**
333 * Add 'loggedout' to the list of actions that allow the wpcom login form to be used.
334 *
335 * This means that the login screen the user sees immediately after logging out is consistent
336 * with the login screen the user sees when they are not logged in: the wpcom login form.
337 *
338 * @param array $allowed_actions The allowed actions.
339 * @return array The modified allowed actions.
340 */
341function wpcomsh_modify_jetpack_sso_allowed_actions( $allowed_actions ) {
342    $allowed_actions[] = 'loggedout';
343    return $allowed_actions;
344}
345add_filter( 'jetpack_sso_allowed_actions', 'wpcomsh_modify_jetpack_sso_allowed_actions' );
346
347/**
348 * Overwrite the default value of SSO "Match by Email" setting.
349 * p9o2xV-2zY-p2
350 */
351add_filter( 'default_option_jetpack_sso_match_by_email', '__return_true' );
352
353/**
354 * Admin enqueue style
355 */
356function wpcomsh_admin_enqueue_style() {
357    wp_enqueue_style(
358        'wpcomsh-admin-style',
359        plugins_url( 'assets/admin-style.css', __FILE__ ),
360        array(),
361        WPCOMSH_VERSION
362    );
363}
364add_action( 'admin_enqueue_scripts', 'wpcomsh_admin_enqueue_style', 999 );
365
366/**
367 * Allow custom wp options
368 *
369 * @param array $options The options.
370 *
371 * @return array
372 */
373function wpcomsh_allow_custom_wp_options( $options ) {
374    // For storing AT options.
375    $options[] = 'at_options';
376    $options[] = 'at_options_logging_on';
377    $options[] = 'at_wpcom_premium_theme';
378    $options[] = 'jetpack_fonts';
379    $options[] = 'site_logo';
380    $options[] = 'footercredit';
381    $options[] = 'wpcomsh_at_managed_plugins';
382    $options[] = 'wpcomsh_at_managed_themes';
383
384    return $options;
385}
386add_filter( 'jetpack_options_whitelist', 'wpcomsh_allow_custom_wp_options' );
387
388add_filter( 'jetpack_site_automated_transfer', '__return_true' );
389
390/**
391 * Check site has pending automated transfer
392 *
393 * @return bool
394 */
395function check_site_has_pending_automated_transfer() {
396    return get_option( 'has_pending_automated_transfer' );
397}
398
399add_filter( 'jetpack_site_pending_automated_transfer', 'check_site_has_pending_automated_transfer' );
400
401/**
402 * We have some instances where `track_number` of an audio attachment is `??0` and shows up as type string.
403 * However the problem is, that if post has nested property attachments with this track_number, `json_serialize` fails silently.
404 * Of course, this should be fixed during audio upload, but we need this fix until we can clean this up properly.
405 * More detail here: https://github.com/Automattic/automated-transfer/issues/235
406 *
407 * @param array $exif_data The file exif data.
408 *
409 * @return array
410 */
411function wpcomsh_jetpack_api_fix_unserializable_track_number( $exif_data ) {
412    if ( isset( $exif_data['track_number'] ) ) {
413        $exif_data['track_number'] = intval( $exif_data['track_number'] );
414    }
415    return $exif_data;
416}
417add_filter( 'wp_get_attachment_metadata', 'wpcomsh_jetpack_api_fix_unserializable_track_number' );
418
419// Jetpack for Atomic sites are always production version.
420add_filter( 'jetpack_development_version', '__return_false' );
421
422/**
423 * Make User Agent consistent with the rest of WordPress.com.
424 *
425 * @param mixed $agent The agent.
426 */
427function wpcomsh_filter_outgoing_user_agent( $agent ) {
428    global $wp_version;
429
430    return str_replace( "WordPress/$wp_version", 'WordPress.com', $agent );
431}
432add_filter( 'http_headers_useragent', 'wpcomsh_filter_outgoing_user_agent', 999 );
433
434/**
435 * Allow redirects to WordPress.com from Customizer.
436 *
437 * @param array $hosts The hosts.
438 */
439function wpcomsh_allowed_redirect_hosts( $hosts ) {
440    if ( is_array( $hosts ) ) {
441        $hosts[] = 'wordpress.com';
442        $hosts[] = 'calypso.localhost';
443        $hosts   = array_unique( $hosts );
444    }
445    return $hosts;
446}
447add_filter( 'allowed_redirect_hosts', 'wpcomsh_allowed_redirect_hosts', 11 );
448
449/**
450 * WP.com make clickable
451 *
452 * Converts all plain-text HTTP URLs in post_content to links on display.
453 * Uses WP_HTML_Tag_Processor for proper HTML tokenization that won't be confused by
454 * content inside tags (e.g., JavaScript comparison operators in script tags).
455 *
456 * @param string $content The content.
457 * @return string Modified content with linkified URLs.
458 * @uses make_clickable()
459 * @since 20121125
460 */
461function wpcomsh_make_content_clickable( $content ) {
462    // Fast path: no URL-shaped substring, no work to do. Avoids loading the
463    // linkifier and walking the tokenizer for the common case.
464    if ( ! $content || ( false === stripos( $content, 'http' ) && false === stripos( $content, 'www.' ) ) ) {
465        return $content;
466    }
467
468    if ( ! method_exists( 'WP_HTML_Tag_Processor', 'next_token' ) ) {
469        if ( function_exists( 'bump_stats_extras' ) ) {
470            bump_stats_extras( 'wpcomsh-make-content-clickable', 'skipped-no-html-api' );
471        }
472        return $content;
473    }
474
475    require_once __DIR__ . '/class-wpcomsh-html-linkifier.php';
476
477    return Wpcomsh_HTML_Linkifier::modify_raw_text_nodes(
478        $content,
479        static function ( $raw_text ) {
480            return 1 === preg_match( '~https?://|www\.~', $raw_text )
481                ? make_clickable( $raw_text )
482                : $raw_text;
483        }
484    );
485}
486add_filter( 'the_content', 'wpcomsh_make_content_clickable', 120 );
487add_filter( 'the_excerpt', 'wpcomsh_make_content_clickable', 120 );
488
489/**
490 * Unhook Jetpack Scan Admin Notice
491 *
492 * Remove once Atomic only runs Jetpack builds that check `jetpack_protect_threat_notifications_enabled`.
493 *
494 * @return void
495 */
496function wpcomsh_remove_threats_from_toolbar() {
497    global $wp_admin_bar;
498    $wp_admin_bar->remove_node( 'jetpack-scan-notice' );
499}
500add_action( 'wp_before_admin_bar_render', 'wpcomsh_remove_threats_from_toolbar', 999999 );
501
502/**
503 * Returns a standardized timezone string.
504 *
505 * `wp_timezone_string()` sometimes returns offsets (e.g. "-07:00"), which are
506 * a non-standard representation of a UTC offset that only works in PHP.
507 * This function returns a standardized timezone string instead, of the form
508 * "Etc/GMT+7" for integer hour offsets, or a matching "<Area>/<City>" form for
509 * fractional hour offsets (used e.g. in India).
510 */
511function wpcomsh_stats_timezone_string() {
512    $wp_tz = wp_timezone_string();
513
514    // Did we get back an offset?
515    if ( preg_match( '/^([+-])?(\d{1,2}):(\d{2})$/', $wp_tz, $matches ) ) {
516        $sign    = $matches[1] === '-' ? -1 : 1;
517        $hours   = intval( $matches[2], 10 );
518        $minutes = intval( $matches[3], 10 );
519
520        // For fractional hour offsets, use `timezone_name_from_abbr` to get a
521        // matching "<Area>/<City>" timezone.
522        if ( $minutes > 0 ) {
523            $offset  = $sign * ( $hours * 3600 + $minutes * 60 );
524            $city_tz = timezone_name_from_abbr( '', $offset, 0 );
525
526            if ( ! empty( $city_tz ) ) {
527                return $city_tz;
528            }
529        }
530
531        // For integer hour offsets, use "Etc/GMT(+|-)<offset>".
532        // The sign is flipped, to match how the `Etc` area is specced.
533        //
534        // This codepath is also followed if no city exists to match a
535        // fractional offset, by simply discarding the fractional part.
536        // This isn't ideal, but there's no standard way of describing
537        // these offsets, and is likely to be an extreme edge case.
538        return 'Etc/GMT' . ( $sign === -1 ? '+' : '-' ) . $hours;
539    }
540
541    // For anything that's not an offset, return the string we got from WP.
542    return $wp_tz;
543}
544
545/**
546 * Collect RUM performance data
547 * p9o2xV-XY-p2
548 */
549function wpcomsh_footer_rum_js() {
550    $service      = 'atomic';
551    $allow_iframe = '';
552    if ( 'admin_footer' === current_action() ) {
553        $service = 'atomic-wpadmin';
554
555        $block_editor = \Automattic\Jetpack\Jetpack_Mu_Wpcom\WPCOM_Block_Editor\Jetpack_WPCOM_Block_Editor::init();
556        if ( $block_editor->is_iframed_block_editor() ) {
557            $service      = 'atomic-gutenframe';
558            $allow_iframe = 'data-allow-iframe="true"';
559        }
560    }
561
562    $rum_kv = array();
563    $rum_kv = apply_filters( 'wpcomsh_rum_kv', $rum_kv, $service );
564    if ( ! is_array( $rum_kv ) ) {
565        $rum_kv = array();
566    }
567
568    $rum_kv = wpcomsh_get_woo_rum_data( $rum_kv );
569    // Add user login and theme info.
570    $rum_kv['logged_in']        = is_user_logged_in() ? '1' : '0';
571    $rum_kv['wptheme']          = get_stylesheet();
572    $rum_kv['wptheme_is_block'] = wp_is_block_theme() ? '1' : '0';
573
574    if ( count( $rum_kv ) > 0 ) {
575        $rum_kv = wp_json_encode( $rum_kv, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_HEX_AMP );
576        if ( is_string( $rum_kv ) ) {
577            $rum_kv = 'data-customproperties="' . esc_attr( $rum_kv ) . '"';
578        } else {
579            $rum_kv = '';
580        }
581    } else {
582        $rum_kv = '';
583    }
584
585    $site_v = apply_filters( 'wpcomsh_bilmur_site_v', null );
586
587    if ( true === $site_v ) {
588        $site_v = md5( (string) wp_parse_url( home_url(), PHP_URL_HOST ) );
589    }
590
591    $data_site_tz = 'data-site-tz="' . esc_attr( wpcomsh_stats_timezone_string() ) . '"';
592
593    $data_site_v = ( is_string( $site_v ) && '' !== $site_v )
594            ? 'data-site-v="' . esc_attr( $site_v ) . '"'
595            : '';
596
597    printf(
598        '<meta id="bilmur" property="bilmur:data" content="" %1$s data-provider="wordpress.com" data-service="%2$s" %3$s %4$s %5$s >' . "\n",
599        $rum_kv, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
600        esc_attr( $service ),
601        wp_kses_post( $allow_iframe ),
602        $data_site_tz, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
603        $data_site_v // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
604    );
605
606    $script_url = 'https://s0.wp.com/wp-content/js/bilmur.min.js?m=' . gmdate( 'YW' );
607
608    // The banner that collects consent only runs on the front end.
609    if ( 'atomic' === $service && function_exists( 'wp_has_consent' ) ) {
610        wp_print_inline_script_tag( wpcomsh_rum_consent_gate_js( $script_url ) );
611        return;
612    }
613
614    // Print the script tag straight away if no consent service is present
615    // (e.g. in admin).
616    printf(
617        '<script defer src="%s"></script>' . "\n", //phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
618        esc_url( $script_url )
619    );
620}
621
622/**
623 * Build an inline script that loads bilmur once the visitor allows statistics.
624 *
625 * The check runs in the browser because cached HTML is shared across visitors.
626 *
627 * @param string $script_url The bilmur script URL.
628 * @return string
629 */
630function wpcomsh_rum_consent_gate_js( $script_url ) {
631    return sprintf(
632        '( function () {
633    var loadDone = false;
634    function load() {
635        if ( loadDone ) { return; }
636        loadDone = true;
637        var script = document.createElement( "script" );
638        script.src = %s;
639        document.head.appendChild( script );
640    }
641    function check() {
642        if ( typeof window.wp_has_consent === "function" && window.wp_has_consent( "statistics" ) ) { load(); }
643    }
644    document.addEventListener( "wp_listen_for_consent_change", function ( event ) {
645        var value = event.detail && event.detail[ "statistics" ];
646        if ( value === "allow" ) { load(); }
647        // Withdrawing consent must also drop a beacon bilmur might have already queued.
648        if ( value === "deny" && loadDone ) { document.dispatchEvent( new Event( "bilmur:cancel" ) ); }
649    } );
650    document.addEventListener( "wp_consent_type_defined", check );
651    if ( document.readyState === "loading" ) {
652        document.addEventListener( "DOMContentLoaded", check );
653    } else {
654        check();
655    }
656} )();',
657        wp_json_encode( esc_url_raw( $script_url ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP )
658    );
659}
660
661/**
662 * Adds WooCommerce-related data to the Real User Monitoring (RUM) array.
663 *
664 * This function checks if WooCommerce is active on the site and adds
665 * this information to the provided RUM data array. It's designed to be
666 * used as part of the RUM data collection process for Atomic sites.
667 *
668 * @param array $rum_kv An array of existing RUM key-value pairs.
669 *                      If not provided, an empty array will be used.
670 *
671 * @return array The input array with added WooCommerce data.
672 *               The 'woo_active' key will be added with a boolean value
673 *               indicating whether WooCommerce is active.
674 */
675function wpcomsh_get_woo_rum_data( $rum_kv = array() ) {
676    $woo_active           = class_exists( 'WooCommerce' ) ? '1' : '0';
677    $rum_kv['woo_active'] = $woo_active;
678    return $rum_kv;
679}
680
681add_action( 'wp_footer', 'wpcomsh_footer_rum_js' );
682add_action( 'admin_footer', 'wpcomsh_footer_rum_js' );
683
684/**
685 * Adds Atomic site ID to WooCommerce tracker data.
686 *
687 * @param array $data The WooCommerce tracker data.
688 *
689 * @return array The WooCommerce tracker data with Atomic site ID added.
690 */
691function wpcomsh_woocommerce_tracker_data( $data ) {
692    $data['atomic_site_id'] = wpcomsh_get_atomic_site_id();
693    return $data;
694}
695
696add_filter( 'woocommerce_tracker_data', 'wpcomsh_woocommerce_tracker_data' );
697
698add_filter( 'amp_dev_tools_user_default_enabled', '__return_false' );
699
700/**
701 * Tracks helper. Filters Jetpack TOS option if class exists.
702 *
703 * @param mixed $event The event.
704 * @param mixed $event_properties The event property.
705 *
706 * @return void
707 */
708function wpcomsh_record_tracks_event( $event, $event_properties ) {
709    if ( class_exists( '\Automattic\Jetpack\Tracking' ) ) {
710        // User has to agree to ToS for tracking. Thing is, on initial Simple -> Atomic we never set the ToS option.
711        // And since they agreed to WP.com ToS, we can track but in a roundabout way. :).
712        add_filter( 'jetpack_options', 'wpcomsh_jetpack_filter_tos_for_tracking', 10, 2 );
713
714        $jetpack_tracks = new \Automattic\Jetpack\Tracking( 'atomic' );
715        $jetpack_tracks->tracks_record_event(
716            wp_get_current_user(),
717            $event,
718            $event_properties
719        );
720
721        remove_filter( 'jetpack_options', 'wpcomsh_jetpack_filter_tos_for_tracking', 10 );
722    }
723}
724
725/**
726 * Helper for filtering tos_agreed for tracking purposes.
727 * Explicit function so it can be removed afterwards.
728 *
729 * @param mixed $value The value.
730 * @param mixed $name Name.
731 *
732 * @return mixed
733 */
734function wpcomsh_jetpack_filter_tos_for_tracking( $value, $name ) {
735    if ( 'tos_agreed' === $name ) {
736        return true;
737    }
738
739    return $value;
740}
741
742/**
743 * Avoid proxied v2 banner
744 *
745 * @return void
746 */
747function wpcomsh_avoid_proxied_v2_banner() {
748    $priority = has_action( 'wp_footer', 'atomic_proxy_bar' );
749    if ( false !== $priority ) {
750        remove_action( 'wp_footer', 'atomic_proxy_bar', $priority );
751    }
752
753    $priority = has_action( 'admin_footer', 'atomic_proxy_bar' );
754    if ( false !== $priority ) {
755        remove_action( 'admin_footer', 'atomic_proxy_bar', $priority );
756    }
757}
758
759// We don't want to show a "PROXIED V2" banner for legacy widget previews
760// which are normally embedded within another page.
761if (
762    defined( 'AT_PROXIED_REQUEST' ) && AT_PROXIED_REQUEST &&
763    isset( $_GET['legacy-widget-preview'] ) && //phpcs:ignore WordPress.Security.NonceVerification
764    0 === strncmp( $_SERVER['REQUEST_URI'], '/wp-admin/widgets.php?', strlen( '/wp-admin/widgets.php?' ) ) ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
765    add_action( 'plugins_loaded', 'wpcomsh_avoid_proxied_v2_banner' );
766}