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