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