Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
7.74% covered (danger)
7.74%
38 / 491
4.88% covered (danger)
4.88%
2 / 41
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Mu_Wpcom
7.76% covered (danger)
7.76%
38 / 490
4.88% covered (danger)
4.88%
2 / 41
25047.50
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
72
 load_wpcom_simple_jetpack_ai
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 schedule_translation_updates
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 maybe_update_translations
0.00% covered (danger)
0.00%
0 / 60
0.00% covered (danger)
0.00%
0 / 1
420
 clear_translation_destination
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
 get_all_active_locales
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 load_features
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
30
 load_wpcom_user_features
15.00% covered (danger)
15.00%
6 / 40
0.00% covered (danger)
0.00%
0 / 1
71.41
 load_wpcom_sites_features
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 load_etk_features_flags
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
20
 load_etk_features
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
90
 load_newspack_blocks
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
30
 load_coming_soon
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
90
 load_launchpad
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 load_wpcom_rest_api_endpoints
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 load_jetpack_mu_wpcom_settings
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
2
 load_map_block_settings
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 load_newsletter_categories_settings
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 unbind_focusout_on_wp_admin_bar_menu_toggle
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 should_disable_comment_experience
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
90
 load_verbum_comments
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 load_jetpack_comments_routes
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 enable_jetpack_comments_for_sticker
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 load_verbum_comments_admin
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 load_verbum_moderate
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 load_wpcom_simple_odyssey_stats
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 load_premium_analytics_wordads_section
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 load_custom_css
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 load_wpcom_random_redirect
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 load_social_links
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 set_wpcom_blog_id_script_data
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 enable_gutenberg_react_19_experiment
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
90
 enable_woocommerce_block_editor_unified_assets
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 has_react_19_incompatible_gutenberg
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 enable_extensible_site_editor_experiment
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 has_react_19_incompatible_extension
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
56
 is_react_19_incompatible_version
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 add_jetpack_script_data_for_p2
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
 log2logstash
71.43% covered (warning)
71.43%
15 / 21
0.00% covered (danger)
0.00%
0 / 1
9.49
 resolve_logstash_blog_id
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
5.93
 queue_logstash_http
