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