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