42.11% covered (danger)
42.11%
8 / 19
0.00% covered (danger)
0.00%
0 / 1
7.10
1<?php
2/**
3 * Enhances your site with features powered by WordPress.com
4 * This package is intended for internal use on WordPress.com sites only (simple and Atomic).
5 * Internal PT Reference: p9dueE-6jY-p2
6 *
7 * @package automattic/jetpack-mu-wpcom
8 */
9
10namespace Automattic\Jetpack;
11
12define( 'WPCOM_ADMIN_BAR_UNIFICATION', true );
13/**
14 * Jetpack_Mu_Wpcom main class.
15 */
16class Jetpack_Mu_Wpcom {
17    const PACKAGE_VERSION = '6.10.1';
18    const PKG_DIR         = __DIR__ . '/../';
19    const BASE_DIR        = __DIR__ . '/';
20    const BASE_FILE       = __FILE__;
21
22    // Gutenberg plugin releases known to break with React 19.
23    const REACT_19_INCOMPATIBLE_GUTENBERG = array( '23.9.0' );
24
25    /*
26     * Themes (by template slug) and plugins (by basename) known to break with React 19,
27     * each mapped to the release that fixed it. Null means no fixed release exists yet.
28     */
29    const REACT_19_INCOMPATIBLE_THEMES  = array(
30        'divi'     => null,
31        'woodmart' => '8.6.1',
32    );
33    const REACT_19_INCOMPATIBLE_PLUGINS = array(
34        'wp-table-builder/wp-table-builder.php'          => null,
35        'ultimate-blocks/ultimate-blocks.php'            => '3.6.0',
36        'beehive-analytics/beehive-analytics.php'        => null,
37        'xspeed/xspeed.php'                              => null,
38        'classified-listing/classified-listing.php'      => null,
39        'advanced-coupons-for-woocommerce-free/advanced-coupons-for-woocommerce-free.php' => null,
40        'advanced-coupons-for-woocommerce/advanced-coupons-for-woocommerce.php' => null,
41        'sb-analytics/sb-analytics-pro.php'              => null,
42        'brave-popup-builder/index.php'                  => null,
43        'bravepopup-pro/index.php'                       => null,
44        'astra-sites/astra-sites.php'                    => null,
45        'llms-full-txt-generator/llms-txt-generator.php' => null,
46        'wp-post-author/aft-wp-post-author.php'          => null,
47        'adminify/adminify.php'                          => null,
48    );
49
50    /**
51     * Initialize the class.
52     */
53    public static function init() {
54        if ( did_action( 'jetpack_mu_wpcom_initialized' ) ) {
55            return;
56        }
57
58        // Shared code for src/features.
59        require_once self::PKG_DIR . 'src/common/index.php'; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.NotAbsolutePath
60        require_once __DIR__ . '/common/fatal-error-signature.php';
61        require_once __DIR__ . '/utils.php';
62
63        // Atomic only — Simple sites can't install plugins. The confirmation
64        // probe wires its `pre_option_active_plugins` filter at mu-plugin
65        // time, before WP loads active plugins.
66        if ( Constants::is_true( 'IS_ATOMIC' ) ) {
67            require_once __DIR__ . '/features/plugin-conflicts-guardian/probe-confirm-bootstrap.php';
68        }
69
70        /*
71         * Feature flag overrides answer the jetpack-feature-flags resolution
72         * filter, and a flag can be checked well before plugins_loaded, so this
73         * is wired here at mu-plugin time rather than from load_features().
74         * Registering the filter reads nothing — the option is only touched when
75         * a flag is actually resolved.
76         *
77         * The overrides themselves are site-wide, but the screen that sets them
78         * is Automatticians-only internal tooling and gates itself accordingly.
79         */
80        require_once __DIR__ . '/features/wpcom-feature-flags/class-wpcom-feature-flags.php';
81        \Automattic\Jetpack\Jetpack_Mu_Wpcom\Wpcom_Feature_Flags::init();
82
83        // Load features that don't need any special loading considerations.
84        add_action( 'plugins_loaded', array( __CLASS__, 'load_features' ) );
85
86        // Load features that only apply to WordPress.com-connected users.
87        add_action( 'plugins_loaded', array( __CLASS__, 'load_wpcom_user_features' ) );
88        add_action( 'plugins_loaded', array( __CLASS__, 'load_etk_features' ) );
89
90        // Load features that only apply to WordPress.com sites, regardless of whether the users are connected.
91        add_action( 'plugins_loaded', array( __CLASS__, 'load_wpcom_sites_features' ) );
92
93        // Load ETK features flag to turn off the features in the ETK plugin.
94        // It needs higher priority than the ETK plugin.
95        add_action( 'plugins_loaded', array( __CLASS__, 'load_etk_features_flags' ), 0 );
96
97        /*
98         * Please double-check whether you really need to load your feature separately.
99         * Chances are you can just add it to the `load_features` method.
100         */
101        add_action( 'plugins_loaded', array( __CLASS__, 'load_launchpad' ), 0 );
102        add_action( 'plugins_loaded', array( __CLASS__, 'load_coming_soon' ) );
103        add_action( 'plugins_loaded', array( __CLASS__, 'load_wpcom_rest_api_endpoints' ) );
104        add_action( 'plugins_loaded', array( __CLASS__, 'load_newspack_blocks' ) );
105
106        // At mu-plugin scope, because Comments::is_enabled() is resolved at plugins_loaded on both hosts.
107        add_filter( 'jetpack_comments_new_hotness', array( __CLASS__, 'enable_jetpack_comments_for_sticker' ) );
108
109        // These features run only on simple sites.
110        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
111            add_action( 'plugins_loaded', array( __CLASS__, 'load_wpcom_simple_jetpack_ai' ) );
112            add_action( 'plugins_loaded', array( __CLASS__, 'load_verbum_comments' ) );
113            add_action( 'plugins_loaded', array( __CLASS__, 'load_jetpack_comments_routes' ) );
114            add_action( 'plugins_loaded', array( __CLASS__, 'load_verbum_moderate' ) );
115            add_action( 'wp_loaded', array( __CLASS__, 'load_verbum_comments_admin' ) );
116            add_action( 'admin_menu', array( __CLASS__, 'load_wpcom_simple_odyssey_stats' ) );
117            add_action( 'plugins_loaded', array( __CLASS__, 'load_wpcom_random_redirect' ) );
118        }
119
120        // These features run only on atomic sites.
121        if ( defined( 'IS_ATOMIC' ) && IS_ATOMIC ) {
122            add_action( 'plugins_loaded', array( __CLASS__, 'load_custom_css' ) );
123            add_action( 'init', array( __CLASS__, 'schedule_translation_updates' ) );
124        }
125
126        // Premium Analytics offers the Ads tab wherever the plan includes WordAds, on Simple and Atomic.
127        add_action( 'plugins_loaded', array( __CLASS__, 'load_premium_analytics_wordads_section' ) );
128
129        // Unified navigation fix for changes in WordPress 6.2.
130        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'unbind_focusout_on_wp_admin_bar_menu_toggle' ) );
131
132        // Load the Map block settings.
133        add_action( 'enqueue_block_assets', array( __CLASS__, 'load_jetpack_mu_wpcom_settings' ), 999 );
134
135        // Load the Map block settings.
136        add_action( 'enqueue_block_assets', array( __CLASS__, 'load_map_block_settings' ), 999 );
137
138        // Load the Newsletter category settings.
139        add_action( 'enqueue_block_assets', array( __CLASS__, 'load_newsletter_categories_settings' ), 999 );
140
141        // Load the Social Links feature.
142        add_action( 'init', array( __CLASS__, 'load_social_links' ), 30 );
143
144        // Filter to ensure JetpackScriptData.site.host and is_wpcom_platform is set, to ensure Jetpack blocks work as expected via P2.
145        add_filter( 'jetpack_public_js_script_data', array( __CLASS__, 'add_jetpack_script_data_for_p2' ), 10, 1 );
146
147        // Filter to populate JetpackScriptData.site.wpcom.blog_id with the actual WP.com blog ID.
148        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'set_wpcom_blog_id_script_data' ), 10, 1 );
149
150        // Enable the `gutenberg-react-19` Gutenberg experiment on selected sites.
151        add_filter( 'option_gutenberg-experiments', array( __CLASS__, 'enable_gutenberg_react_19_experiment' ) );
152        add_filter( 'default_option_gutenberg-experiments', array( __CLASS__, 'enable_gutenberg_react_19_experiment' ) );
153
154        // Allow blog stickers to override the WooCommerce unified block editor assets option.
155        add_filter( 'option_woocommerce_feature_block_editor_unified_assets_enabled', array( __CLASS__, 'enable_woocommerce_block_editor_unified_assets' ) );
156        add_filter( 'default_option_woocommerce_feature_block_editor_unified_assets_enabled', array( __CLASS__, 'enable_woocommerce_block_editor_unified_assets' ) );
157
158        if ( wpcom_has_blog_sticker( 'gutenberg-extensible-site-editor', get_wpcom_blog_id() ) ) {
159            add_filter( 'option_gutenberg-experiments', array( __CLASS__, 'enable_extensible_site_editor_experiment' ) );
160
161            // Priority 20 because register_setting() hooks core's filter_default_option() at 10,
162            // and that callback discards the value it is handed and returns the registered default.
163            add_filter( 'default_option_gutenberg-experiments', array( __CLASS__, 'enable_extensible_site_editor_experiment' ), 20 );
164        }
165
166        /**
167         * Runs right after the Jetpack_Mu_Wpcom package is initialized.
168         *
169         * @since 0.1.2
170         */
171        do_action( 'jetpack_mu_wpcom_initialized' );
172    }
173
174    /**
175     * Load the Jetpack AI Hub integration on WordPress.com Simple sites.
176     */
177    public static function load_wpcom_simple_jetpack_ai() {
178        /**
179         * Filters whether WordPress.com Simple should register the Jetpack AI Hub.
180         *
181         * @since $$next-version$$
182         *
183         * @param bool $load Whether to load the AI Hub integration.
184         */
185        if ( ! apply_filters( 'jetpack_mu_wpcom_load_jetpack_ai_hub', false ) ) {
186            return;
187        }
188
189        require_once __DIR__ . '/features/jetpack-ai-hub/jetpack-ai-hub.php';
190    }
191
192    /**
193     * Schedules translation updates for Jetpack MU WPCOM.
194     *
195     * This function sets up the necessary cron jobs to ensure that translation files
196     * are regularly updated.
197     *
198     * @return void
199     */
200    public static function schedule_translation_updates() {
201        add_action( 'wpcomsh_translation_update', array( __CLASS__, 'maybe_update_translations' ) );
202
203        if ( ! wp_next_scheduled( 'wpcomsh_translation_update' ) ) {
204            wp_schedule_event( time(), 'twicedaily', 'wpcomsh_translation_update' );
205        }
206    }
207
208    /**
209     * Fetches and installs Jetpack-mu-wpcom package translations when needed.
210     */
211    public static function maybe_update_translations() {
212        global $wp_filesystem;
213        if ( ! $wp_filesystem ) {
214            require_once ABSPATH . 'wp-admin/includes/file.php';
215            WP_Filesystem();
216        }
217
218        $locales = self::get_all_active_locales();
219        if ( empty( $locales ) ) {
220            return;
221        }
222
223        $plugins_request_data              = array();
224        $plugin_language_pack_destinations = array(
225            'jetpack-mu-wpcom' => WP_LANG_DIR . '/mu-plugins/',
226            'wpcomsh'          => WP_LANG_DIR . '/mu-plugins/',
227        );
228
229        foreach ( array_keys( $plugin_language_pack_destinations ) as $plugin_slug ) {
230            $plugins_request_data[ $plugin_slug ] = array( 'version' => 'latest' );
231        }
232
233        $response = wp_remote_post(
234            'https://translate.wordpress.com/api/translations-updates/wpcom/plugins',
235            array(
236                'body'    => wp_json_encode(
237                    array(
238                        'locales' => $locales,
239                        'plugins' => $plugins_request_data,
240                    ),
241                    JSON_UNESCAPED_SLASHES
242                ),
243                'headers' => array( 'Content-Type' => 'application/json' ),
244                'timeout' => 10,
245            )
246        );
247
248        if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) {
249            return;
250        }
251
252        $data = json_decode( wp_remote_retrieve_body( $response ), true );
253
254        // API error, api returned but something was wrong.
255        if ( array_key_exists( 'success', $data ) && false === $data['success'] ) {
256            return;
257        }
258
259        if ( ! is_array( $data ) || ! is_array( $data['data'] ) ) {
260            return;
261        }
262
263        foreach ( $data['data'] as $plugin_name => $language_packs ) {
264            if ( ! isset( $plugin_language_pack_destinations[ $plugin_name ] ) ) {
265                continue;
266            }
267
268            $destination = $plugin_language_pack_destinations[ $plugin_name ];
269
270            foreach ( $language_packs as $translation ) {
271                $locale        = $translation['wp_locale'] ?? '';
272                $package_url   = $translation['package'] ?? '';
273                $last_modified = $translation['last_modified'] ?? '';
274
275                if ( ! $locale || ! $package_url || ! $last_modified ) {
276                    continue;
277                }
278
279                $local_po_file = "{$destination}/$plugin_name-{$locale}.po";
280                if ( file_exists( $local_po_file ) ) {
281                    $local_po_data                       = wp_get_pomo_file_data( $local_po_file );
282                    $installed_translation_revision_time = new \DateTime( $local_po_data['PO-Revision-Date'] );
283                    $new_translation_revision_time       = new \DateTime( $last_modified );
284
285                    // Skip if translation language pack is not newer than what is installed already.
286                    if ( $new_translation_revision_time <= $installed_translation_revision_time ) {
287                        continue;
288                    }
289                }
290
291                $translation_zip_file = download_url( $package_url );
292                if ( is_wp_error( $translation_zip_file ) ) {
293                    continue;
294                }
295
296                static::clear_translation_destination( $destination, $plugin_name, $locale );
297
298                $unzip_result = unzip_file( $translation_zip_file, $destination );
299                if ( is_wp_error( $unzip_result ) ) {
300                    wp_delete_file( $translation_zip_file );
301                    continue;
302                }
303
304                wp_delete_file( $translation_zip_file );
305
306            }
307        }
308    }
309
310    /**
311     * Clears the translation destination by deleting existing translation files.
312     *
313     * @param string $local_destination The local destination path.
314     * @param string $plugin_slug The plugin slug.
315     * @param string $locale The locale.
316     */
317    public static function clear_translation_destination( $local_destination, $plugin_slug, $locale ) {
318        global $wp_filesystem;
319
320        if ( ! $wp_filesystem ) {
321            require_once ABSPATH . 'wp-admin/includes/file.php';
322            WP_Filesystem();
323        }
324
325        $files = array(
326            "{$local_destination}{$plugin_slug}-{$locale}.po",
327            "{$local_destination}{$plugin_slug}-{$locale}.mo",
328            "{$local_destination}{$plugin_slug}-{$locale}.l10n.php",
329        );
330
331        $json_files = glob( "{$local_destination}{$plugin_slug}-{$locale}-*.json" );
332        if ( $json_files ) {
333            $files = array_merge( $files, $json_files );
334        }
335
336        foreach ( $files as $file ) {
337            if ( $wp_filesystem->exists( $file ) ) {
338                $wp_filesystem->delete( $file );
339            }
340        }
341    }
342
343    /**
344     * Retrieves all active locales for the site.
345     */
346    public static function get_all_active_locales() {
347        $locales = array( get_locale() );
348
349        $available_languages = get_available_languages();
350        if ( ! empty( $available_languages ) ) {
351            $locales = array_merge( $locales, $available_languages );
352        }
353        return array_values( array_unique( $locales ) );
354    }
355
356    /**
357     * Load features that don't need any special loading considerations.
358     */
359    public static function load_features() {
360        \Automattic\Jetpack\ExPlat::init();
361
362        // Please keep the features in alphabetical order.
363        require_once __DIR__ . '/features/100-year-plan/enhanced-ownership.php';
364        require_once __DIR__ . '/features/100-year-plan/locked-mode.php';
365        require_once __DIR__ . '/features/admin-color-schemes/admin-color-schemes.php';
366        require_once __DIR__ . '/features/ai-launchpad/ai-launchpad.php';
367        require_once __DIR__ . '/features/block-patterns/block-patterns.php';
368        require_once __DIR__ . '/features/blog-privacy/blog-privacy.php';
369        require_once __DIR__ . '/features/cloudflare-analytics/cloudflare-analytics.php';
370        require_once __DIR__ . '/features/code-editor/class-code-editor.php';
371        require_once __DIR__ . '/features/wpcom-blocks/code/class-code-block.php';
372        require_once __DIR__ . '/features/css-monkey-patches/index.php';
373        require_once __DIR__ . '/features/error-reporting/error-reporting.php';
374        require_once __DIR__ . '/features/first-posts-stream/first-posts-stream-helpers.php';
375        require_once __DIR__ . '/features/font-smoothing-antialiased/font-smoothing-antialiased.php';
376        require_once __DIR__ . '/features/google-analytics/google-analytics.php';
377        require_once __DIR__ . '/features/holiday-snow/class-holiday-snow.php';
378        require_once __DIR__ . '/features/launch-button/index.php';
379        require_once __DIR__ . '/features/layout-grid-usage-tracking/layout-grid-usage-tracking.php';
380        require_once __DIR__ . '/features/logo-tool/logo-tool.php';
381        require_once __DIR__ . '/features/marketplace-products-updater/class-marketplace-products-updater.php';
382        require_once __DIR__ . '/features/media/heif-support.php';
383        if ( Constants::is_true( 'IS_ATOMIC' ) ) {
384            require_once __DIR__ . '/features/plugin-conflicts-guardian/plugin-conflicts-guardian.php';
385        }
386        require_once __DIR__ . '/features/post-categories/quick-actions.php';
387        require_once __DIR__ . '/features/post-like-from-email/post-like-from-email.php';
388        require_once __DIR__ . '/features/podcast-feed-credit/podcast-feed-credit.php';
389        require_once __DIR__ . '/features/site-editor-dashboard-link/site-editor-dashboard-link.php';
390        require_once __DIR__ . '/features/wpcom-attachment-pages/wpcom-attachment-pages.php';
391        require_once __DIR__ . '/features/wpcom-block-editor/class-jetpack-wpcom-block-editor.php';
392        require_once __DIR__ . '/features/wpcom-block-editor/functions.editor-type.php';
393        require_once __DIR__ . '/features/wpcom-dashboard/class-wpcom-dashboard.php';
394        require_once __DIR__ . '/features/wpcom-logout/wpcom-logout.php';
395        require_once __DIR__ . '/features/wpcom-themes/wpcom-theme-fixes.php';
396        require_once __DIR__ . '/features/wpcom-post-list/wpcom-post-types-tracking.php';
397        require_once __DIR__ . '/features/wpcom-unified-admin-page-view/wpcom-unified-admin-page-view.php';
398        require_once __DIR__ . '/features/wpcom-widgets/wpcom-widgets.php';
399        require_once __DIR__ . '/features/wpcom-wpadmin-page-view/wpcom-wpadmin-page-view.php';
400
401        require_once __DIR__ . '/features/write/write.php';
402
403        /*
404         * Temporarily disable client-side media processing.
405         *
406         * Client-side media processing enables cross-origin isolation (COEP/COOP headers)
407         * which can break authenticated API requests. This should be removed once client-side
408         * media processing is compatible with Dotcom's infrastructure.
409         *
410         * @see gutenberg_set_up_cross_origin_isolation() in Gutenberg's lib/media/load.php
411         * @see https://a8c.slack.com/archives/CBTN58FTJ/p1771950744814189
412         */
413        add_filter( 'wp_client_side_media_processing_enabled', '__return_false' );
414
415        // Initializers, if needed.
416        $activity_log_event_class = 'Automattic\\Jetpack\\Sync\\Activity_Log_Event';
417        if ( class_exists( $activity_log_event_class ) ) {
418            $activity_log_event_class::init();
419        }
420
421        \Marketplace_Products_Updater::init();
422        \Automattic\Jetpack\Code_Editor::setup();
423        \Automattic\Jetpack\Code_Block::setup();
424        \Automattic\Jetpack\Classic_Theme_Helper\Main::init();
425        \Automattic\Jetpack\Classic_Theme_Helper\Featured_Content::setup();
426
427        \Automattic\Jetpack\Jetpack_Mu_Wpcom\AI_Launchpad::init();
428        \Automattic\Jetpack\Jetpack_Mu_Wpcom\Holiday_Snow::init();
429        \Automattic\Jetpack\Jetpack_Mu_Wpcom\Wpcom_Dashboard::init();
430
431        // The front-end Action Bar lives in the jetpack-newsletter package, which mu-wpcom does not
432        // composer-require; the class comes from the sibling Jetpack autoloader. Not in
433        // load_wpcom_user_features(): logged-out visitors are the bar's main audience.
434        if ( class_exists( '\Automattic\Jetpack\Newsletter\Action_Bar' ) ) {
435            // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by sibling autoloader.
436            \Automattic\Jetpack\Newsletter\Action_Bar::init();
437        }
438
439        // Gets autoloaded from the Scheduled_Updates package.
440        if ( class_exists( 'Automattic\Jetpack\Scheduled_Updates' ) ) {
441            Scheduled_Updates::init();
442        }
443    }
444
445    /**
446     * Load features that only apply to WordPress.com-connected users.
447     */
448    public static function load_wpcom_user_features() {
449        // To avoid potential collisions with ETK.
450        if ( ! class_exists( 'A8C\FSE\Help_Center' ) && class_exists( \Automattic\Jetpack\Help_Center\Help_Center::class ) ) {
451            add_action( 'init', array( \Automattic\Jetpack\Help_Center\Help_Center::class, 'init' ), 10, 0 );
452        }
453
454        // Every admin, not only WordPress.com users: one who cannot renew, such as
455        // the client of an agency-managed site, is told whose plan it is, and the
456        // legacy notice the feature replaces stands down only once this has loaded.
457        require_once __DIR__ . '/features/expiry-notices/expiry-notices.php';
458
459        if ( ! is_wpcom_user() ) {
460            require_once __DIR__ . '/features/replace-site-visibility/hide-site-visibility.php';
461            return;
462        }
463        if ( ! class_exists( 'A8C\FSE\Survicate' ) ) {
464            require_once __DIR__ . '/features/survicate/class-survicate.php';
465        }
466        require_once __DIR__ . '/features/ai-assistant-banner/ai-assistant-banner.php';
467        require_once __DIR__ . '/features/html-block-restricted-tags/html-block-restricted-tags.php';
468        require_once __DIR__ . '/features/pages/pages.php';
469        require_once __DIR__ . '/features/replace-site-visibility/replace-site-visibility.php';
470        require_once __DIR__ . '/features/stats/stats.php';
471        require_once __DIR__ . '/features/wpcom-admin-bar/wpcom-admin-bar.php';
472        require_once __DIR__ . '/features/wpcom-admin-interface/wpcom-admin-interface.php';
473        require_once __DIR__ . '/features/wpcom-admin-menu/wpcom-admin-menu.php';
474        require_once __DIR__ . '/features/wpcom-comments/wpcom-comments.php';
475        require_once __DIR__ . '/features/wpcom-dashboard-widgets/wpcom-dashboard-widgets.php';
476        require_once __DIR__ . '/features/wpcom-imports/wpcom-imports.php';
477        require_once __DIR__ . '/features/wpcom-locale/sync-locale-from-calypso-to-atomic.php';
478        require_once __DIR__ . '/features/wpcom-media/wpcom-media-url-upload.php';
479        require_once __DIR__ . '/features/wpcom-media/wpcom-export-media-files.php';
480        require_once __DIR__ . '/features/wpcom-options-general/options-general.php';
481        require_once __DIR__ . '/features/wpcom-plugins/wpcom-plugins.php';
482        require_once __DIR__ . '/features/wpcom-plugins/wpcom-marketplace-tab.php';
483        require_once __DIR__ . '/features/wpcom-profile-settings/profile-settings-link-to-wpcom.php';
484        require_once __DIR__ . '/features/wpcom-profile-settings/profile-settings-notices.php';
485        require_once __DIR__ . '/features/wpcom-sidebar-notice/wpcom-sidebar-notice.php';
486        require_once __DIR__ . '/features/wpcom-themes/wpcom-theme-tracking.php';
487        require_once __DIR__ . '/features/wpcom-themes/wpcom-themes.php';
488        require_once __DIR__ . '/features/wpcom-user-edit/wpcom-user-edit.php';
489        require_once __DIR__ . '/features/wpcom-videopress/wpcom-videopress.php';
490
491        // Initialize Newsletter Settings so hooks like the Reading page notice
492        // are registered on Simple sites (where load-jetpack.php doesn't run).
493        // Guarded with class_exists since mu-wpcom no longer composer-requires
494        // the jetpack-newsletter package: the class is provided by the standalone
495        // Jetpack plugin on Atomic, or by the wpcom platform's bundled Jetpack
496        // source on Simple.
497        if ( class_exists( '\Automattic\Jetpack\Newsletter\Settings' ) ) {
498            // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by sibling autoloader.
499            \Automattic\Jetpack\Newsletter\Settings::init();
500        }
501
502        // Register the Daily Writing Prompt dashboard widget, which now lives in
503        // the jetpack-newsletter package. Guarded with class_exists for the same
504        // reason as Settings above: mu-wpcom doesn't composer-require the package.
505        if ( class_exists( '\Automattic\Jetpack\Newsletter\Writing_Prompt_Widget' ) ) {
506            // @phan-suppress-next-line PhanUndeclaredClassMethod -- class_exists guarded above; provided by sibling autoloader.
507            \Automattic\Jetpack\Newsletter\Writing_Prompt_Widget::init();
508        }
509
510        // Only load the Masterbar features on WoA sites.
511        if ( class_exists( '\Automattic\Jetpack\Status\Host' ) && ( new \Automattic\Jetpack\Status\Host() )->is_woa_site() ) {
512            // This is temporary. After we cleanup Masterbar on WPCOM we should load Masterbar for Simple sites too.
513            \Automattic\Jetpack\Masterbar\Main::init();
514        }
515
516        if ( class_exists( 'Automattic\Jetpack\Agents_Manager\Agents_Manager' ) ) {
517            \Automattic\Jetpack\Agents_Manager\Agents_Manager::init();
518        }
519    }
520
521    /**
522     * Load features that only apply to WordPress.com sites, regardless of whether the users are connected.
523     */
524    public static function load_wpcom_sites_features() {
525        if ( is_fully_managed_agency_site() ) {
526            return;
527        }
528
529        require_once __DIR__ . '/features/gutenberg-rtc/gutenberg-rtc.php';
530        require_once __DIR__ . '/features/wpcom-contact-form-flags/wpcom-contact-form-flags.php';
531    }
532
533    /**
534     * Define the flags to turn off features in the ETK plugin.
535     * Can be removed once the feature no longer exists in the ETK plugin.
536     */
537    public static function load_etk_features_flags() {
538        // Don't load on agency sites.
539        if ( is_fully_managed_agency_site() ) {
540            return;
541        }
542
543        // Don't load if the user is not a wpcom user on WP Admin.
544        // The features is still required on the frontend page regardless of the user.
545        if ( is_admin() && ! is_wpcom_user() ) {
546            return;
547        }
548
549        define( 'MU_WPCOM_COBLOCKS_GALLERY', true );
550        define( 'MU_WPCOM_CUSTOM_LINE_HEIGHT', true );
551        define( 'MU_WPCOM_BLOCK_INSERTER_MODIFICATIONS', true );
552        define( 'MU_WPCOM_HOMEPAGE_TITLE_HIDDEN', true );
553        define( 'MU_WPCOM_JETPACK_GLOBAL_STYLES', true );
554        define( 'A8C_USE_FONT_SMOOTHING_ANTIALIASED', false );
555        define( 'MU_WPCOM_MAILERLITE_WIDGET', true );
556        define( 'MU_WPCOM_OVERRIDE_PREVIEW_BUTTON_URL', true );
557        define( 'MU_WPCOM_PARAGRAPH_BLOCK', true );
558        define( 'MU_WPCOM_STARTER_PAGE_TEMPLATES', true );
559        define( 'MU_WPCOM_TAGS_EDUCATION', true );
560        define( 'MU_WPCOM_BLOCK_DESCRIPTION_LINKS', true );
561        define( 'MU_WPCOM_BLOCK_EDITOR_NUX', true );
562        define( 'MU_WPCOM_POSTS_LIST_BLOCK', true );
563        define( 'MU_WPCOM_JETPACK_COUNTDOWN_BLOCK', true );
564        define( 'MU_WPCOM_JETPACK_TIMELINE_BLOCK', true );
565        define( 'MU_WPCOM_DOCUMENTATION_LINKS', true );
566        define( 'MU_WPCOM_GLOBAL_STYLES', true );
567        define( 'MU_WPCOM_FSE', true );
568        define( 'MU_WPCOM_TEMPLATE_INSERTER', true );
569        define( 'MU_WPCOM_WHATS_NEW', true );
570    }
571
572    /**
573     * Load ETK features.
574     * Can be moved back to load_features() once the feature no longer exists in the ETK plugin.
575     */
576    public static function load_etk_features() {
577        // Don't load on agency sites.
578        if ( is_fully_managed_agency_site() ) {
579            return;
580        }
581
582        // Don't load if the user is not a wpcom user on WP Admin.
583        // The features is still required on the frontend page regardless of the user.
584        if ( is_admin() && ! is_wpcom_user() ) {
585            return;
586        }
587
588        require_once __DIR__ . '/features/jetpack-global-styles/class-global-styles.php';
589        require_once __DIR__ . '/features/mailerlite/subscriber-popup.php';
590        require_once __DIR__ . '/features/wpcom-fse/wpcom-fse.php';
591
592        /**
593         * Load features for the editor and the frontend pages.
594         */
595        global $pagenow;
596        $allowed_pages = array( 'post.php', 'post-new.php', 'site-editor.php' );
597        if ( ( isset( $pagenow ) && in_array( $pagenow, $allowed_pages, true ) ) || ! is_admin() ) {
598            require_once __DIR__ . '/features/block-editor/custom-line-height.php';
599            require_once __DIR__ . '/features/block-inserter-modifications/block-inserter-modifications.php';
600            require_once __DIR__ . '/features/hide-homepage-title/hide-homepage-title.php';
601            require_once __DIR__ . '/features/override-preview-button-url/override-preview-button-url.php';
602            require_once __DIR__ . '/features/paragraph-block-placeholder/paragraph-block-placeholder.php';
603            require_once __DIR__ . '/features/tags-education/tags-education.php';
604            require_once __DIR__ . '/features/wpcom-block-description-links/wpcom-block-description-links.php';
605            require_once __DIR__ . '/features/wpcom-block-editor-nux/class-wpcom-block-editor-nux.php';
606            require_once __DIR__ . '/features/wpcom-blocks/a8c-posts-list/a8c-posts-list.php';
607            require_once __DIR__ . '/features/wpcom-blocks/event-countdown/event-countdown.php';
608            require_once __DIR__ . '/features/wpcom-blocks/timeline/timeline.php';
609            require_once __DIR__ . '/features/wpcom-documentation-links/wpcom-documentation-links.php';
610            require_once __DIR__ . '/features/wpcom-global-styles/index.php';
611            require_once __DIR__ . '/features/wpcom-legacy-fse/wpcom-legacy-fse.php';
612        } elseif ( isset( $pagenow ) && 'customize.php' === $pagenow ) {
613            // Load wpcom-global-styles on the customizer so access to additional css can be checked there.
614            require_once __DIR__ . '/features/wpcom-global-styles/index.php';
615        }
616    }
617
618    /**
619     * Load the newspack blocks feature for the editor and the frontend pages.
620     */
621    public static function load_newspack_blocks() {
622        /**
623         * Avoid potential collisions with newspack-blocks plugin.
624         */
625        if ( class_exists( '\Newspack_Blocks', false ) ) {
626            return;
627        }
628
629        global $pagenow;
630        $allowed_pages = array( 'post.php', 'post-new.php', 'site-editor.php' );
631        if ( ( isset( $pagenow ) && in_array( $pagenow, $allowed_pages, true ) ) || ! is_admin() ) {
632            define( 'MU_WPCOM_NEWSPACK_BLOCKS', true );
633            require_once __DIR__ . '/features/newspack-blocks/index.php';
634        }
635    }
636
637    /**
638     * Load the Coming Soon feature.
639     */
640    public static function load_coming_soon() {
641        /**
642         * On WoA sites, users may be using non-symlinked older versions of the FSE plugin.
643         * If they are, check the active version to avoid redeclaration errors.
644         */
645        if ( ! function_exists( 'is_plugin_active' ) ) {
646            require_once ABSPATH . 'wp-admin/includes/plugin.php';
647        }
648
649        /**
650         * Explicitly pass $markup = false in get_plugin_data to avoid indirectly calling wptexturize that could cause unintended side effects.
651         * See: https://developer.wordpress.org/reference/functions/get_plugin_data/
652         */
653        $fse_plugin                 = 'full-site-editing/full-site-editing-plugin.php';
654        $fse_plugin_path            = WP_PLUGIN_DIR . '/' . $fse_plugin;
655        $invalid_fse_version_active =
656            file_exists( $fse_plugin_path ) &&
657            is_file( $fse_plugin_path ) &&
658            is_plugin_active( $fse_plugin ) &&
659            version_compare( get_plugin_data( $fse_plugin_path, false )['Version'], '3.56084', '<' );
660
661        if ( $invalid_fse_version_active ) {
662            return;
663        }
664
665        if (
666            ( defined( 'WPCOM_PUBLIC_COMING_SOON' ) && WPCOM_PUBLIC_COMING_SOON ) ||
667            apply_filters( 'a8c_enable_public_coming_soon', false )
668        ) {
669            require_once __DIR__ . '/features/coming-soon/coming-soon.php';
670        }
671    }
672
673    /**
674     * Load the Launchpad feature.
675     */
676    public static function load_launchpad() {
677        require_once __DIR__ . '/features/launchpad/launchpad.php';
678    }
679
680    /**
681     * Load WP REST API plugins for wpcom.
682     */
683    public static function load_wpcom_rest_api_endpoints() {
684        if ( ! function_exists( 'wpcom_rest_api_v2_load_plugin' ) ) {
685            return;
686        }
687
688        // We don't use `wpcom_rest_api_v2_load_plugin_files` because it operates inconsisently.
689        $plugins = glob( __DIR__ . '/features/wpcom-endpoints/*.php' );
690
691        if ( ! is_array( $plugins ) ) {
692            return;
693        }
694
695        foreach ( array_filter( $plugins, 'is_file' ) as $plugin ) {
696            require_once $plugin;
697        }
698    }
699
700    /**
701     * Adds a global variable containing the config of the plugin to the window object.
702     */
703    public static function load_jetpack_mu_wpcom_settings() {
704        $handle = 'jetpack-mu-wpcom-settings';
705
706        // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter
707        wp_register_script(
708            $handle,
709            false,
710            array(),
711            true
712        );
713
714        $data = wp_json_encode(
715            array(
716                'assetsUrl' => plugins_url( 'build/', self::BASE_FILE ),
717            ),
718            JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
719        );
720
721        wp_add_inline_script(
722            $handle,
723            "var JETPACK_MU_WPCOM_SETTINGS = $data;",
724            'before'
725        );
726
727        wp_enqueue_script( $handle );
728    }
729
730    /**
731     * Adds a global variable containing the map provider in a map_block_settings object to the window object.
732     */
733    public static function load_map_block_settings() {
734        if (
735            ! function_exists( 'get_current_screen' )
736            || \get_current_screen() === null
737        ) {
738            return;
739        }
740
741        // Return early if we are not in the block editor.
742        if ( ! wp_should_load_block_editor_scripts_and_styles() ) {
743            return;
744        }
745
746        $map_provider = apply_filters( 'wpcom_map_block_map_provider', 'mapbox' );
747        wp_localize_script( 'jetpack-blocks-editor', 'Jetpack_Maps', array( 'provider' => $map_provider ) );
748    }
749
750    /**
751     * Adds a global variable containing where the newsletter categories should be shown.
752     */
753    public static function load_newsletter_categories_settings() {
754        if (
755            ! function_exists( 'get_current_screen' )
756            || \get_current_screen() === null
757        ) {
758            return;
759        }
760
761        // Return early if we are not in the block editor.
762        if ( ! wp_should_load_block_editor_scripts_and_styles() ) {
763            return;
764        }
765
766        $newsletter_categories_location = apply_filters( 'wpcom_newsletter_categories_location', 'block' );
767        wp_localize_script( 'jetpack-blocks-editor', 'Jetpack_Subscriptions', array( 'newsletter_categories_location' => $newsletter_categories_location ) );
768    }
769
770    /**
771     * Unbinds focusout event handler on #wp-admin-bar-menu-toggle introduced in WordPress 6.2.
772     *
773     * The focusout event handler is preventing the unified navigation from being closed on mobile.
774     */
775    public static function unbind_focusout_on_wp_admin_bar_menu_toggle() {
776        wp_add_inline_script( 'common', '(function($){ $(document).on("wp-responsive-activate", function(){ $(".is-nav-unification #wp-admin-bar-menu-toggle, .is-nav-unification #adminmenumain").off("focusout"); } ); }(jQuery) );' );
777    }
778
779    /**
780     * Determine whether to disable the comment experience.
781     *
782     * @param int $blog_id The blog ID.
783     * @return boolean
784     */
785    private static function should_disable_comment_experience( $blog_id ) {
786        $path_wp_for_teams = WP_CONTENT_DIR . '/lib/wpforteams/functions.php';
787
788        if ( file_exists( $path_wp_for_teams ) ) {
789            require_once $path_wp_for_teams;
790        }
791
792        // This covers both P2 and P2020 themes.
793        $is_p2     = str_contains( get_stylesheet(), 'pub/p2' ) || function_exists( '\WPForTeams\is_wpforteams_site' ) && is_wpforteams_site( $blog_id );
794        $is_forums = str_contains( get_stylesheet(), 'a8c/supportforums' ); // Not in /forums.
795
796        $verbum_option_enabled = get_blog_option( $blog_id, 'enable_verbum_commenting', true );
797
798        if ( empty( $verbum_option_enabled ) ) {
799            return true;
800        }
801
802        // Don't load any comment experience in the Reader, GlotPress, wp-admin, or P2.
803        return ( 1 === $blog_id || TRANSLATE_BLOG_ID === $blog_id || is_admin() || $is_p2 || $is_forums );
804    }
805
806    /**
807     * Load Verbum Comments.
808     */
809    public static function load_verbum_comments() {
810        if ( class_exists( 'Verbum_Comments' ) ) {
811            return;
812        } else {
813            $blog_id = get_current_blog_id();
814            // Jetpack loads Verbum though an iframe from jetpack.wordpress.com.
815            // So we need to check the GET request for the blogid.
816            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
817            if ( isset( $_GET['blogid'] ) ) {
818                $blog_id = intval( $_GET['blogid'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
819            }
820            if ( self::should_disable_comment_experience( $blog_id ) ) {
821                return;
822            }
823
824            if ( class_exists( '\Automattic\Jetpack\Comments\Comments' ) && \Automattic\Jetpack\Comments\Comments::is_enabled() ) {
825                \Automattic\Jetpack\Comments\Comments::init();
826                return;
827            }
828
829            require_once __DIR__ . '/features/verbum-comments/class-verbum-comments.php';
830            new \Automattic\Jetpack\Verbum_Comments();
831        }
832    }
833
834    /**
835     * Register Jetpack Comments' browser-facing routes ahead of the comment
836     * experience gates. admin-ajax is is_admin(), and a public-api request runs
837     * plugins_loaded on the wrong blog, so load_verbum_comments() skips both.
838     * Runs on every request, blog 1 and P2s included, on purpose: the routes
839     * gate themselves on the feature filter, as Posts_To_Podcast_Endpoint does.
840     */
841    public static function load_jetpack_comments_routes() {
842        if ( class_exists( '\Automattic\Jetpack\Comments\Checkpoint_Endpoint' ) ) {
843            \Automattic\Jetpack\Comments\Checkpoint_Endpoint::init();
844        }
845    }
846
847    /**
848     * Turn on the rebuilt Jetpack Comments form for a Simple or Atomic site
849     * carrying the rollout sticker.
850     *
851     * @since $$next-version$$
852     *
853     * @param bool $enabled Whether it is already on.
854     * @return bool
855     */
856    public static function enable_jetpack_comments_for_sticker( $enabled ) {
857        if ( $enabled ) {
858            return true;
859        }
860
861        $blog_id = (int) get_wpcom_blog_id();
862
863        return $blog_id > 0 && wpcom_has_blog_sticker( 'comment-new-hotness', $blog_id );
864    }
865
866    /**
867     * Load Verbum Comments Settings.
868     */
869    public static function load_verbum_comments_admin() {
870        require_once __DIR__ . '/features/verbum-comments/assets/class-verbum-admin.php';
871        new \Automattic\Jetpack\Verbum_Admin();
872    }
873
874    /**
875     * Load Verbum Moderate.
876     */
877    public static function load_verbum_moderate() {
878        require_once __DIR__ . '/features/verbum-comments/assets/class-verbum-moderate.php';
879        new \Automattic\Jetpack\Verbum_Moderate();
880    }
881
882    /**
883     * Load Odyssey Stats in Simple sites.
884     */
885    public static function load_wpcom_simple_odyssey_stats() {
886        require_once __DIR__ . '/features/wpcom-simple-odyssey-stats/wpcom-simple-odyssey-stats.php';
887    }
888
889    /**
890     * Register the Ads tab of the Premium Analytics dashboard by plan feature.
891     *
892     * Hooks the dashboard's registry action, which only fires once the package boots, so this
893     * is inert on a site without the dashboard.
894     *
895     * @since $$next-version$$
896     */
897    public static function load_premium_analytics_wordads_section() {
898        require_once __DIR__ . '/features/premium-analytics/wordads-section.php';
899    }
900
901    /**
902     * Load the Jetpack Custom CSS feature.
903     */
904    public static function load_custom_css() {
905        require_once __DIR__ . '/features/custom-css/custom-css/preprocessors.php';
906        require_once __DIR__ . '/features/custom-css/custom-css.php';
907    }
908
909    /**
910     * Load the Random Redirect feature.
911     */
912    public static function load_wpcom_random_redirect() {
913        require_once __DIR__ . '/features/random-redirect/random-redirect.php';
914    }
915
916    /**
917     * Load the Social Links feature.
918     */
919    public static function load_social_links() {
920        if ( class_exists( 'Automattic\Jetpack\Classic_Theme_Helper\Social_Links' ) ) {
921            new \Automattic\Jetpack\Classic_Theme_Helper\Social_Links();
922        }
923    }
924
925    /**
926     * Populate JetpackScriptData.site.wpcom.blog_id with the actual WP.com blog ID.
927     *
928     * @param array $data The script data.
929     * @return array
930     */
931    public static function set_wpcom_blog_id_script_data( $data ) {
932        $blog_id = get_wpcom_blog_id();
933        if ( $blog_id ) {
934            $data['site']['wpcom']['blog_id'] = $blog_id;
935        }
936        return $data;
937    }
938
939    /**
940     * Add `gutenberg-react-19` to the list of enabled Gutenberg experiments.
941     *
942     * The `disable-gutenberg-react-19` blog sticker force-disables the experiment,
943     * the `gutenberg-react-19` sticker opts the site in. With neither sticker,
944     * the experiment is enabled on a certain percentage of Atomic sites,
945     * known incompatible plugins and themes are excluded.
946     *
947     * @param mixed $experiments The current value of the gutenberg-experiments option.
948     * @return mixed Original option value or the filtered experiments.
949     */
950    public static function enable_gutenberg_react_19_experiment( $experiments ) {
951        if ( self::has_react_19_incompatible_gutenberg() ) {
952            return $experiments;
953        }
954
955        $blog_id = get_wpcom_blog_id();
956
957        if ( wpcom_has_blog_sticker( 'disable-gutenberg-react-19', $blog_id ) ) {
958            return $experiments;
959        }
960
961        $is_enabled = wpcom_has_blog_sticker( 'gutenberg-react-19', $blog_id );
962
963        if ( ! $is_enabled && function_exists( 'wpcomsh_get_atomic_site_id' ) ) {
964            $site_id = wpcomsh_get_atomic_site_id();
965
966            // Don't enable if the site ID is unknown (zero).
967            if ( ! $site_id ) {
968                $is_enabled = false;
969            } elseif ( self::has_react_19_incompatible_extension() ) {
970                $is_enabled = false;
971            } else {
972                $current_segment = 40; // Segment of Atomic sites in the experiment, in %.
973                $site_segment    = $site_id % 100;
974
975                /*
976                 * Sites whose Atomic site ID ends in digits < $current_segment are in the segment.
977                 * Must stay in sync with the error reporting rollout in wpcomsh
978                 * (wpcomsh_enable_error_reporting_for_react_19), so that every site in
979                 * the experiment also reports JS errors.
980                 */
981                $is_enabled = $site_segment < $current_segment;
982            }
983        }
984
985        if ( ! $is_enabled ) {
986            return $experiments;
987        }
988
989        if ( ! is_array( $experiments ) ) {
990            $experiments = array();
991        }
992
993        $experiments['gutenberg-react-19'] = true;
994        return $experiments;
995    }
996
997    /**
998     * Override the WooCommerce unified block editor assets option with blog stickers.
999     *
1000     * The `wc-disable-block-editor-unified-assets` blog sticker force-disables the feature,
1001     * while the `wc-block-editor-unified-assets` sticker opts the site in.
1002     *
1003     * @since $$next-version$$
1004     *
1005     * @param mixed $enabled The current feature option value.
1006     * @return mixed Original option value, `yes` when enabled, or `no` when force-disabled.
1007     */
1008    public static function enable_woocommerce_block_editor_unified_assets( $enabled ) {
1009        $blog_id = get_wpcom_blog_id();
1010
1011        if ( wpcom_has_blog_sticker( 'wc-disable-block-editor-unified-assets', $blog_id ) ) {
1012            return 'no';
1013        }
1014
1015        if ( wpcom_has_blog_sticker( 'wc-block-editor-unified-assets', $blog_id ) ) {
1016            return 'yes';
1017        }
1018
1019        // phpcs:disable Squiz.PHP.CommentedOutCode.Found,Squiz.Commenting.BlockComment.NoCapital -- Preserve the rollout for future activation.
1020
1021        /*
1022        if ( function_exists( 'wpcomsh_get_atomic_site_id' ) ) {
1023            $site_id = wpcomsh_get_atomic_site_id();
1024
1025            if ( $site_id ) {
1026                $current_segment = 1; // Segment of Atomic sites in the experiment, in %.
1027
1028                if ( $site_id % 100 < $current_segment ) {
1029                    return 'yes';
1030                }
1031            }
1032        }
1033        */
1034        // phpcs:enable
1035
1036        return $enabled;
1037    }
1038
1039    /**
1040     * Whether the site runs a Gutenberg plugin release that's known to break with React 19.
1041     *
1042     * Sites without the plugin run core's bundled Gutenberg, which the list doesn't cover.
1043     *
1044     * @return bool
1045     */
1046    private static function has_react_19_incompatible_gutenberg() {
1047        if ( ! defined( 'GUTENBERG_VERSION' ) ) {
1048            return false;
1049        }
1050
1051        // Match on the release number alone, so prereleases like 23.9.0-rc.1 count as 23.9.0.
1052        if ( ! preg_match( '/^(\d+(?:\.\d+)*)/', (string) GUTENBERG_VERSION, $matches ) ) {
1053            return false;
1054        }
1055
1056        return in_array( $matches[1], self::REACT_19_INCOMPATIBLE_GUTENBERG, true );
1057    }
1058
1059    /**
1060     * Add `gutenberg-extensible-site-editor` to the list of enabled Gutenberg experiments.
1061     *
1062     * Only registered on sites holding the sticker, so this does not re-check it.
1063     *
1064     * @param mixed $experiments The current value of the gutenberg-experiments option.
1065     * @return array The experiments, with the extensible site editor enabled.
1066     */
1067    public static function enable_extensible_site_editor_experiment( $experiments ) {
1068        if ( ! is_array( $experiments ) ) {
1069            $experiments = array();
1070        }
1071
1072        $experiments['gutenberg-extensible-site-editor'] = true;
1073        return $experiments;
1074    }
1075
1076    /**
1077     * Whether the site runs an extension that's known to break with React 19.
1078     *
1079     * @return bool
1080     */
1081    private static function has_react_19_incompatible_extension() {
1082        // Outside wp-admin the plugin check is unavailable, and the experiment isn't needed.
1083        if ( ! function_exists( 'is_plugin_active' ) ) {
1084            return true;
1085        }
1086
1087        $template = strtolower( get_template() );
1088        if ( array_key_exists( $template, self::REACT_19_INCOMPATIBLE_THEMES ) ) {
1089            $theme_version = (string) wp_get_theme( get_template() )->get( 'Version' );
1090
1091            if ( self::is_react_19_incompatible_version( $theme_version, self::REACT_19_INCOMPATIBLE_THEMES[ $template ] ) ) {
1092                return true;
1093            }
1094        }
1095
1096        foreach ( self::REACT_19_INCOMPATIBLE_PLUGINS as $plugin_file => $fixed_in ) {
1097            if ( ! is_plugin_active( $plugin_file ) ) {
1098                continue;
1099            }
1100
1101            $plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin_file, false, false );
1102
1103            if ( self::is_react_19_incompatible_version( (string) $plugin_data['Version'], $fixed_in ) ) {
1104                return true;
1105            }
1106        }
1107
1108        return false;
1109    }
1110
1111    /**
1112     * Whether an installed version predates the release that fixed its React 19 incompatibility.
1113     *
1114     * An unreadable version counts as incompatible, so a missing header can't opt a site in.
1115     *
1116     * @param string      $version  The installed version.
1117     * @param string|null $fixed_in The release that fixed the incompatibility, or null if there is none.
1118     * @return bool
1119     */
1120    private static function is_react_19_incompatible_version( $version, $fixed_in ) {
1121        if ( null === $fixed_in || '' === $version ) {
1122            return true;
1123        }
1124
1125        return version_compare( $version, $fixed_in, '<' );
1126    }
1127
1128    /**
1129     * Add Jetpack script data with host information on P2
1130     *
1131     * @param array $data - The Jetpack script data.
1132     * @return array - The modified Jetpack script data.
1133     */
1134    public static function add_jetpack_script_data_for_p2( $data ) {
1135        if (
1136        str_contains( get_stylesheet(), 'pub/p2' ) ||
1137        ( function_exists( '\WPForTeams\is_wpforteams_site' ) && is_wpforteams_site( get_current_blog_id() ) )
1138        ) {
1139            $host = new \Automattic\Jetpack\Status\Host();
1140            if ( ! isset( $data['site']['host'] ) ) {
1141                $data['site']['host'] = $host->get_known_host_guess();
1142            }
1143            if ( ! isset( $data['site']['is_wpcom_platform'] ) ) {
1144                $data['site']['is_wpcom_platform'] = $host->is_wpcom_platform();
1145            }
1146        }
1147        return $data;
1148    }
1149
1150    /**
1151     * Emit an event to the wpcom logstash cluster.
1152     *
1153     * Uses the in-process `log2logstash()` on WP.com Simple, and falls back to
1154     * the public-api `/rest/v1.1/logstash` endpoint (fire-and-forget) on
1155     * Atomic, where `log2logstash()` isn't available.
1156     *
1157     * Best-effort: a logging failure must never escalate into a fatal for the caller.
1158     *
1159     * @param string $feature Logstash `feature` bucket; should start with the `atomic_` prefix (e.g. "atomic_plugin_conflicts_guardian").
1160     * @param string $message Event message slug.
1161     * @param array  $extra   Event-specific properties; JSON-encoded into the `extra` field.
1162     * @return void
1163     */
1164    public static function log2logstash( $feature, $message, array $extra = array() ) {
1165        // Resolve the dispatch path once per request — on upgrade flows this
1166        // can be called several times in a row (one per plugin) and the path
1167        // doesn't change mid-request.
1168        static $dispatch = null;
1169        if ( null === $dispatch ) {
1170            try {
1171                if ( ! function_exists( 'log2logstash' ) ) {
1172                    $log2logstash_path = WP_CONTENT_DIR . '/lib/log2logstash/log2logstash.php';
1173                    if ( is_readable( $log2logstash_path ) ) {
1174                        require_once $log2logstash_path;
1175                    }
1176                }
1177            } catch ( \Throwable $e ) { // require_once can still throw (parse error / top-level fatal in the included file); fall through to the HTTP dispatch.
1178                unset( $e );
1179            }
1180            $dispatch = function_exists( 'log2logstash' ) ? 'native' : 'http';
1181        }
1182
1183        try {
1184            $payload = array(
1185                'blog_id' => self::resolve_logstash_blog_id(),
1186                'feature' => (string) $feature,
1187                'message' => (string) $message,
1188                'extra'   => wp_json_encode( $extra, JSON_UNESCAPED_SLASHES ),
1189            );
1190
1191            if ( 'native' === $dispatch ) {
1192                log2logstash( $payload );
1193                return;
1194            }
1195
1196            // Defer the HTTP POST to shutdown. Dispatching inline as a
1197            // non-blocking request loses the event when the caller `exit`s
1198            // or `wp_safe_redirect`s right after (e.g. the activation-guard
1199            // block path), because the cURL handle is torn down before the
1200            // TLS handshake completes. Draining at shutdown with a blocking
1201            // POST guarantees delivery without adding latency to the
1202            // user-visible response.
1203            self::queue_logstash_http( $payload );
1204        } catch ( \Throwable $e ) { // best-effort: a logging failure must never escalate into a fatal for the caller.
1205            unset( $e );
1206        }
1207    }
1208
1209    /**
1210     * Resolve the WP.com blog ID for a logstash record.
1211     *
1212     * `get_wpcom_blog_id()` falls back to `get_current_blog_id()` on Atomic
1213     * when `jetpack_options['id']` isn't readable — that returns `1` on a
1214     * single-site install, which is a valid-looking but wrong WP.com blog ID
1215     * and makes log records impossible to attribute. Emit `0` instead when
1216     * the real WP.com blog ID is unknown, so the gap is obvious in Kibana.
1217     *
1218     * @return int WP.com blog ID, or 0 when it can't be determined.
1219     */
1220    private static function resolve_logstash_blog_id() {
1221        // WP.com Simple: the current blog ID *is* the WP.com blog ID.
1222        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1223            return (int) get_current_blog_id();
1224        }
1225        // Atomic / connected Jetpack: the WP.com blog ID lives in the
1226        // `jetpack_options` option. Read it directly (no `Jetpack_Options`
1227        // dependency) and return 0 — never the local blog ID — when absent.
1228        $jetpack_options = get_option( 'jetpack_options' );
1229        if ( is_array( $jetpack_options ) && ! empty( $jetpack_options['id'] ) ) {
1230            return (int) $jetpack_options['id'];
1231        }
1232        return 0;
1233    }
1234
1235    /**
1236     * Append a logstash payload to the shutdown drain queue, registering
1237     * the drain hook on first enqueue. See `log2logstash()` for why
1238     * dispatch is deferred.
1239     *
1240     * @param array $payload Logstash record (`blog_id`, `feature`, `message`, `extra`).
1241     * @return void
1242     */
1243    private static function queue_logstash_http( array $payload ) {
1244        static $queue = null;
1245        if ( null === $queue ) {
1246            $queue = array();
1247            register_shutdown_function(
1248                static function () use ( &$queue ) {
1249                    foreach ( $queue as $entry ) {
1250                        try {
1251                            wp_remote_post(
1252                                'https://public-api.wordpress.com/rest/v1.1/logstash',
1253                                array(
1254                                    'body'    => array( 'params' => wp_json_encode( $entry, JSON_UNESCAPED_SLASHES ) ),
1255                                    'timeout' => 5,
1256                                )
1257                            );
1258                        } catch ( \Throwable $e ) { // best-effort: a logging failure must never escalate into a fatal at shutdown.
1259                            unset( $e );
1260                        }
1261                    }
1262                    $queue = array();
1263                }
1264            );
1265        }
1266        $queue[] = $payload;
1267    }
1268}