Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
54.26% covered (warning)
54.26%
306 / 564
40.43% covered (danger)
40.43%
19 / 47
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Gutenberg
54.74% covered (warning)
54.74%
306 / 559
40.43% covered (danger)
40.43%
19 / 47
5222.02
0.00% covered (danger)
0.00%
0 / 1
 is_gutenberg_version_available
87.50% covered (warning)
87.50%
21 / 24
0.00% covered (danger)
0.00%
0 / 1
8.12
 prepend_block_prefix
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 remove_extension_prefix
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 share_items
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 set_extension_available
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 set_extension_unavailable
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 init
n/a
0 / 0
n/a
0 / 0
1
 reset
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_blocks_directory
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 preset_exists
n/a
0 / 0
n/a
0 / 0
1
 get_preset
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
4.59
 get_jetpack_gutenberg_extensions_allowed_list
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_available_extensions
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 is_registered_and_no_entry_in_availability
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_cached_availability
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_availability
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
6
 get_extensions
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
4.25
 is_registered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_gutenberg_available
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 should_load
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 register_blocks_assets_base_url
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 load_assets_as_required
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
4.02
 load_styles_as_required
27.27% covered (danger)
27.27%
3 / 11
0.00% covered (danger)
0.00%
0 / 1
19.85
 load_scripts_as_required
31.82% covered (danger)
31.82%
7 / 22
0.00% covered (danger)
0.00%
0 / 1
28.29
 block_has_asset
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_asset_version
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 enqueue_block_editor_assets
0.00% covered (danger)
0.00%
0 / 103
0.00% covered (danger)
0.00%
0 / 1
380
 get_no_post_editor_extensions
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 load_independent_blocks
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
10
 lazy_register_deferred_block
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 register_deferred_blocks_in_subtree
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
14
 load_and_register_deferred_block
85.00% covered (warning)
85.00%
17 / 20
0.00% covered (danger)
0.00%
0 / 1
9.27
 warn_about_deferred_block_registration_failure
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
4.01
 is_block_editor_context
96.43% covered (success)
96.43%
27 / 28
0.00% covered (danger)
0.00%
0 / 1
14
 load_block_editor_extensions
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
7
 blocks_variation
88.00% covered (warning)
88.00%
22 / 25
0.00% covered (danger)
0.00%
0 / 1
9.14
 get_extensions_preset_for_variation
40.00% covered (danger)
40.00%
6 / 15
0.00% covered (danger)
0.00%
0 / 1
17.58
 validate_block_embed_url
