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