95.83% covered (success)
95.83%
23 / 24
0.00% covered (danger)
0.00%
0 / 1
12
 should_show_frontend_preview
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 upgrade_nudge
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 notice
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
72
 get_site_specific_features
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 set_availability_for_plan
66.67% covered (warning)
66.67%
18 / 27
0.00% covered (danger)
0.00%
0 / 1
12.00
 get_render_callback_with_availability_check
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
56
 display_deprecated_block_message
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 register_block_metadata_collection
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
3.19
 set_block_js_loading_strategy
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_block_js_loading_strategy
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
1<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Handles server-side registration and use of all blocks and plugins available in Jetpack for the block editor, aka Gutenberg.
4 * Works in tandem with client-side block registration via `index.json`
5 *
6 * @package automattic/jetpack
7 */
8
9use Automattic\Jetpack\Assets;
10use Automattic\Jetpack\Blocks;
11use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
12use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13use Automattic\Jetpack\Constants;
14use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
15use Automattic\Jetpack\Modules;
16use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
17use Automattic\Jetpack\Status;
18use Automattic\Jetpack\Status\Host;
19
20if ( ! defined( 'ABSPATH' ) ) {
21    exit( 0 );
22}
23
24// Required directly so the AI master-gate helper is available regardless of
25// which loader pulled this class in.
26require_once __DIR__ . '/_inc/lib/class-jetpack-ai-settings.php';
27
28/**
29 * General Gutenberg editor specific functionality
30 */
31class Jetpack_Gutenberg {
32
33    /**
34     * Only these extensions can be registered. Used to control availability of beta blocks.
35     *
36     * @var array|null Extensions allowed list or `null` if not initialized yet.
37     * @see static::get_extensions()
38     */
39    private static $extensions = null;
40
41    /**
42     * Keeps track of the reasons why a given extension is unavailable.
43     *
44     * @var array Extensions availability information
45     */
46    private static $availability = array();
47
48    /**
49     * A cached array of the fully processed availability data. Keeps track of
50     * reasons why an extension is unavailable or missing.
51     *
52     * @var array Extensions availability information.
53     */
54    private static $cached_availability = null;
55
56    /**
57     * Site-specific features available.
58     * Their calculation can be expensive and slow, so we're caching it for the request.
59     *
60     * @var array Site-specific features
61     */
62    private static $site_specific_features = array();
63
64    /**
65     * List of deprecated blocks.
66     *
67     * @var array List of deprecated blocks.
68     */
69    private static $deprecated_blocks = array(
70        'jetpack/revue',
71    );
72
73    /**
74     * Display-only blocks whose registration PHP can be deferred until the block
75     * actually appears on a front-end page.
76     *
77     * Every block listed here has been verified to be "pure": the callback it hooks
78     * to `init` does nothing but call Blocks::jetpack_register_block() (plus trivial
79     * connection/module guards). It registers exactly one block type named
80     * `jetpack/<dir>` (matching its directory), and any front-end hooks it adds (asset
81     * enqueues, wp_footer, filters, â€¦) live inside its render callback, so they only
82     * run when the block is rendered.
83     *
84     * On plain front-end requests these blocks are NOT loaded on `init`. Instead they
85     * are registered just-in-time the first time the block (or a block whose subtree
86     * contains it) is encountered while rendering, via self::lazy_register_deferred_block()
87     * on `pre_render_block`. On admin/REST/cron/CLI/XML-RPC (block-editor) requests they
88     * keep loading eagerly so the editor, the block-types REST endpoint and server-side
89     * rendering are unaffected.
90     *
91     * One class of front-end request is NOT safe to defer on: front-end block editors
92     * (e.g. P2) render the inserter on a plain front-end page, so is_block_editor_context()
93     * is false, yet the block must be registered at `init` for get_availability() to report
94     * it as available. self::load_independent_blocks() therefore never defers a block that
95     * ships in the `no-post-editor` preset (extensions/index.json) â€” those are exactly the
96     * blocks available in editors other than the post editor. A block listed here that is
97     * also in `no-post-editor` simply keeps loading eagerly.
98     *
99     * A block must NOT be added here if:
100     *   - its `init` callback registers any other hook, post meta, REST route,
101     *     shortcode, block pattern or hooked-block;
102     *   - it registers more than one block type, or a block name that differs from its
103     *     directory name (e.g. videopress registers `jetpack/videopress-block`); or
104     *   - it uses `plan_check` (its availability is computed from the init-time
105     *     `jetpack_register_gutenberg_extensions` hook, which lazy registration bypasses,
106     *     so the front-end availability nudge/render could read a stale value); or
107     *   - a front-end path reads its entry from get_cached_availability() before the
108     *     block renders. Deferred blocks appear unavailable there until the lazy
109     *     registration callback runs; or
110     *   - its block file can be `require`d by another runtime code path after `init`
111     *     (e.g. slideshow is included by modules/shortcodes/slideshow.php). The lazy
112     *     loader registers a block by running the `init` callback its include adds; if
113     *     the file was already included elsewhere, the include is a no-op and the
114     *     callback would never run, so the block would silently fail to register; or
115     *   - another runtime code path calls a function defined in its block file
116     *     (e.g. button defines Button\render_email(), called by subscriptions and
117     *     memberships for WooCommerce e-mail rendering). Deferring the file would leave
118     *     that function undefined when the dependent path runs; or
119     *   - it registers a `render_email_callback`. That callback is read off the
120     *     registered block type by the WooCommerce e-mail editor â€” an out-of-band
121     *     renderer that does not go through `pre_render_block`/`do_blocks` â€” so the block
122     *     must already be registered when an e-mail containing it is rendered, which can
123     *     happen on a front-end request (e.g. a transactional e-mail sent during checkout).
124     *
125     * When in doubt, leave it out: omitted blocks simply keep their current eager
126     * behavior.
127     *
128     * @since 16.0
129     * @var string[] Block feature names (directory names, without the `jetpack/` prefix).
130     */
131    private static $lazy_blocks = array(
132        'blog-stats',
133        'blogging-prompt',
134        'business-hours',
135        'eventbrite',
136        'gif',
137        'goodreads',
138        'google-calendar',
139        'google-docs-embed',
140        'image-compare',
141        'like',
142        'markdown',
143        'nextdoor',
144        'payments-intro',
145        'pinterest',
146        'related-posts',
147        'repeat-visitor',
148        'sharing-buttons',
149        'story',
150        'tock',
151        'top-posts',
152        'voice-to-content',
153    );
154
155    /**
156     * Blocks that were deferred on the current request and still need to be
157     * registered just-in-time when first rendered. Keyed by block feature name.
158     *
159     * @since 16.0
160     * @var array<string,bool>
161     */
162    private static $deferred_blocks = array();
163
164    /**
165     * Fallback minimum plan requirements for WordPress.com/Atomic sites.
166     *
167     * Used when features have conditional availability (e.g., sticker-based gating)
168     * and don't appear in features_data['available']. This only affects the upsell
169     * message shown to users.
170     *
171     * @since 15.5
172     * @var array Feature slug => minimum WordPress.com plan slug.
173     */
174    private static $wpcom_minimum_plan_fallbacks = array(
175        'donations'              => 'value_bundle',
176        'payment-buttons'        => 'value_bundle',
177        'paypal-payment-buttons' => 'value_bundle',
178    );
179
180    /**
181     * Storing the contents of the preset file.
182     *
183     * Already been json_decode.
184     *
185     * @var null|object JSON decoded object after first usage.
186     */
187    private static $preset_cache = null;
188
189    /**
190     * Keep track of JS loading strategies for each block that needs it.
191     *
192     * @var array<string, array|bool>
193     *
194     * @since 15.0
195     */
196    private static $block_js_loading_strategies = array();
197
198    /**
199     * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
200     * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
201     * optionally fall back to that.
202     *
203     * @param array  $version_requirements An array containing the required Gutenberg version and, if known, the WordPress version that was released with this minimum version.
204     * @param string $slug The slug of the block or plugin that has the gutenberg version requirement.
205     *
206     * @since 8.3.0
207     *
208     * @return boolean True if the version of gutenberg required by the block or plugin is available.
209     */
210    public static function is_gutenberg_version_available( $version_requirements, $slug ) {
211        global $wp_version;
212
213        // Bail if we don't at least have the gutenberg version requirement, the WP version is optional.
214        if ( empty( $version_requirements['gutenberg'] ) ) {
215            return false;
216        }
217
218        // If running a local dev build of gutenberg plugin GUTENBERG_DEVELOPMENT_MODE is set so assume correct version.
219        if ( defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE ) {
220            return true;
221        }
222
223        $version_available = false;
224
225        // If running a production build of the gutenberg plugin then GUTENBERG_VERSION is set, otherwise if WP version
226        // with required version of Gutenberg is known check that.
227        if ( defined( 'GUTENBERG_VERSION' ) ) {
228            $version_available = version_compare( GUTENBERG_VERSION, $version_requirements['gutenberg'], '>=' );
229        } elseif ( ! empty( $version_requirements['wp'] ) ) {
230            $version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
231        }
232
233        if ( ! $version_available ) {
234            $slug = self::remove_extension_prefix( $slug );
235            self::set_extension_unavailable(
236                $slug,
237                'incorrect_gutenberg_version',
238                array(
239                    'required_feature' => $slug,
240                    'required_version' => $version_requirements,
241                    'current_version'  => array(
242                        'wp'        => $wp_version,
243                        'gutenberg' => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null,
244                    ),
245                )
246            );
247        }
248
249        return $version_available;
250    }
251
252    /**
253     * Prepend the 'jetpack/' prefix to a block name
254     *
255     * @param string $block_name The block name.
256     *
257     * @return string The prefixed block name.
258     */
259    private static function prepend_block_prefix( $block_name ) {
260        return 'jetpack/' . $block_name;
261    }
262
263    /**
264     * Remove the 'jetpack/' or jetpack-' prefix from an extension name
265     *
266     * @param string $extension_name The extension name.
267     *
268     * @return string The unprefixed extension name.
269     */
270    public static function remove_extension_prefix( $extension_name ) {
271        if ( str_starts_with( $extension_name, 'jetpack/' ) || str_starts_with( $extension_name, 'jetpack-' ) ) {
272            return substr( $extension_name, strlen( 'jetpack/' ) );
273        }
274        return $extension_name;
275    }
276
277    /**
278     * Whether two arrays share at least one item
279     *
280     * @param array $a An array.
281     * @param array $b Another array.
282     *
283     * @return boolean True if $a and $b share at least one item
284     */
285    protected static function share_items( $a, $b ) {
286        return array_intersect( $a, $b ) !== array();
287    }
288
289    /**
290     * Set a (non-block) extension as available
291     *
292     * @param string $slug Slug of the extension.
293     */
294    public static function set_extension_available( $slug ) {
295        $slug                        = self::remove_extension_prefix( $slug );
296        self::$availability[ $slug ] = true;
297    }
298
299    /**
300     * Set the reason why an extension (block or plugin) is unavailable
301     *
302     * @param string $slug Slug of the extension.
303     * @param string $reason A string representation of why the extension is unavailable.
304     * @param array  $details A free-form array containing more information on why the extension is unavailable.
305     */
306    public static function set_extension_unavailable( $slug, $reason, $details = array() ) {
307        if (
308            // Extensions that require a plan may be eligible for upgrades.
309            'missing_plan' === $reason
310            && (
311                /**
312                 * Filter 'jetpack_block_editor_enable_upgrade_nudge' with `true` to enable or `false`
313                 * to disable paid feature upgrade nudges in the block editor.
314                 *
315                 * When this is changed to default to `true`, you should also update `modules/memberships/class-jetpack-memberships.php`
316                 * See https://github.com/Automattic/jetpack/pull/13394#pullrequestreview-293063378
317                 *
318                 * @since 7.7.0
319                 *
320                 * @param boolean
321                 */
322                ! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
323                /** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
324                || ! apply_filters( 'jetpack_show_promotions', true )
325            )
326        ) {
327            // The block editor may apply an upgrade nudge if `missing_plan` is the reason.
328            // Add a descriptive suffix to disable behavior but provide informative reason.
329            $reason .= '__nudge_disabled';
330        }
331        $slug                        = self::remove_extension_prefix( $slug );
332        self::$availability[ $slug ] = array(
333            'reason'  => $reason,
334            'details' => $details,
335        );
336    }
337
338    /**
339     * Used to initialize the class, no longer in use.
340     *
341     * @return void
342     * @deprecated 12.2 No longer needed.
343     */
344    public static function init() {
345        _deprecated_function( __METHOD__, '12.2' );
346    }
347
348    /**
349     * Resets the class to its original state
350     *
351     * Used in unit tests
352     *
353     * @return void
354     */
355    public static function reset() {
356        self::$extensions                  = null;
357        self::$availability                = array();
358        self::$cached_availability         = null;
359        self::$block_js_loading_strategies = array();
360        self::$deferred_blocks             = array();
361    }
362
363    /**
364     * Return the Gutenberg extensions (blocks and plugins) directory
365     *
366     * @return string The Gutenberg extensions directory
367     */
368    public static function get_blocks_directory() {
369        /**
370         * Filter to select Gutenberg blocks directory
371         *
372         * @since 6.9.0
373         *
374         * @param string default: '_inc/blocks/'
375         */
376        return apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
377    }
378
379    /**
380     * Checks for a given .json file in the blocks folder.
381     *
382     * @deprecated 14.3
383     *
384     * @param string $preset The name of the .json file to look for.
385     *
386     * @return bool True if the file is found.
387     */
388    public static function preset_exists( $preset ) {
389        _deprecated_function( __METHOD__, '14.3' );
390        return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
391    }
392
393    /**
394     * Decodes JSON loaded from the preset file in the blocks folder
395     *
396     * @since 14.3 Deprecated argument. Only one value is ever used.
397     *
398     * @param null $deprecated No longer used.
399     *
400     * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
401     */
402    public static function get_preset( $deprecated = null ) {
403        if ( $deprecated ) {
404            _deprecated_argument( __METHOD__, '14.3', 'The $preset argument is no longer needed or used.' );
405        }
406
407        if ( self::$preset_cache ) {
408            return self::$preset_cache;
409        }
410
411        /*
412         * The manifest is a build artifact and is absent in a source checkout (e.g. when
413         * running the test suite). Return false â€” as documented â€” rather than calling
414         * wp_json_file_decode() on a missing file, which triggers _doing_it_wrong().
415         */
416        $preset_file = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . 'index.json';
417        if ( ! file_exists( $preset_file ) ) {
418            return false;
419        }
420
421        self::$preset_cache = wp_json_file_decode( $preset_file );
422        return self::$preset_cache;
423    }
424
425    /**
426     * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
427     *
428     * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
429     */
430    public static function get_jetpack_gutenberg_extensions_allowed_list() {
431        $preset_extensions_manifest = ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) ? array() : self::get_preset();
432        $blocks_variation           = self::blocks_variation();
433
434        return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
435    }
436
437    /**
438     * Returns a diff from a combined list of allowed extensions and extensions determined to be excluded
439     *
440     * @param  array $allowed_extensions An array of allowed extensions.
441     *
442     * @return array A list of blocks: eg array( 'publicize', 'markdown' )
443     */
444    public static function get_available_extensions( $allowed_extensions = null ) {
445        $exclusions         = get_option( 'jetpack_excluded_extensions', array() );
446        $allowed_extensions = $allowed_extensions === null ? self::get_jetpack_gutenberg_extensions_allowed_list() : $allowed_extensions;
447
448        // Avoid errors if option data is not as expected.
449        if ( ! is_array( $exclusions ) ) {
450            $exclusions = array();
451        }
452
453        return array_diff( $allowed_extensions, $exclusions );
454    }
455
456    /**
457     * Return true if the extension has been registered and there's nothing in the availablilty array.
458     *
459     * @param string $extension The name of the extension.
460     *
461     * @return bool whether the extension has been registered and there's nothing in the availablilty array.
462     */
463    public static function is_registered_and_no_entry_in_availability( $extension ) {
464        return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
465    }
466
467    /**
468     * Return true if the extension has a true entry in the availablilty array.
469     *
470     * @param string $extension The name of the extension.
471     *
472     * @return bool whether the extension has a true entry in the availablilty array.
473     */
474    public static function is_available( $extension ) {
475        return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
476    }
477
478    /**
479     * Get the availability of each block / plugin, or return the cached availability
480     * if it has already been calculated. Avoids re-registering extensions when not
481     * necessary.
482     *
483     * @return array A list of block and plugins and their availability status.
484     */
485    public static function get_cached_availability() {
486        if ( null === self::$cached_availability ) {
487            self::$cached_availability = self::get_availability();
488        }
489        return self::$cached_availability;
490    }
491
492    /**
493     * Get availability of each block / plugin.
494     *
495     * @return array A list of block and plugins and their availablity status
496     */
497    public static function get_availability() {
498        /**
499         * Fires before Gutenberg extensions availability is computed.
500         *
501         * In the function call you supply, use `Blocks::jetpack_register_block()` to set a block as available.
502         * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
503         * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
504         * but marked as unavailable).
505         *
506         * @since 7.0.0
507         */
508        do_action( 'jetpack_register_gutenberg_extensions' );
509
510        $available_extensions = array();
511
512        foreach ( static::get_extensions() as $extension ) {
513            $is_available                       = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
514            $available_extensions[ $extension ] = array(
515                'available' => $is_available,
516            );
517
518            if ( ! $is_available ) {
519                $reason  = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
520                $details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
521                $available_extensions[ $extension ]['unavailable_reason'] = $reason;
522                $available_extensions[ $extension ]['details']            = $details;
523            }
524        }
525
526        return $available_extensions;
527    }
528
529    /**
530     * Return the list of extensions that are available.
531     *
532     * @since 11.9
533     *
534     * @return array A list of block and plugins and their availability status.
535     */
536    public static function get_extensions() {
537        if ( ! static::should_load() ) {
538            return array();
539        }
540
541        if ( null === self::$extensions ) {
542            /**
543             * Filter the list of block editor extensions that are available through Jetpack.
544             *
545             * @since 7.0.0
546             *
547             * @param array
548             */
549            self::$extensions = apply_filters( 'jetpack_set_available_extensions', self::get_available_extensions() );
550
551            if ( ! is_array( self::$extensions ) ) {
552                _doing_it_wrong( __METHOD__, esc_html__( 'The jetpack_set_available_extensions filter must return an array.', 'jetpack' ), '14.9' );
553                self::$extensions = array();
554            }
555        }
556
557        return self::$extensions;
558    }
559
560    /**
561     * Check if an extension/block is already registered
562     *
563     * @since 7.2
564     *
565     * @param string $slug Name of extension/block to check.
566     *
567     * @return bool
568     */
569    public static function is_registered( $slug ) {
570        return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
571    }
572
573    /**
574     * Check if Gutenberg editor is available
575     *
576     * @since 6.7.0
577     *
578     * @return bool
579     */
580    public static function is_gutenberg_available() {
581        return true;
582    }
583
584    /**
585     * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
586     *
587     * Loading blocks and plugins is enabled by default and may be disabled via filter:
588     *   add_filter( 'jetpack_gutenberg', '__return_false' );
589     *
590     * @since 6.9.0
591     *
592     * @return bool
593     */
594    public static function should_load() {
595        if ( ! Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
596            return false;
597        }
598
599        $return = true;
600
601        if ( ! ( new Modules() )->is_active( 'blocks' ) ) {
602            $return = false;
603        }
604
605        /**
606         * Filter to enable Gutenberg blocks.
607         *
608         * Defaults to true if (connected or in offline mode) and the Blocks module is active.
609         *
610         * @since 6.5.0
611         * @since 13.9 Filter is able to activate or deactivate Gutenberg blocks.
612         *
613         * @param bool true Whether to load Gutenberg blocks
614         */
615        return (bool) apply_filters( 'jetpack_gutenberg', $return );
616    }
617
618    /**
619     * Queue a script to set `Jetpack_Block_Assets_Base_Url`.
620     *
621     * In certain cases Webpack needs to know a base to load additional assets from.
622     * Normally it can determine that itself, but when JS concatenation is involved that tends to confuse it.
623     * We work around that by explicitly outputting a variable with the correct URL.
624     * We set that as its own "script" so we can reliably only output it once.
625     */
626    private static function register_blocks_assets_base_url() {
627        if ( ! wp_script_is( 'jetpack-blocks-assets-base-url', 'registered' ) ) {
628            // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- No actual script, so no version needed.
629            wp_register_script( 'jetpack-blocks-assets-base-url', false, array(), null, array( 'in_footer' => false ) );
630            $json_encode_flags = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP;
631            if ( get_option( 'blog_charset' ) === 'UTF-8' ) {
632                $json_encode_flags |= JSON_UNESCAPED_UNICODE;
633            }
634            wp_add_inline_script(
635                'jetpack-blocks-assets-base-url',
636                'var Jetpack_Block_Assets_Base_Url=' . wp_json_encode( plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE ), $json_encode_flags ) . ';',
637                'before'
638            );
639        }
640    }
641
642    /**
643     * Only enqueue block assets when needed.
644     *
645     * @param string $type Slug of the block or absolute path to the block source code directory.
646     * @param array  $script_dependencies Script dependencies. Will be merged with automatically
647     *                                    detected script dependencies from the webpack build.
648     *
649     * @return void
650     */
651    public static function load_assets_as_required( $type, $script_dependencies = array() ) {
652        if ( is_admin() ) {
653            // A block's view assets will not be required in wp-admin.
654            return;
655        }
656
657        // Retrieve the feature from block.json if a path is passed.
658        if ( path_is_absolute( $type ) ) {
659            $metadata = Blocks::get_block_metadata_from_file( Blocks::get_path_to_block_metadata( $type ) );
660            $feature  = Blocks::get_block_feature_from_metadata( $metadata );
661
662            if ( ! empty( $feature ) ) {
663                $type = $feature;
664            }
665        }
666
667        $type = sanitize_title_with_dashes( $type );
668        self::load_styles_as_required( $type );
669        self::load_scripts_as_required( $type, $script_dependencies );
670    }
671
672    /**
673     * Only enqueue block sytles when needed.
674     *
675     * @param string $type Slug of the block.
676     *
677     * @since 7.2.0
678     *
679     * @return void
680     */
681    public static function load_styles_as_required( $type ) {
682        if ( is_admin() ) {
683            // A block's view assets will not be required in wp-admin.
684            return;
685        }
686
687        // Enqueue styles.
688        $style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
689        if ( self::block_has_asset( $style_relative_path ) ) {
690            $style_version = self::get_asset_version( $style_relative_path );
691            $view_style    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
692            $view_style    = add_query_arg( 'minify', 'false', $view_style );
693
694            // If this is a customizer preview, render the style directly to the preview after autosave.
695            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
696            if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
697                // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
698                echo '<link rel="stylesheet" id="jetpack-block-' . esc_attr( $type ) . '" href="' . esc_attr( $view_style ) . '&amp;ver=' . esc_attr( $style_version ) . '" media="all">';
699            } else {
700                wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
701                wp_style_add_data( 'jetpack-block-' . $type, 'path', JETPACK__PLUGIN_DIR . $style_relative_path );
702            }
703        }
704    }
705
706    /**
707     * Only enqueue block scripts when needed.
708     *
709     * @param string $type Slug of the block.
710     * @param array  $script_dependencies Script dependencies. Will be merged with automatically
711     *                             detected script dependencies from the webpack build.
712     *
713     * @since 7.2.0
714     *
715     * @return void
716     */
717    public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
718        if ( is_admin() ) {
719            // A block's view assets will not be required in wp-admin.
720            return;
721        }
722
723        self::register_blocks_assets_base_url();
724
725        // Enqueue script.
726        $script_relative_path  = self::get_blocks_directory() . $type . '/view.js';
727        $script_deps_path      = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
728        $script_dependencies[] = 'jetpack-blocks-assets-base-url';
729        if ( file_exists( $script_deps_path ) ) {
730            $asset_manifest      = include $script_deps_path;
731            $script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
732        }
733
734        if ( ! Blocks::is_amp_request() && self::block_has_asset( $script_relative_path ) ) {
735            $script_version = self::get_asset_version( $script_relative_path );
736            $view_script    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
737            $view_script    = add_query_arg( 'minify', 'false', $view_script );
738            $strategy       = self::get_block_js_loading_strategy( $type );
739
740            // Enqueue dependencies.
741            wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, $strategy );
742
743            // If this is a customizer preview, enqueue the dependencies and render the script directly to the preview after autosave.
744            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
745            if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
746                // The Map block is dependent on wp-element, and it doesn't appear to to be possible to load
747                // this dynamically into the customizer iframe currently.
748                if ( 'map' === $type ) {
749                    echo '<div>' . esc_html__( 'No map preview available. Publish and refresh to see this widget.', 'jetpack' ) . '</div>';
750                    echo '<script>';
751                    echo 'Array.from(document.getElementsByClassName(\'wp-block-jetpack-map\')).forEach(function(element){element.style.display = \'none\';})';
752                    echo '</script>';
753                } else {
754                    echo '<script id="jetpack-block-' . esc_attr( $type ) . '" src="' . esc_attr( $view_script ) . '&amp;ver=' . esc_attr( $script_version ) . '"></script>';
755                }
756            }
757        }
758    }
759
760    /**
761     * Check if an asset exists for a block.
762     *
763     * @param string $file Path of the file we are looking for.
764     *
765     * @return bool $block_has_asset Does the file exist.
766     */
767    public static function block_has_asset( $file ) {
768        return file_exists( JETPACK__PLUGIN_DIR . $file );
769    }
770
771    /**
772     * Get the version number to use when loading the file. Allows us to bypass cache when developing.
773     *
774     * @param string $file Path of the file we are looking for.
775     *
776     * @return string $script_version Version number.
777     */
778    public static function get_asset_version( $file ) {
779        return Jetpack::is_development_version() && self::block_has_asset( $file )
780            ? filemtime( JETPACK__PLUGIN_DIR . $file )
781            : JETPACK__VERSION;
782    }
783
784    /**
785     * Load Gutenberg editor assets
786     *
787     * @since 6.7.0
788     *
789     * @return void
790     */
791    public static function enqueue_block_editor_assets() {
792        if ( ! self::should_load() ) {
793            return;
794        }
795
796        /*
797         * When the user returns to the editor right after a successful plan
798         * purchase (signalled by the `plan_upgraded` redirect argument), refresh
799         * the locally cached plan from WordPress.com before block availability is
800         * computed below. Otherwise `available_blocks` is derived from the stale
801         * `jetpack_active_plan` option (only refreshed by the daily heartbeat) and
802         * paid blocks keep showing their upgrade nudge even though the plan is now
803         * active. Simple sites gate features live via `wpcom_site_has_feature()`,
804         * so they neither need nor benefit from this.
805         *
806         * The refresh is a blocking WordPress.com request, so it is guarded to run
807         * only on a connected, non-WPCOM site, throttled to once per minute (a
808         * repeated or bookmarked `?plan_upgraded` URL cannot trigger a request on
809         * every load), and time-boxed so a slow origin cannot hang the editor. The
810         * client-side reload fallback covers a skipped or failed refresh. The value
811         * is only used to trigger a cache refresh from an authoritative source, so
812         * no nonce is required. See FORMS-712.
813         */
814        if (
815            ! empty( $_GET['plan_upgraded'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
816            && ! ( defined( 'IS_WPCOM' ) && IS_WPCOM )
817            && Jetpack::is_connection_ready()
818            && ! get_transient( 'jetpack_plan_upgraded_refresh' )
819        ) {
820            set_transient( 'jetpack_plan_upgraded_refresh', 1, MINUTE_IN_SECONDS );
821
822            $cap_plan_refresh_timeout = static function () {
823                return 5;
824            };
825            add_filter( 'http_request_timeout', $cap_plan_refresh_timeout, PHP_INT_MAX );
826            Jetpack_Plan::refresh_from_wpcom();
827            remove_filter( 'http_request_timeout', $cap_plan_refresh_timeout, PHP_INT_MAX );
828        }
829
830        $status = new Status();
831
832        // Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
833        if ( ! $status->is_offline_mode() && Jetpack::is_connection_ready() ) {
834            wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
835        }
836
837        $blocks_dir       = self::get_blocks_directory();
838        $blocks_variation = self::blocks_variation();
839
840        if ( 'production' !== $blocks_variation ) {
841            $blocks_env = '-' . esc_attr( $blocks_variation );
842        } else {
843            $blocks_env = '';
844        }
845
846        self::register_blocks_assets_base_url();
847
848        Assets::register_script(
849            'jetpack-blocks-editor',
850            "{$blocks_dir}editor{$blocks_env}.js",
851            JETPACK__PLUGIN_FILE,
852            array(
853                'textdomain'   => 'jetpack',
854                'dependencies' => array( 'jetpack-blocks-assets-base-url' ),
855            )
856        );
857
858        /**
859         * This can be called multiple times per page load in the admin, during the `enqueue_block_assets` action.
860         * These assets are necessary for the admin for editing but are not necessary for each pattern preview.
861         * Therefore we dequeue them, so they don't load for each pattern preview iframe.
862         */
863        if ( ! wp_should_load_block_editor_scripts_and_styles() ) {
864            wp_dequeue_script( 'jp-tracks' );
865            wp_dequeue_script( 'jetpack-blocks-editor' );
866
867            return;
868        }
869
870        // Hack around #20357 (specifically, that the editor bundle depends on
871        // wp-edit-post but wp-edit-post's styles break the Widget Editor and
872        // Site Editor) until a real fix gets unblocked.
873        // @todo Remove this once #20357 is properly fixed.
874        $wp_styles_fix = wp_styles()->query( 'jetpack-blocks-editor', 'registered' );
875        if ( empty( $wp_styles_fix ) ) {
876            wp_die( 'Your installation of Jetpack is incomplete. Please run "jetpack build plugins/jetpack" in your dev env.' );
877        }
878        wp_styles()->query( 'jetpack-blocks-editor', 'registered' )->deps = array();
879
880        Assets::enqueue_script( 'jetpack-blocks-editor' );
881
882        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
883            $user                      = wp_get_current_user();
884            $user_data                 = array(
885                'email'    => $user->user_email,
886                'userid'   => $user->ID,
887                'username' => $user->user_login,
888            );
889            $blog_id                   = get_current_blog_id();
890            $is_current_user_connected = true;
891        } else {
892            $user_data                 = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
893            $blog_id                   = Jetpack_Options::get_option( 'id', 0 );
894            $is_current_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected();
895        }
896
897        if ( $blocks_variation === 'beta' && $is_current_user_connected ) {
898            wp_enqueue_style( 'recoleta-font', '//s1.wp.com/i/fonts/recoleta/css/400.min.css', array(), Constants::get_constant( 'JETPACK__VERSION' ) );
899        }
900        // AI Assistant
901        $ai_assistant_state = array(
902            'is-enabled'     => Jetpack_AI_Settings::is_ai_enabled(),
903            'is-seo-enabled' => Jetpack_AI_Settings::is_ai_seo_enabled(),
904        );
905
906        $screen_base = null;
907        if ( function_exists( 'get_current_screen' ) ) {
908            $current_screen = get_current_screen();
909            $screen_base    = $current_screen ? $current_screen->base : null;
910        }
911
912        $modules = array();
913        if ( class_exists( 'Jetpack_Core_API_Module_List_Endpoint' ) ) {
914            $module_list_endpoint = new Jetpack_Core_API_Module_List_Endpoint();
915            $modules              = $module_list_endpoint->get_modules();
916        }
917
918        $jetpack_plan  = Jetpack_Plan::get();
919        $initial_state = array(
920            'available_blocks' => self::get_availability(),
921            'blocks_variation' => $blocks_variation,
922            'modules'          => $modules,
923            'jetpack'          => array(
924                'is_active'                     => Jetpack::is_connection_ready(),
925                'is_current_user_connected'     => $is_current_user_connected,
926                /** This filter is documented in class.jetpack-gutenberg.php */
927                'enable_upgrade_nudge'          => apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ),
928                'is_private_site'               => $status->is_private_site(),
929                'is_coming_soon'                => $status->is_coming_soon(),
930                'is_offline_mode'               => $status->is_offline_mode(),
931                'is_newsletter_feature_enabled' => class_exists( '\Jetpack_Memberships' ),
932                // Whether the current user may send a newsletter test email to an
933                // address other than their own. The wpcom guard enforces this on send
934                // (also checking add_users and site stickers); this flag only controls
935                // whether the editor's recipient field is editable. Approximated with
936                // manage_options so editors, who can only test-send to themselves,
937                // aren't shown an editable field that would always be rejected.
938                'can_send_test_email_to_others' => current_user_can( 'manage_options' ),
939                // this is the equivalent of JP initial state siteData.showMyJetpack (class-jetpack-redux-state-helper)
940                // used to determine if we can link to My Jetpack from the block editor
941                'is_my_jetpack_available'       => My_Jetpack_Initializer::should_initialize(),
942                'jetpack_plan'                  => array(
943                    'data' => $jetpack_plan['product_slug'],
944                ),
945                /**
946                 * Enable the RePublicize UI in the block editor context.
947                 *
948                 * @module publicize
949                 *
950                 * @since 10.3.0
951                 * @deprecated 11.5 This is a feature flag that is no longer used.
952                 *
953                 * @param bool true Enable the RePublicize UI in the block editor context. Defaults to true.
954                 */
955                'republicize_enabled'           => apply_filters( 'jetpack_block_editor_republicize_feature', true ),
956            ),
957            'siteFragment'     => $status->get_site_suffix(),
958            'adminUrl'         => esc_url( admin_url() ),
959            'tracksUserData'   => $user_data,
960            'wpcomBlogId'      => $blog_id,
961            'allowedMimeTypes' => wp_get_mime_types(),
962            'siteLocale'       => str_replace( '_', '-', get_locale() ),
963            'ai-assistant'     => $ai_assistant_state,
964            'screenBase'       => $screen_base,
965            /**
966             * Add your own feature flags to the block editor.
967             *
968             * You can access the feature flags in the block editor via hasFeatureFlag( 'your-feature-flag' ) function.
969             *
970             * @since 14.8
971             *
972             * @param array true Enable the RePublicize UI in the block editor context. Defaults to true.
973             */
974            'feature_flags'    => apply_filters( 'jetpack_block_editor_feature_flags', array() ),
975            'pluginBasePath'   => plugins_url( '', Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
976        );
977
978        wp_localize_script(
979            'jetpack-blocks-editor',
980            'Jetpack_Editor_Initial_State',
981            $initial_state
982        );
983
984        // Adds Connection package initial state.
985        Connection_Initial_State::render_script( 'jetpack-blocks-editor' );
986    }
987
988    /**
989     * Block feature names in the `no-post-editor` preset (extensions/index.json): blocks
990     * whose editor bundle is usable outside the post editor, so they appear in front-end
991     * block editors such as P2. These must never be deferred (see self::$lazy_blocks and
992     * self::load_independent_blocks()).
993     *
994     * @since $$next-version$$
995     *
996     * @return string[] Feature names, or an empty array when the preset is unavailable.
997     */
998    private static function get_no_post_editor_extensions() {
999        $preset = self::get_preset();
1000        if ( is_object( $preset ) && isset( $preset->{'no-post-editor'} ) && is_array( $preset->{'no-post-editor'} ) ) {
1001            return $preset->{'no-post-editor'};
1002        }
1003        return array();
1004    }
1005
1006    /**
1007     * Some blocks do not depend on a specific module,
1008     * and can consequently be loaded outside of the usual modules.
1009     * We will look for such modules in the extensions/ directory.
1010     *
1011     * @since 7.1.0
1012     * @since 16.0 Pure display blocks are deferred on front-end requests and registered on first render.
1013     * @since $$next-version$$ Blocks in the `no-post-editor` preset are never deferred, so front-end editors (e.g. P2) keep them.
1014     * @see wp_common_block_scripts_and_styles()
1015     */
1016    public static function load_independent_blocks() {
1017        if ( self::should_load() ) {
1018            /**
1019             * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
1020             * If available, load them.
1021             */
1022            $directories = array( 'blocks', 'plugins', 'extended-blocks' );
1023
1024            /*
1025             * On plain front-end requests, defer the registration PHP of pure display
1026             * blocks (see self::$lazy_blocks) until the block is actually encountered
1027             * while rendering. The block editor, the block-types REST endpoint and
1028             * server-side rendering all run in a "block-editor context" and keep loading
1029             * every block eagerly, so their behavior is unchanged.
1030             */
1031            $defer = ! self::is_block_editor_context();
1032
1033            /*
1034             * Front-end block editors (e.g. P2) render the inserter on a plain front-end
1035             * request, so is_block_editor_context() is false there, yet a block must be
1036             * registered on `init` for get_availability() to report it and keep it in the
1037             * inserter. Never defer a block that ships in the `no-post-editor` preset â€”
1038             * those are precisely the blocks usable outside the post editor.
1039             */
1040            $no_post_editor_blocks = $defer ? self::get_no_post_editor_extensions() : array();
1041
1042            foreach ( static::get_extensions() as $extension ) {
1043                if (
1044                    $defer
1045                    && in_array( $extension, self::$lazy_blocks, true )
1046                    && ! in_array( $extension, $no_post_editor_blocks, true )
1047                ) {
1048                    self::$deferred_blocks[ $extension ] = true;
1049                    continue;
1050                }
1051
1052                foreach ( $directories as $dirname ) {
1053                    $path = JETPACK__PLUGIN_DIR . "extensions/{$dirname}/{$extension}/{$extension}.php";
1054
1055                    if ( file_exists( $path ) ) {
1056                        include_once $path;
1057                        continue 2;
1058                    }
1059                }
1060            }
1061
1062            if ( ! empty( self::$deferred_blocks ) ) {
1063                add_filter( 'pre_render_block', array( __CLASS__, 'lazy_register_deferred_block' ), 10, 3 );
1064            }
1065        }
1066    }
1067
1068    /**
1069     * Register deferred blocks present in a top-level block's subtree before it renders.
1070     *
1071     * Hooked to `pre_render_block`. For a top-level block ($parent_block is null) the
1072     * filter fires before core builds the block's WP_Block object, so we walk the whole
1073     * parsed subtree and register every deferred Jetpack block it contains. This must
1074     * happen at the top level: core resolves an inner block's `block_type` when it
1075     * constructs that inner WP_Block, which is *before* the inner block's own
1076     * `pre_render_block` fires â€” so registering a deferred dynamic block only when its
1077     * own inner filter fires would be too late and its render_callback would be skipped.
1078     * Inner-block invocations (non-null $parent_block) are ignored because the top-level
1079     * walk has already handled the whole tree. Returns $pre_render untouched.
1080     *
1081     * @since 16.0
1082     *
1083     * @param string|null    $pre_render   The pre-rendered content. Default null.
1084     * @param array          $parsed_block The parsed block being rendered.
1085     * @param \WP_Block|null $parent_block Parent block, or null for a top-level block.
1086     *
1087     * @return string|null Unchanged $pre_render.
1088     */
1089    public static function lazy_register_deferred_block( $pre_render, $parsed_block, $parent_block = null ) {
1090        // Respect any earlier short-circuit, only act on top-level blocks, and stop
1091        // once every deferred block on the page has been registered.
1092        if ( null !== $pre_render || null !== $parent_block || empty( self::$deferred_blocks ) ) {
1093            return $pre_render;
1094        }
1095
1096        self::register_deferred_blocks_in_subtree( $parsed_block );
1097
1098        return $pre_render;
1099    }
1100
1101    /**
1102     * Recursively register any deferred Jetpack blocks found in a parsed block subtree.
1103     *
1104     * @since 16.0
1105     *
1106     * @param array $parsed_block A parsed block (with optional `innerBlocks`).
1107     * @param array $seen_refs    Reusable-block IDs already visited, to guard against cycles.
1108     *
1109     * @return void
1110     */
1111    private static function register_deferred_blocks_in_subtree( $parsed_block, &$seen_refs = array() ) {
1112        if ( empty( self::$deferred_blocks ) ) {
1113            return;
1114        }
1115
1116        $block_name = $parsed_block['blockName'] ?? '';
1117        if ( '' !== $block_name && str_starts_with( $block_name, 'jetpack/' ) ) {
1118            $feature = substr( $block_name, strlen( 'jetpack/' ) );
1119            if ( ! empty( self::$deferred_blocks[ $feature ] ) ) {
1120                // Only attempt registration once per block, whether or not it succeeds
1121                // (a block guarded by a connection/module check may intentionally not register).
1122                unset( self::$deferred_blocks[ $feature ] );
1123
1124                if ( ! self::is_registered( $block_name ) ) {
1125                    self::load_and_register_deferred_block( $feature );
1126                }
1127            }
1128        }
1129
1130        /*
1131         * A synced pattern / reusable block (core/block) keeps its content in a separate
1132         * wp_block post that core only parses at render time (render_block_core_block),
1133         * so it is absent from this parsed tree. Resolve the reference and recurse so a
1134         * deferred block inside the pattern is registered before core builds its WP_Block.
1135         *
1136         * core/navigation has the same ref-based hidden-content shape (a wp_navigation
1137         * post) but is intentionally not handled: none of the deferred blocks can be
1138         * inserted into a navigation menu through the editor, and resolving the ref would
1139         * add a get_post()/parse_blocks() on essentially every front-end page (menus are
1140         * near-ubiquitous) for a case that cannot occur without hand-authored markup.
1141         */
1142        if ( 'core/block' === $block_name && ! empty( $parsed_block['attrs']['ref'] ) ) {
1143            $ref = (int) $parsed_block['attrs']['ref'];
1144            if ( ! isset( $seen_refs[ $ref ] ) ) {
1145                $seen_refs[ $ref ] = true;
1146                $reusable_block    = get_post( $ref );
1147                if ( $reusable_block instanceof \WP_Post && 'wp_block' === $reusable_block->post_type ) {
1148                    foreach ( parse_blocks( $reusable_block->post_content ) as $inner_block ) {
1149                        self::register_deferred_blocks_in_subtree( $inner_block, $seen_refs );
1150                    }
1151                }
1152            }
1153        }
1154
1155        if ( ! empty( $parsed_block['innerBlocks'] ) ) {
1156            foreach ( $parsed_block['innerBlocks'] as $inner_block ) {
1157                self::register_deferred_blocks_in_subtree( $inner_block, $seen_refs );
1158            }
1159        }
1160    }
1161
1162    /**
1163     * Include a deferred block's registration PHP and run the `init` callback it
1164     * adds, immediately.
1165     *
1166     * The block files register themselves with `add_action( 'init', â€¦ )`. By render
1167     * time `init` has long since fired, so including the file is not enough on its
1168     * own: we capture the callback(s) the include adds to `init` and invoke them now.
1169     * Only blocks in self::$lazy_blocks reach this path, and each adds exactly its
1170     * own registration callback to `init`, so this runs that single registration.
1171     *
1172     * @since 16.0
1173     *
1174     * @param string $feature Block feature name (directory name without the `jetpack/` prefix).
1175     *
1176     * @return void
1177     */
1178    private static function load_and_register_deferred_block( $feature ) {
1179        $path = JETPACK__PLUGIN_DIR . "extensions/blocks/{$feature}/{$feature}.php";
1180        if ( ! file_exists( $path ) ) {
1181            self::warn_about_deferred_block_registration_failure( $feature, 'missing block registration file' );
1182            return;
1183        }
1184
1185        global $wp_filter;
1186
1187        $before = isset( $wp_filter['init'] ) ? $wp_filter['init']->callbacks : array();
1188
1189        include_once $path;
1190
1191        if ( ! isset( $wp_filter['init'] ) ) {
1192            self::warn_about_deferred_block_registration_failure( $feature, 'block file did not add an init callback' );
1193            return;
1194        }
1195
1196        $registered_callback = false;
1197
1198        // Run (and then detach) any callback the include just added to `init`.
1199        foreach ( $wp_filter['init']->callbacks as $priority => $callbacks ) {
1200            foreach ( $callbacks as $id => $callback ) {
1201                if ( isset( $before[ $priority ][ $id ] ) ) {
1202                    continue;
1203                }
1204                $registered_callback = true;
1205                if ( is_callable( $callback['function'] ) ) {
1206                    call_user_func( $callback['function'] );
1207                }
1208                remove_action( 'init', $callback['function'], $priority );
1209            }
1210        }
1211
1212        if ( ! $registered_callback ) {
1213            self::warn_about_deferred_block_registration_failure( $feature, 'block file did not add a new init callback' );
1214        }
1215    }
1216
1217    /**
1218     * Surface lazy-registration mistakes during debugging without adding front-end noise.
1219     *
1220     * @since 16.0
1221     *
1222     * @param string $feature Block feature name (directory name without the `jetpack/` prefix).
1223     * @param string $reason  Short reason for the failure.
1224     *
1225     * @return void
1226     */
1227    private static function warn_about_deferred_block_registration_failure( $feature, $reason ) {
1228        if ( ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || ! function_exists( '_doing_it_wrong' ) ) {
1229            return;
1230        }
1231
1232        _doing_it_wrong(
1233            __METHOD__,
1234            sprintf(
1235                /* translators: 1: Jetpack block feature name. 2: Failure reason. */
1236                esc_html__( 'Lazy Jetpack block registration failed for "%1$s": %2$s.', 'jetpack' ),
1237                esc_html( $feature ),
1238                esc_html( $reason )
1239            ),
1240            '16.0'
1241        );
1242    }
1243
1244    /**
1245     * Determine whether the current request is a block-editor context that needs
1246     * every Jetpack block loaded eagerly on `init`.
1247     *
1248     * Returns true for admin, REST, cron, WP-CLI and XML-RPC requests so the editor,
1249     * the `/wp/v2/block-types` endpoint and server-side rendering keep seeing the full
1250     * set of blocks. Returns false only for plain front-end web requests, where pure
1251     * display blocks are registered just-in-time as they render.
1252     *
1253     * This runs at module-load time (around after_setup_theme), before core defines
1254     * REST_REQUEST during parse_request, so self-hosted and Atomic REST requests are
1255     * detected from the request URL instead of the constant. That URL check cannot
1256     * work on WordPress.com Simple: its public API filters `rest_url_prefix` to an
1257     * empty string, so rest_get_url_prefix() returns '' and the REST roots computed
1258     * below collapse to '//', which no request path can match. Simple's requests are
1259     * detected via REST_API_REQUEST instead, which its API entry points define before
1260     * wp-load.php runs.
1261     *
1262     * @since 16.0
1263     *
1264     * @return bool True for block-editor (non-front-end) contexts, false for plain front-end requests.
1265     */
1266    private static function is_block_editor_context() {
1267        if ( is_admin() ) {
1268            return true;
1269        }
1270
1271        /*
1272         * Treat any non-front-end execution context as block-editor. These are not the
1273         * front-end hot path this gate optimizes, and some still render block content
1274         * (e.g. cron-generated subscription e-mails) that depends on full registration.
1275         *
1276         * Core defines REST_REQUEST during parse_request, after this runs, so it is
1277         * normally still unset here; it is checked anyway so the result stays correct
1278         * if this is ever called later in the request. REST_API_REQUEST is what catches
1279         * WordPress.com Simple, where the URL check below cannot work at all (see the
1280         * method docblock).
1281         */
1282        if (
1283            Constants::is_true( 'DOING_CRON' )
1284            || Constants::is_true( 'WP_CLI' )
1285            || Constants::is_true( 'XMLRPC_REQUEST' )
1286            || Constants::is_true( 'REST_REQUEST' )
1287            || Constants::is_true( 'REST_API_REQUEST' )
1288        ) {
1289            return true;
1290        }
1291
1292        /*
1293         * No request URI means a non-web execution context (WP-CLI without it, test
1294         * suites, etc.). A genuine front-end page request always carries one, so it
1295         * costs nothing on the hot path to treat the empty case as "load eagerly".
1296         */
1297        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
1298        if ( '' === $request_uri ) {
1299            return true;
1300        }
1301
1302        /*
1303         * Anchor the REST root (home path + prefix) at the start of the request path,
1304         * so a front-end URL that merely carries the prefix in a query value or a
1305         * deeper path segment is not misread as a REST request. home_url() is used
1306         * rather than rest_url() so detection does not depend on permalink structure.
1307         * Both the rewritten `/wp-json/` form and the index-permalink
1308         * `/index.php/wp-json/` form (used when the site lacks pretty permalinks) are
1309         * matched.
1310         */
1311        $path = (string) wp_parse_url( $request_uri, PHP_URL_PATH );
1312        if ( '' !== $path ) {
1313            $home_path   = trailingslashit( (string) wp_parse_url( home_url(), PHP_URL_PATH ) );
1314            $rest_prefix = trailingslashit( rest_get_url_prefix() );
1315            $rest_roots  = array(
1316                $home_path . $rest_prefix,
1317                $home_path . 'index.php/' . $rest_prefix,
1318            );
1319            foreach ( $rest_roots as $rest_root ) {
1320                if ( str_starts_with( trailingslashit( $path ), $rest_root ) ) {
1321                    return true;
1322                }
1323            }
1324        }
1325
1326        // Plain-permalink REST uses a `rest_route` query var; match the exact key.
1327        $query = (string) wp_parse_url( $request_uri, PHP_URL_QUERY );
1328        if ( '' !== $query ) {
1329            parse_str( $query, $query_vars );
1330            if ( ! empty( $query_vars['rest_route'] ) ) {
1331                return true;
1332            }
1333        }
1334
1335        return false;
1336    }
1337
1338    /**
1339     * Editor-oriented extensions that nonetheless have front-end side effects and must
1340     * therefore keep loading on every request, even outside the block editor.
1341     *
1342     * Keyed by directory ('plugins' / 'extended-blocks') for an exact, intentional match.
1343     *
1344     * @since 16.0
1345     *
1346     * @var array
1347     */
1348    private static $frontend_editor_extensions = array(
1349        'plugins'         => array(
1350            // Mounts the Reader Chat widget on the front end (wp_enqueue_scripts) and
1351            // wires the AI sidebar/provider registration AI Assistant depends on.
1352            'ai-assistant-plugin',
1353            // Signals Big Sky via the jetpack_image_studio_enabled filter on `init`,
1354            // which can run on the front end.
1355            'image-studio',
1356        ),
1357        'extended-blocks' => array(
1358            // Registers the videopress/video block on `init`, required to render it on the front end.
1359            'videopress-video',
1360            // Registers the `premium-content/container` plan availability that the Premium Content
1361            // block's front-end render reads via required_plan_checks(); skipping it breaks the paywall.
1362            'premium-content-container',
1363        ),
1364    );
1365
1366    /**
1367     * Loads PHP components of block editor extensions.
1368     *
1369     * @since 8.9.0
1370     */
1371    public static function load_block_editor_extensions() {
1372        if ( self::should_load() ) {
1373            // Block editor extensions to load.
1374            $extensions_to_load = array(
1375                'extended-blocks',
1376                'plugins',
1377            );
1378
1379            $is_editor_context = self::is_block_editor_context();
1380
1381            // Collect the extension paths.
1382            foreach ( $extensions_to_load as $extension_to_load ) {
1383                $extensions_folder = glob( JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/*' );
1384
1385                $frontend_allow_list = self::$frontend_editor_extensions[ $extension_to_load ] ?? array();
1386
1387                // Require each of the extension files, in case it exists.
1388                foreach ( $extensions_folder as $extension_folder ) {
1389                    $name = basename( $extension_folder );
1390
1391                    /*
1392                     * On plain front-end requests, only load extensions that have known
1393                     * front-end side effects. Editor-only extensions are skipped here and
1394                     * loaded on admin/REST (block-editor) requests instead, reducing the
1395                     * per-front-end-request PHP/opcache footprint.
1396                     */
1397                    if ( ! $is_editor_context && ! in_array( $name, $frontend_allow_list, true ) ) {
1398                        continue;
1399                    }
1400
1401                    $extension_file_path = JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/' . $name . '/' . $name . '.php';
1402
1403                    if ( file_exists( $extension_file_path ) ) {
1404                        include_once $extension_file_path;
1405                    }
1406                }
1407            }
1408        }
1409    }
1410
1411    /**
1412     * Determine whether a site should use the default set of blocks, or a custom set.
1413     * Possible variations are currently beta, experimental, and production.
1414     *
1415     * @since 8.1.0
1416     *
1417     * @return string $block_varation production|beta|experimental
1418     */
1419    public static function blocks_variation() {
1420        // Default to production blocks.
1421        $block_varation = 'production';
1422
1423        /*
1424         * Prefer to use this JETPACK_BLOCKS_VARIATION constant
1425         * or the jetpack_blocks_variation filter
1426         * to set the block variation in your code.
1427         */
1428        $default = Constants::get_constant( 'JETPACK_BLOCKS_VARIATION' );
1429        if ( ! empty( $default ) && in_array( $default, array( 'beta', 'experimental', 'production' ), true ) ) {
1430            $block_varation = $default;
1431        }
1432
1433        /**
1434        * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
1435        *
1436        * @since 6.9.0
1437        * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
1438        *
1439        * @param boolean
1440        */
1441        $is_beta = apply_filters_deprecated(
1442            'jetpack_load_beta_blocks',
1443            array( false ),
1444            'jetpack-11.8.0',
1445            'jetpack_blocks_variation'
1446        );
1447
1448        /*
1449         * Switch to beta blocks if you use the JETPACK_BETA_BLOCKS constant
1450         * or the deprecated jetpack_load_beta_blocks filter.
1451         * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
1452         */
1453        if (
1454            empty( $default )
1455            && (
1456                $is_beta
1457                || Constants::is_true( 'JETPACK_BETA_BLOCKS' )
1458            )
1459        ) {
1460            $block_varation = 'beta';
1461        }
1462
1463        /**
1464        * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
1465        *
1466        * @since 6.9.0
1467        * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
1468        *
1469        * @param boolean
1470        */
1471        $is_experimental = apply_filters_deprecated(
1472            'jetpack_load_experimental_blocks',
1473            array( false ),
1474            'jetpack-11.8.0',
1475            'jetpack_blocks_variation'
1476        );
1477
1478        /*
1479         * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant
1480         * or the deprecated jetpack_load_experimental_blocks filter.
1481         * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
1482         */
1483        if (
1484            empty( $default )
1485            && (
1486                $is_experimental
1487                || Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' )
1488            )
1489        ) {
1490            $block_varation = 'experimental';
1491        }
1492
1493        /**
1494         * Allow customizing the variation of blocks in use on a site.
1495         * Overwrites any previously set values, whether by constant or filter.
1496         *
1497         * @since 8.1.0
1498         *
1499         * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
1500         */
1501        return apply_filters( 'jetpack_blocks_variation', $block_varation );
1502    }
1503
1504    /**
1505     * Get a list of extensions available for the variation you chose.
1506     *
1507     * @since 8.1.0
1508     *
1509     * @param object $preset_extensions_manifest List of extensions available in Jetpack.
1510     * @param string $blocks_variation           Subset of blocks. production|beta|experimental.
1511     *
1512     * @return array $preset_extensions Array of extensions for that variation
1513     */
1514    public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
1515        $preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
1516                ? (array) $preset_extensions_manifest->{ $blocks_variation }
1517                : array();
1518
1519        /*
1520         * Experimental and Beta blocks need the production blocks as well.
1521         */
1522        if (
1523            'experimental' === $blocks_variation
1524            || 'beta' === $blocks_variation
1525        ) {
1526            $production_extensions = isset( $preset_extensions_manifest->production )
1527                ? (array) $preset_extensions_manifest->production
1528                : array();
1529
1530            $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
1531        }
1532
1533        /*
1534         * Beta blocks need the experimental blocks as well.
1535         *
1536         * If you've chosen to see Beta blocks,
1537         * we want to make all blocks available to you:
1538         * - Production
1539         * - Experimental
1540         * - Beta
1541         */
1542        if ( 'beta' === $blocks_variation ) {
1543            $production_extensions = isset( $preset_extensions_manifest->experimental )
1544                ? (array) $preset_extensions_manifest->experimental
1545                : array();
1546
1547            $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
1548        }
1549
1550        return $preset_extensions;
1551    }
1552
1553    /**
1554     * Validate a URL used in a SSR block.
1555     *
1556     * @since 8.3.0
1557     *
1558     * @param string $url      URL saved as an attribute in block.
1559     * @param array  $allowed  Array of allowed hosts for that block, or regexes to check against.
1560     * @param bool   $is_regex Array of regexes matching the URL that could be used in block.
1561     *
1562     * @return bool|string
1563     */
1564    public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
1565        if (
1566            empty( $url )
1567            || ! is_array( $allowed )
1568            || empty( $allowed )
1569        ) {
1570            return false;
1571        }
1572
1573        $url_components = wp_parse_url( $url );
1574
1575        // Bail early if we cannot find a host.
1576        if ( empty( $url_components['host'] ) ) {
1577            return false;
1578        }
1579
1580        // Normalize URL.
1581        $url = sprintf(
1582            '%s://%s%s%s',
1583            $url_components['scheme'] ?? 'https',
1584            $url_components['host'],
1585            $url_components['path'] ?? '/',
1586            isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
1587        );
1588
1589        if ( ! empty( $url_components['fragment'] ) ) {
1590            $url = $url . '#' . rawurlencode( $url_components['fragment'] );
1591        }
1592
1593        /*
1594         * If we're using an allowed list of hosts,
1595         * check if the URL belongs to one of the domains allowed for that block.
1596         */
1597        if (
1598            false === $is_regex
1599            && in_array( $url_components['host'], $allowed, true )
1600        ) {
1601            return $url;
1602        }
1603
1604        /*
1605         * If we are using an array of regexes to check against,
1606         * loop through that.
1607         */
1608        if ( true === $is_regex ) {
1609            foreach ( $allowed as $regex ) {
1610                if ( 1 === preg_match( $regex, $url ) ) {
1611                    return $url;
1612                }
1613            }
1614        }
1615
1616        return false;
1617    }
1618
1619    /**
1620     * Determines whether a preview of the block with an upgrade nudge should
1621     * be displayed for admins on the site frontend.
1622     *
1623     * @since 8.4.0
1624     *
1625     * @param array $availability_for_block The availability for the block.
1626     *
1627     * @return bool
1628     */
1629    public static function should_show_frontend_preview( $availability_for_block ) {
1630        return (
1631            isset( $availability_for_block['details']['required_plan'] )
1632            && current_user_can( 'manage_options' )
1633            && ! is_feed()
1634        );
1635    }
1636
1637    /**
1638     * Output an UpgradeNudge Component on the frontend of a site.
1639     *
1640     * @since 8.4.0
1641     *
1642     * @param string $plan The plan that users need to purchase to make the block work.
1643     *
1644     * @return string
1645     */
1646    public static function upgrade_nudge( $plan ) {
1647        require_once JETPACK__PLUGIN_DIR . '_inc/lib/components.php';
1648        return Jetpack_Components::render_upgrade_nudge(
1649            array(
1650                'plan' => $plan,
1651            )
1652        );
1653    }
1654
1655    /**
1656     * Output a notice within a block.
1657     *
1658     * @since 8.6.0
1659     *
1660     * @param string $message Notice we want to output.
1661     * @param string $status  Status of the notice. Can be one of success, info, warning, error. info by default.
1662     * @param string $classes List of CSS classes.
1663     *
1664     * @return string
1665     */
1666    public static function notice( $message, $status = 'info', $classes = '' ) {
1667        if (
1668            empty( $message )
1669            || ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1670        ) {
1671            return '';
1672        }
1673
1674        $color = '';
1675        switch ( $status ) {
1676            case 'success':
1677                $color = '#00a32a';
1678                break;
1679            case 'warning':
1680                $color = '#dba617';
1681                break;
1682            case 'error':
1683                $color = '#d63638';
1684                break;
1685            case 'info':
1686            default:
1687                $color = '#72aee6';
1688                break;
1689        }
1690
1691        return sprintf(
1692            '<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1693            esc_attr( $status ),
1694            wp_kses(
1695                $message,
1696                array(
1697                    'br' => array(),
1698                    'p'  => array(),
1699                    'a'  => array(
1700                        'href'   => array(),
1701                        'target' => array(),
1702                        'rel'    => array(),
1703                    ),
1704                )
1705            ),
1706            esc_attr( $classes ),
1707            sanitize_hex_color( $color )
1708        );
1709    }
1710
1711    /**
1712     * Retrieve site-specific features for Simple sites.
1713     *
1714     * We're caching the data for the lifetime of the request, because it can be slow to calculate,
1715     * and it can be called multiple times per single request.
1716     *
1717     * We intentionally don't use object caching or any other type of persistent caching,
1718     * in order to avoid complex cache invalidation on subscription addition or removal.
1719     *
1720     * @since 10.7
1721     *
1722     * @return array
1723     */
1724    private static function get_site_specific_features() {
1725        $current_blog_id = get_current_blog_id();
1726
1727        if ( isset( self::$site_specific_features[ $current_blog_id ] ) ) {
1728            return self::$site_specific_features[ $current_blog_id ];
1729        }
1730
1731        if ( ! class_exists( 'Store_Product_List' ) ) {
1732            require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1733        }
1734
1735        $site_specific_features                           = Store_Product_List::get_site_specific_features_data( $current_blog_id );
1736        self::$site_specific_features[ $current_blog_id ] = $site_specific_features;
1737
1738        return $site_specific_features;
1739    }
1740
1741    /**
1742     * Set the availability of the block as the editor
1743     * is loaded.
1744     *
1745     * @param string $slug Slug of the block.
1746     */
1747    public static function set_availability_for_plan( $slug ) {
1748        $slug = self::remove_extension_prefix( $slug );
1749
1750        if ( Jetpack_Plan::supports( $slug ) ) {
1751            self::set_extension_available( $slug );
1752            return;
1753        }
1754
1755        // Check what's the minimum plan where the feature is available.
1756        $plan           = '';
1757        $features_data  = array();
1758        $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
1759        $is_atomic_site = ( new Host() )->is_woa_site();
1760
1761        if ( $is_simple_site || $is_atomic_site ) {
1762            // Simple sites.
1763            if ( $is_simple_site ) {
1764                $features_data = self::get_site_specific_features();
1765            } else {
1766                // Atomic sites.
1767                $option = get_option( 'jetpack_active_plan' );
1768                if ( isset( $option['features'] ) ) {
1769                    $features_data = $option['features'];
1770                }
1771            }
1772
1773            if ( ! empty( $features_data['available'][ $slug ] ) ) {
1774                $plan = $features_data['available'][ $slug ][0];
1775            } elseif ( isset( self::$wpcom_minimum_plan_fallbacks[ $slug ] ) ) {
1776                // Fallback for features with conditional availability (e.g., sticker-based gating)
1777                // that don't appear in features_data['available'].
1778                $plan = self::$wpcom_minimum_plan_fallbacks[ $slug ];
1779            }
1780        } else {
1781            // Jetpack sites.
1782            $plan = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1783        }
1784
1785        self::set_extension_unavailable(
1786            $slug,
1787            'missing_plan',
1788            array(
1789                'required_feature' => $slug,
1790                'required_plan'    => $plan,
1791            )
1792        );
1793    }
1794
1795    /**
1796     * Wraps the suplied render_callback in a function to check
1797     * the availability of the block before rendering it.
1798     *
1799     * @param string   $slug The block slug, used to check for availability.
1800     * @param callable $render_callback The render_callback that will be called if the block is available.
1801     */
1802    public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1803        return function ( $prepared_attributes, $block_content, $block ) use ( $render_callback, $slug ) {
1804            $availability = self::get_cached_availability();
1805            $bare_slug    = self::remove_extension_prefix( $slug );
1806            if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1807                return call_user_func( $render_callback, $prepared_attributes, $block_content, $block );
1808            }
1809
1810            // A preview of the block is rendered for admins on the frontend with an upgrade nudge.
1811            if ( isset( $availability[ $bare_slug ] ) ) {
1812                if ( self::should_show_frontend_preview( $availability[ $bare_slug ] ) ) {
1813                    $block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content, $block );
1814
1815                    // If the upgrade nudge isn't already being displayed by a parent block, display the nudge.
1816                    if ( isset( $block->attributes['shouldDisplayFrontendBanner'] ) && $block->attributes['shouldDisplayFrontendBanner'] ) {
1817                        $upgrade_nudge = self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
1818                        return $upgrade_nudge . $block_preview;
1819                    }
1820
1821                    return $block_preview;
1822                }
1823            }
1824
1825            return null;
1826        };
1827    }
1828
1829    /**
1830     * Display a message to site editors and roles above when a block is no longer supported.
1831     * This is only displayed on the frontend.
1832     *
1833     * @since 12.3
1834     *
1835     * @param string $block_content The block content.
1836     * @param array  $block         The full block, including name and attributes.
1837     *
1838     * @return string
1839     */
1840    public static function display_deprecated_block_message( $block_content, $block ) {
1841        if ( isset( $block['blockName'] ) && in_array( $block['blockName'], self::$deprecated_blocks, true ) ) {
1842            if ( current_user_can( 'edit_posts' ) ) {
1843                $block_content = self::notice(
1844                    __( 'This block is no longer supported. Its contents will no longer be displayed to your visitors and as such this block should be removed.', 'jetpack' ),
1845                    'warning',
1846                    'jetpack-block-deprecated'
1847                );
1848            } else {
1849                $block_content = '';
1850            }
1851        }
1852
1853        return $block_content;
1854    }
1855
1856    /**
1857     * Register block metadata collection for Jetpack blocks.
1858     * This allows for more efficient block metadata loading by avoiding
1859     * individual block.json file reads at runtime.
1860     *
1861     * Uses wp_register_block_metadata_collection() if the manifest file
1862     * exists. The manifest file is auto-generated during the build process.
1863     *
1864     * Runs on plugins_loaded to ensure registration happens before individual
1865     * blocks register themselves on init.
1866     *
1867     * @static
1868     * @since 14.1
1869     * @return void
1870     */
1871    public static function register_block_metadata_collection() {
1872        $meta_file_path = JETPACK__PLUGIN_DIR . '_inc/blocks/blocks-manifest.php';
1873        if ( file_exists( $meta_file_path ) ) {
1874            wp_register_block_metadata_collection(
1875                JETPACK__PLUGIN_DIR . '_inc/blocks/',
1876                $meta_file_path
1877            );
1878        }
1879    }
1880
1881    /**
1882     * Set the JS loading strategy for a block.
1883     *
1884     * @param string     $block_name The block name.
1885     * @param array|bool $strategy   The JS loading strategy.
1886     *
1887     * @since 15.0
1888     */
1889    public static function set_block_js_loading_strategy( $block_name, $strategy ) {
1890        self::$block_js_loading_strategies[ $block_name ] = $strategy;
1891    }
1892
1893    /**
1894     * Get the JS loading strategy for a block.
1895     *
1896     * @param string $block_name The block name.
1897     *
1898     * @return array|bool The JS loading strategy for the block.
1899     *
1900     * @since 15.0
1901     */
1902    public static function get_block_js_loading_strategy( $block_name ) {
1903        $strategy = array(
1904            'strategy'  => 'defer',
1905            'in_footer' => true,
1906        );
1907
1908        if ( isset( self::$block_js_loading_strategies[ $block_name ] ) ) {
1909            $strategy = self::$block_js_loading_strategies[ $block_name ];
1910        }
1911
1912        return $strategy;
1913    }
1914}
1915
1916if ( ( new Host() )->is_woa_site() ) {
1917    /**
1918    * Enable upgrade nudge for Atomic sites.
1919     * This feature is false as default,
1920     * so let's enable it through this filter.
1921     *
1922     * More doc: https://github.com/Automattic/jetpack/blob/trunk/projects/plugins/jetpack/extensions/README.md#upgrades-for-blocks
1923     */
1924    add_filter( 'jetpack_block_editor_enable_upgrade_nudge', '__return_true' );
1925}