PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-a.7
Jetpack – WP Security, Backup, Speed, & Growth v16.3-a.7
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 13.7.2 13.8.3 All 506 releases
← All changes | class.jetpack-gutenberg.php +767 -176 12.5.2 → 16.3-a.7 View file →
@@ -6,36 +6,26 @@
6 6 * @package automattic/jetpack
7 7 */
8 8
9 9 use Automattic\Jetpack\Assets;
10 +use Automattic\Jetpack\Assets\Shared_Stores_Assets;
10 11 use Automattic\Jetpack\Blocks;
11 12 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
12 13 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13 14 use Automattic\Jetpack\Constants;
14 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;
15 18 use Automattic\Jetpack\Status;
16 19 use Automattic\Jetpack\Status\Host;
17 20
18 -// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move the functions and such to some other file.
21 +if ( ! defined( 'ABSPATH' ) ) {
22 + exit( 0 );
23 +}
19 24
20 -/**
21 - * Wrapper function to safely register a gutenberg block type
22 - *
23 - * @deprecated 9.1.0 Use Automattic\\Jetpack\\Blocks::jetpack_register_block instead
24 - *
25 - * @see register_block_type
26 - *
27 - * @since 6.7.0
28 - *
29 - * @param string $slug Slug of the block.
30 - * @param array $args Arguments that are passed into register_block_type.
31 - *
32 - * @return WP_Block_Type|false The registered block type on success, or false on failure.
33 - */
34 -function jetpack_register_block( $slug, $args = array() ) {
35 - _deprecated_function( __METHOD__, '9.1.0', 'Automattic\\Jetpack\\Blocks::jetpack_register_block' );
36 - return Blocks::jetpack_register_block( $slug, $args );
37 -}
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';
38 28
39 29 /**
40 30 * General Gutenberg editor specific functionality
41 31 */
@@ -81,8 +71,133 @@
81 71 'jetpack/revue',
82 72 );
83 73
84 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 + /**
85 200 * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
86 201 * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
87 202 * optionally fall back to that.
88 203 *
@@ -116,8 +231,9 @@
116 231 $version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
117 232 }
118 233
119 234 if ( ! $version_available ) {
235 + $slug = self::remove_extension_prefix( $slug );
120 236 self::set_extension_unavailable(
121 237 $slug,
122 238 'incorrect_gutenberg_version',
123 239 array(
@@ -152,9 +268,9 @@
152 268 *
153 269 * @return string The unprefixed extension name.
154 270 */
155 271 public static function remove_extension_prefix( $extension_name ) {
156 - if ( 0 === strpos( $extension_name, 'jetpack/' ) || 0 === strpos( $extension_name, 'jetpack-' ) ) {
272 + if ( str_starts_with( $extension_name, 'jetpack/' ) || str_starts_with( $extension_name, 'jetpack-' ) ) {
157 273 return substr( $extension_name, strlen( 'jetpack/' ) );
158 274 }
159 275 return $extension_name;
160 276 }
@@ -176,9 +292,10 @@
176 292 *
177 293 * @param string $slug Slug of the extension.
178 294 */
179 295 public static function set_extension_available( $slug ) {
180 - self::$availability[ self::remove_extension_prefix( $slug ) ] = true;
296 + $slug = self::remove_extension_prefix( $slug );
297 + self::$availability[ $slug ] = true;
181 298 }
182 299
183 300 /**
184 301 * Set the reason why an extension (block or plugin) is unavailable
@@ -211,10 +328,10 @@
211 328 // The block editor may apply an upgrade nudge if `missing_plan` is the reason.
212 329 // Add a descriptive suffix to disable behavior but provide informative reason.
213 330 $reason .= '__nudge_disabled';
214 331 }
215 -
216 - self::$availability[ self::remove_extension_prefix( $slug ) ] = array(
332 + $slug = self::remove_extension_prefix( $slug );
333 + self::$availability[ $slug ] = array(
217 334 'reason' => $reason,
218 335 'details' => $details,
219 336 );
220 337 }
@@ -236,11 +353,13 @@
236 353 *
237 354 * @return void
238 355 */
239 356 public static function reset() {
240 - self::$extensions = null;
241 - self::$availability = array();
242 - self::$cached_availability = null;
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();
243 362 }
244 363
245 364 /**
246 365 * Return the Gutenberg extensions (blocks and plugins) directory
@@ -260,28 +379,49 @@
260 379
261 380 /**
262 381 * Checks for a given .json file in the blocks folder.
263 382 *
383 + * @deprecated 14.3
384 + *
264 385 * @param string $preset The name of the .json file to look for.
265 386 *
266 387 * @return bool True if the file is found.
267 388 */
268 389 public static function preset_exists( $preset ) {
390 + _deprecated_function( __METHOD__, '14.3' );
269 391 return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
270 392 }
271 393
272 394 /**
273 - * Decodes JSON loaded from a preset file in the blocks folder
395 + * Decodes JSON loaded from the preset file in the blocks folder
274 396 *
275 - * @param string $preset The name of the .json file to load.
397 + * @since 14.3 Deprecated argument. Only one value is ever used.
276 398 *
399 + * @param null $deprecated No longer used.
400 + *
277 401 * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
278 402 */
279 - public static function get_preset( $preset ) {
280 - return json_decode(
281 - // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
282 - file_get_contents( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' )
283 - );
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;
284 424 }
285 425
286 426 /**
287 427 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
@@ -288,11 +428,9 @@
288 428 *
289 429 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
290 430 */
291 431 public static function get_jetpack_gutenberg_extensions_allowed_list() {
292 - $preset_extensions_manifest = self::preset_exists( 'index' )
293 - ? self::get_preset( 'index' )
294 - : (object) array();
432 + $preset_extensions_manifest = ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) ? array() : self::get_preset();
295 433 $blocks_variation = self::blocks_variation();
296 434
297 435 return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
298 436 }
@@ -307,8 +445,13 @@
307 445 public static function get_available_extensions( $allowed_extensions = null ) {
308 446 $exclusions = get_option( 'jetpack_excluded_extensions', array() );
309 447 $allowed_extensions = $allowed_extensions === null ? self::get_jetpack_gutenberg_extensions_allowed_list() : $allowed_extensions;
310 448
449 + // Avoid errors if option data is not as expected.
450 + if ( ! is_array( $exclusions ) ) {
451 + $exclusions = array();
452 + }
453 +
311 454 return array_diff( $allowed_extensions, $exclusions );
312 455 }
313 456
314 457 /**
@@ -404,8 +547,13 @@
404 547 *
405 548 * @param array
406 549 */
407 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 + }
408 556 }
409 557
410 558 return self::$extensions;
411 559 }
@@ -448,26 +596,55 @@
448 596 if ( ! Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
449 597 return false;
450 598 }
451 599
452 - if ( get_option( 'jetpack_blocks_disabled', false ) ) {
453 - return false;
600 + $return = true;
601 +
602 + if ( ! ( new Modules() )->is_active( 'blocks' ) ) {
603 + $return = false;
454 604 }
455 605
456 606 /**
457 - * Filter to disable Gutenberg blocks
607 + * Filter to enable Gutenberg blocks.
458 608 *
609 + * Defaults to true if (connected or in offline mode) and the Blocks module is active.
610 + *
459 611 * @since 6.5.0
612 + * @since 13.9 Filter is able to activate or deactivate Gutenberg blocks.
460 613 *
461 614 * @param bool true Whether to load Gutenberg blocks
462 615 */
463 - return (bool) apply_filters( 'jetpack_gutenberg', true );
616 + return (bool) apply_filters( 'jetpack_gutenberg', $return );
464 617 }
465 618
466 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 + /**
467 644 * Only enqueue block assets when needed.
468 645 *
469 - * @param string $type Slug of the block.
646 + * @param string $type Slug of the block or absolute path to the block source code directory.
470 647 * @param array $script_dependencies Script dependencies. Will be merged with automatically
471 648 * detected script dependencies from the webpack build.
472 649 *
473 650 * @return void
@@ -477,8 +654,18 @@
477 654 // A block's view assets will not be required in wp-admin.
478 655 return;
479 656 }
480 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 +
481 668 $type = sanitize_title_with_dashes( $type );
482 669 self::load_styles_as_required( $type );
483 670 self::load_scripts_as_required( $type, $script_dependencies );
484 671 }
@@ -533,12 +720,14 @@
533 720 // A block's view assets will not be required in wp-admin.
534 721 return;
535 722 }
536 723
724 + self::register_blocks_assets_base_url();
725 +
537 726 // Enqueue script.
538 727 $script_relative_path = self::get_blocks_directory() . $type . '/view.js';
539 728 $script_deps_path = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
540 - $script_dependencies[] = 'wp-polyfill';
729 + $script_dependencies[] = 'jetpack-blocks-assets-base-url';
541 730 if ( file_exists( $script_deps_path ) ) {
542 731 $asset_manifest = include $script_deps_path;
543 732 $script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
544 733 }
@@ -546,11 +735,12 @@
546 735 if ( ! Blocks::is_amp_request() && self::block_has_asset( $script_relative_path ) ) {
547 736 $script_version = self::get_asset_version( $script_relative_path );
548 737 $view_script = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
549 738 $view_script = add_query_arg( 'minify', 'false', $view_script );
739 + $strategy = self::get_block_js_loading_strategy( $type );
550 740
551 741 // Enqueue dependencies.
552 - wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
742 + wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, $strategy );
553 743
554 744 // If this is a customizer preview, enqueue the dependencies and render the script directly to the preview after autosave.
555 745 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
556 746 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
@@ -556,9 +746,9 @@
556 746 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
557 747 // The Map block is dependent on wp-element, and it doesn't appear to to be possible to load
558 748 // this dynamically into the customizer iframe currently.
559 749 if ( 'map' === $type ) {
560 - echo '<div>' . esc_html_e( 'No map preview available. Publish and refresh to see this widget.', 'jetpack' ) . '</div>';
750 + echo '<div>' . esc_html__( 'No map preview available. Publish and refresh to see this widget.', 'jetpack' ) . '</div>';
561 751 echo '<script>';
562 752 echo 'Array.from(document.getElementsByClassName(\'wp-block-jetpack-map\')).forEach(function(element){element.style.display = \'none\';})';
563 753 echo '</script>';
564 754 } else {
@@ -565,16 +755,8 @@
565 755 echo '<script id="jetpack-block-' . esc_attr( $type ) . '" src="' . esc_attr( $view_script ) . '&amp;ver=' . esc_attr( $script_version ) . '"></script>';
566 756 }
567 757 }
568 758 }
569 -
570 - wp_localize_script(
571 - 'jetpack-block-' . $type,
572 - 'Jetpack_Block_Assets_Base_Url',
573 - array(
574 - 'url' => plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE ),
575 - )
576 - );
577 759 }
578 760
579 761 /**
580 762 * Check if an asset exists for a block.
@@ -611,8 +793,42 @@
611 793 if ( ! self::should_load() ) {
612 794 return;
613 795 }
614 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 +
615 831 $status = new Status();
616 832
617 833 // Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
618 834 if ( ! $status->is_offline_mode() && Jetpack::is_connection_ready() ) {
@@ -627,31 +843,44 @@
627 843 } else {
628 844 $blocks_env = '';
629 845 }
630 846
847 + self::register_blocks_assets_base_url();
848 +
631 849 Assets::register_script(
632 850 'jetpack-blocks-editor',
633 851 "{$blocks_dir}editor{$blocks_env}.js",
634 852 JETPACK__PLUGIN_FILE,
635 - array( 'textdomain' => 'jetpack' )
853 + array(
854 + 'textdomain' => 'jetpack',
855 + 'dependencies' => array( 'jetpack-blocks-assets-base-url' ),
856 + )
636 857 );
637 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 +
638 871 // Hack around #20357 (specifically, that the editor bundle depends on
639 872 // wp-edit-post but wp-edit-post's styles break the Widget Editor and
640 873 // Site Editor) until a real fix gets unblocked.
641 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 + }
642 879 wp_styles()->query( 'jetpack-blocks-editor', 'registered' )->deps = array();
643 880
644 881 Assets::enqueue_script( 'jetpack-blocks-editor' );
645 882
646 - wp_localize_script(
647 - 'jetpack-blocks-editor',
648 - 'Jetpack_Block_Assets_Base_Url',
649 - array(
650 - 'url' => plugins_url( $blocks_dir . '/', JETPACK__PLUGIN_FILE ),
651 - )
652 - );
653 -
654 883 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
655 884 $user = wp_get_current_user();
656 885 $user_data = array(
657 886 'email' => $user->user_email,
@@ -665,27 +894,34 @@
665 894 $blog_id = Jetpack_Options::get_option( 'id', 0 );
666 895 $is_current_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected();
667 896 }
668 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 + }
669 901 // AI Assistant
670 - $ai_assistant_state = Jetpack_AI_Helper::get_ai_assistance_feature();
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 + );
671 906
672 - if ( is_wp_error( $ai_assistant_state ) ) {
673 - $ai_assistant_state = array(
674 - 'error-message' => $ai_assistant_state->get_error_message(),
675 - 'error-code' => $ai_assistant_state->get_error_code(),
676 - );
677 - } else {
678 - $ai_assistant_state['is-playground-visible'] = Constants::is_true( 'JETPACK_AI_ASSISTANT_PLAYGROUND' );
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;
679 911 }
680 912
681 - $screen_base = null;
682 - if ( function_exists( 'get_current_screen' ) ) {
683 - $screen_base = get_current_screen()->base;
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();
684 917 }
685 918
919 + $jetpack_plan = Jetpack_Plan::get();
686 920 $initial_state = array(
687 921 'available_blocks' => self::get_availability(),
922 + 'blocks_variation' => $blocks_variation,
923 + 'modules' => $modules,
688 924 'jetpack' => array(
689 925 'is_active' => Jetpack::is_connection_ready(),
690 926 'is_current_user_connected' => $is_current_user_connected,
691 927 /** This filter is documented in class.jetpack-gutenberg.php */
@@ -693,8 +929,27 @@
693 929 'is_private_site' => $status->is_private_site(),
694 930 'is_coming_soon' => $status->is_coming_soon(),
695 931 'is_offline_mode' => $status->is_offline_mode(),
696 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 + ) : null,
946 + // this is the equivalent of JP initial state siteData.showMyJetpack (class-jetpack-redux-state-helper)
947 + // used to determine if we can link to My Jetpack from the block editor
948 + 'is_my_jetpack_available' => My_Jetpack_Initializer::should_initialize(),
949 + 'jetpack_plan' => array(
950 + 'data' => $jetpack_plan['product_slug'],
951 + ),
697 952 /**
698 953 * Enable the RePublicize UI in the block editor context.
699 954 *
700 955 * @module publicize
@@ -699,18 +954,13 @@
699 954 *
700 955 * @module publicize
701 956 *
702 957 * @since 10.3.0
703 - * @deprecated $$next_version$$ This is a feature flag that is no longer used.
958 + * @deprecated 11.5 This is a feature flag that is no longer used.
704 959 *
705 960 * @param bool true Enable the RePublicize UI in the block editor context. Defaults to true.
706 961 */
707 962 'republicize_enabled' => apply_filters( 'jetpack_block_editor_republicize_feature', true ),
708 - /**
709 - * Prevent the registration of the blocks from extensions/blocks/contact-form
710 - * if the Forms package is enabled.
711 - */
712 - 'is_form_package_enabled' => apply_filters( 'jetpack_contact_form_use_package', true ),
713 963 ),
714 964 'siteFragment' => $status->get_site_suffix(),
715 965 'adminUrl' => esc_url( admin_url() ),
716 966 'tracksUserData' => $user_data,
@@ -718,27 +968,23 @@
718 968 'allowedMimeTypes' => wp_get_mime_types(),
719 969 'siteLocale' => str_replace( '_', '-', get_locale() ),
720 970 'ai-assistant' => $ai_assistant_state,
721 971 'screenBase' => $screen_base,
972 + /**
973 + * Add your own feature flags to the block editor.
974 + *
975 + * You can access the feature flags in the block editor via hasFeatureFlag( 'your-feature-flag' ) function.
976 + *
977 + * @since 14.8
978 + *
979 + * @param array true Enable the RePublicize UI in the block editor context. Defaults to true.
980 + */
981 + 'feature_flags' => apply_filters( 'jetpack_block_editor_feature_flags', array() ),
982 + 'pluginBasePath' => plugins_url( '', Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
722 983 );
723 984
724 - if ( Jetpack::is_module_active( 'publicize' ) && function_exists( 'publicize_init' ) ) {
725 - $publicize = publicize_init();
726 - $sig_settings = new Automattic\Jetpack\Publicize\Social_Image_Generator\Settings();
727 - $initial_state['social'] = array(
728 - 'sharesData' => $publicize->get_publicize_shares_info( $blog_id ),
729 - 'hasPaidPlan' => $publicize->has_paid_plan(),
730 - 'isEnhancedPublishingEnabled' => $publicize->has_enhanced_publishing_feature(),
731 - 'isSocialImageGeneratorAvailable' => $sig_settings->is_available(),
732 - 'isSocialImageGeneratorEnabled' => $sig_settings->is_enabled(),
733 - 'dismissedNotices' => $publicize->get_dismissed_notices(),
734 - 'isInstagramConnectionSupported' => $publicize->has_instagram_connection_feature(),
735 - 'isMastodonConnectionSupported' => $publicize->has_mastodon_connection_feature(),
736 - );
737 - }
738 -
739 985 wp_localize_script(
740 - 'jetpack-blocks-editor',
986 + Shared_Stores_Assets::SCRIPT_HANDLE,
741 987 'Jetpack_Editor_Initial_State',
742 988 $initial_state
743 989 );
744 990
@@ -746,96 +992,386 @@
746 992 Connection_Initial_State::render_script( 'jetpack-blocks-editor' );
747 993 }
748 994
749 995 /**
750 - * Add the Gutenberg editor stylesheet to iframed editors, such as the site editor,
751 - * which don't have access to stylesheets added with `wp_enqueue_style`.
996 + * Block feature names in the `no-post-editor` preset (extensions/index.json): blocks
997 + * whose editor bundle is usable outside the post editor, so they appear in front-end
998 + * block editors such as P2. These must never be deferred (see self::$lazy_blocks and
999 + * self::load_independent_blocks()).
752 1000 *
753 - * This workaround is currently used by WordPress.com Simple and Atomic sites.
1001 + * @since 16.2
754 1002 *
755 - * @since 10.7
1003 + * @return string[] Feature names, or an empty array when the preset is unavailable.
1004 + */
1005 + private static function get_no_post_editor_extensions() {
1006 + $preset = self::get_preset();
1007 + if ( is_object( $preset ) && isset( $preset->{'no-post-editor'} ) && is_array( $preset->{'no-post-editor'} ) ) {
1008 + return $preset->{'no-post-editor'};
1009 + }
1010 + return array();
1011 + }
1012 +
1013 + /**
1014 + * Some blocks do not depend on a specific module,
1015 + * and can consequently be loaded outside of the usual modules.
1016 + * We will look for such modules in the extensions/ directory.
756 1017 *
1018 + * @since 7.1.0
1019 + * @since 16.0 Pure display blocks are deferred on front-end requests and registered on first render.
1020 + * @since 16.2 Blocks in the `no-post-editor` preset are never deferred, so front-end editors (e.g. P2) keep them.
1021 + * @see wp_common_block_scripts_and_styles()
1022 + */
1023 + public static function load_independent_blocks() {
1024 + if ( self::should_load() ) {
1025 + /**
1026 + * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
1027 + * If available, load them.
1028 + */
1029 + $directories = array( 'blocks', 'plugins', 'extended-blocks' );
1030 +
1031 + /*
1032 + * On plain front-end requests, defer the registration PHP of pure display
1033 + * blocks (see self::$lazy_blocks) until the block is actually encountered
1034 + * while rendering. The block editor, the block-types REST endpoint and
1035 + * server-side rendering all run in a "block-editor context" and keep loading
1036 + * every block eagerly, so their behavior is unchanged.
1037 + */
1038 + $defer = ! self::is_block_editor_context();
1039 +
1040 + /*
1041 + * Front-end block editors (e.g. P2) render the inserter on a plain front-end
1042 + * request, so is_block_editor_context() is false there, yet a block must be
1043 + * registered on `init` for get_availability() to report it and keep it in the
1044 + * inserter. Never defer a block that ships in the `no-post-editor` preset —
1045 + * those are precisely the blocks usable outside the post editor.
1046 + */
1047 + $no_post_editor_blocks = $defer ? self::get_no_post_editor_extensions() : array();
1048 +
1049 + foreach ( static::get_extensions() as $extension ) {
1050 + if (
1051 + $defer
1052 + && in_array( $extension, self::$lazy_blocks, true )
1053 + && ! in_array( $extension, $no_post_editor_blocks, true )
1054 + ) {
1055 + self::$deferred_blocks[ $extension ] = true;
1056 + continue;
1057 + }
1058 +
1059 + foreach ( $directories as $dirname ) {
1060 + $path = JETPACK__PLUGIN_DIR . "extensions/{$dirname}/{$extension}/{$extension}.php";
1061 +
1062 + if ( file_exists( $path ) ) {
1063 + include_once $path;
1064 + continue 2;
1065 + }
1066 + }
1067 + }
1068 +
1069 + if ( ! empty( self::$deferred_blocks ) ) {
1070 + add_filter( 'pre_render_block', array( __CLASS__, 'lazy_register_deferred_block' ), 10, 3 );
1071 + }
1072 + }
1073 + }
1074 +
1075 + /**
1076 + * Register deferred blocks present in a top-level block's subtree before it renders.
1077 + *
1078 + * Hooked to `pre_render_block`. For a top-level block ($parent_block is null) the
1079 + * filter fires before core builds the block's WP_Block object, so we walk the whole
1080 + * parsed subtree and register every deferred Jetpack block it contains. This must
1081 + * happen at the top level: core resolves an inner block's `block_type` when it
1082 + * constructs that inner WP_Block, which is *before* the inner block's own
1083 + * `pre_render_block` fires — so registering a deferred dynamic block only when its
1084 + * own inner filter fires would be too late and its render_callback would be skipped.
1085 + * Inner-block invocations (non-null $parent_block) are ignored because the top-level
1086 + * walk has already handled the whole tree. Returns $pre_render untouched.
1087 + *
1088 + * @since 16.0
1089 + *
1090 + * @param string|null $pre_render The pre-rendered content. Default null.
1091 + * @param array $parsed_block The parsed block being rendered.
1092 + * @param \WP_Block|null $parent_block Parent block, or null for a top-level block.
1093 + *
1094 + * @return string|null Unchanged $pre_render.
1095 + */
1096 + public static function lazy_register_deferred_block( $pre_render, $parsed_block, $parent_block = null ) {
1097 + // Respect any earlier short-circuit, only act on top-level blocks, and stop
1098 + // once every deferred block on the page has been registered.
1099 + if ( null !== $pre_render || null !== $parent_block || empty( self::$deferred_blocks ) ) {
1100 + return $pre_render;
1101 + }
1102 +
1103 + self::register_deferred_blocks_in_subtree( $parsed_block );
1104 +
1105 + return $pre_render;
1106 + }
1107 +
1108 + /**
1109 + * Recursively register any deferred Jetpack blocks found in a parsed block subtree.
1110 + *
1111 + * @since 16.0
1112 + *
1113 + * @param array $parsed_block A parsed block (with optional `innerBlocks`).
1114 + * @param array $seen_refs Reusable-block IDs already visited, to guard against cycles.
1115 + *
757 1116 * @return void
758 1117 */
759 - public static function add_iframed_editor_style() {
760 - if ( ! self::should_load() ) {
1118 + private static function register_deferred_blocks_in_subtree( $parsed_block, &$seen_refs = array() ) {
1119 + if ( empty( self::$deferred_blocks ) ) {
761 1120 return;
762 1121 }
763 1122
764 - global $pagenow;
765 - if ( ! isset( $pagenow ) ) {
766 - return;
1123 + $block_name = $parsed_block['blockName'] ?? '';
1124 + if ( '' !== $block_name && str_starts_with( $block_name, 'jetpack/' ) ) {
1125 + $feature = substr( $block_name, strlen( 'jetpack/' ) );
1126 + if ( ! empty( self::$deferred_blocks[ $feature ] ) ) {
1127 + // Only attempt registration once per block, whether or not it succeeds
1128 + // (a block guarded by a connection/module check may intentionally not register).
1129 + unset( self::$deferred_blocks[ $feature ] );
1130 +
1131 + if ( ! self::is_registered( $block_name ) ) {
1132 + self::load_and_register_deferred_block( $feature );
1133 + }
1134 + }
767 1135 }
768 1136
769 - // Pre 13.7 pages that still need to be supported if < 13.7 is
770 - // still installed.
771 - $allowed_old_pages = array( 'admin.php', 'themes.php' );
772 - $is_old_site_editor_page = in_array( $pagenow, $allowed_old_pages, true ) && isset( $_GET['page'] ) && 'gutenberg-edit-site' === $_GET['page']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
773 - // For Gutenberg > 13.7, the core `site-editor.php` route is used instead
774 - $is_site_editor_page = 'site-editor.php' === $pagenow;
1137 + /*
1138 + * A synced pattern / reusable block (core/block) keeps its content in a separate
1139 + * wp_block post that core only parses at render time (render_block_core_block),
1140 + * so it is absent from this parsed tree. Resolve the reference and recurse so a
1141 + * deferred block inside the pattern is registered before core builds its WP_Block.
1142 + *
1143 + * core/navigation has the same ref-based hidden-content shape (a wp_navigation
1144 + * post) but is intentionally not handled: none of the deferred blocks can be
1145 + * inserted into a navigation menu through the editor, and resolving the ref would
1146 + * add a get_post()/parse_blocks() on essentially every front-end page (menus are
1147 + * near-ubiquitous) for a case that cannot occur without hand-authored markup.
1148 + */
1149 + if ( 'core/block' === $block_name && ! empty( $parsed_block['attrs']['ref'] ) ) {
1150 + $ref = (int) $parsed_block['attrs']['ref'];
1151 + if ( ! isset( $seen_refs[ $ref ] ) ) {
1152 + $seen_refs[ $ref ] = true;
1153 + $reusable_block = get_post( $ref );
1154 + if ( $reusable_block instanceof \WP_Post && 'wp_block' === $reusable_block->post_type ) {
1155 + foreach ( parse_blocks( $reusable_block->post_content ) as $inner_block ) {
1156 + self::register_deferred_blocks_in_subtree( $inner_block, $seen_refs );
1157 + }
1158 + }
1159 + }
1160 + }
775 1161
776 - $should_skip_adding_styles = ! $is_site_editor_page && ! $is_old_site_editor_page;
777 - if ( $should_skip_adding_styles ) {
1162 + if ( ! empty( $parsed_block['innerBlocks'] ) ) {
1163 + foreach ( $parsed_block['innerBlocks'] as $inner_block ) {
1164 + self::register_deferred_blocks_in_subtree( $inner_block, $seen_refs );
1165 + }
1166 + }
1167 + }
1168 +
1169 + /**
1170 + * Include a deferred block's registration PHP and run the `init` callback it
1171 + * adds, immediately.
1172 + *
1173 + * The block files register themselves with `add_action( 'init', … )`. By render
1174 + * time `init` has long since fired, so including the file is not enough on its
1175 + * own: we capture the callback(s) the include adds to `init` and invoke them now.
1176 + * Only blocks in self::$lazy_blocks reach this path, and each adds exactly its
1177 + * own registration callback to `init`, so this runs that single registration.
1178 + *
1179 + * @since 16.0
1180 + *
1181 + * @param string $feature Block feature name (directory name without the `jetpack/` prefix).
1182 + *
1183 + * @return void
1184 + */
1185 + private static function load_and_register_deferred_block( $feature ) {
1186 + $path = JETPACK__PLUGIN_DIR . "extensions/blocks/{$feature}/{$feature}.php";
1187 + if ( ! file_exists( $path ) ) {
1188 + self::warn_about_deferred_block_registration_failure( $feature, 'missing block registration file' );
778 1189 return;
779 1190 }
780 1191
781 - $blocks_dir = self::get_blocks_directory();
782 - $blocks_variation = self::blocks_variation();
1192 + global $wp_filter;
783 1193
784 - if ( 'production' !== $blocks_variation ) {
785 - $blocks_env = '-' . esc_attr( $blocks_variation );
786 - } else {
787 - $blocks_env = '';
1194 + $before = isset( $wp_filter['init'] ) ? $wp_filter['init']->callbacks : array();
1195 +
1196 + include_once $path;
1197 +
1198 + if ( ! isset( $wp_filter['init'] ) ) {
1199 + self::warn_about_deferred_block_registration_failure( $feature, 'block file did not add an init callback' );
1200 + return;
788 1201 }
789 1202
790 - $path = "{$blocks_dir}editor{$blocks_env}.css";
791 - $dir = dirname( JETPACK__PLUGIN_FILE );
1203 + $registered_callback = false;
792 1204
793 - if ( file_exists( "$dir/$path" ) ) {
794 - if ( is_rtl() ) {
795 - $rtlcsspath = substr( $path, 0, -4 ) . '.rtl.css';
796 - if ( file_exists( "$dir/$rtlcsspath" ) ) {
797 - $path = $rtlcsspath;
1205 + // Run (and then detach) any callback the include just added to `init`.
1206 + foreach ( $wp_filter['init']->callbacks as $priority => $callbacks ) {
1207 + foreach ( $callbacks as $id => $callback ) {
1208 + if ( isset( $before[ $priority ][ $id ] ) ) {
1209 + continue;
798 1210 }
1211 + $registered_callback = true;
1212 + if ( is_callable( $callback['function'] ) ) {
1213 + call_user_func( $callback['function'] );
1214 + }
1215 + remove_action( 'init', $callback['function'], $priority );
799 1216 }
1217 + }
800 1218
801 - $url = Assets::normalize_path( plugins_url( $path, JETPACK__PLUGIN_FILE ) );
802 - $url = add_query_arg( 'minify', 'false', $url );
1219 + if ( ! $registered_callback ) {
1220 + self::warn_about_deferred_block_registration_failure( $feature, 'block file did not add a new init callback' );
1221 + }
1222 + }
803 1223
804 - add_editor_style( $url );
1224 + /**
1225 + * Surface lazy-registration mistakes during debugging without adding front-end noise.
1226 + *
1227 + * @since 16.0
1228 + *
1229 + * @param string $feature Block feature name (directory name without the `jetpack/` prefix).
1230 + * @param string $reason Short reason for the failure.
1231 + *
1232 + * @return void
1233 + */
1234 + private static function warn_about_deferred_block_registration_failure( $feature, $reason ) {
1235 + if ( ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) || ! function_exists( '_doing_it_wrong' ) ) {
1236 + return;
805 1237 }
1238 +
1239 + _doing_it_wrong(
1240 + __METHOD__,
1241 + sprintf(
1242 + /* translators: 1: Jetpack block feature name. 2: Failure reason. */
1243 + esc_html__( 'Lazy Jetpack block registration failed for "%1$s": %2$s.', 'jetpack' ),
1244 + esc_html( $feature ),
1245 + esc_html( $reason )
1246 + ),
1247 + '16.0'
1248 + );
806 1249 }
807 1250
808 1251 /**
809 - * Some blocks do not depend on a specific module,
810 - * and can consequently be loaded outside of the usual modules.
811 - * We will look for such modules in the extensions/ directory.
1252 + * Determine whether the current request is a block-editor context that needs
1253 + * every Jetpack block loaded eagerly on `init`.
812 1254 *
813 - * @since 7.1.0
814 - * @see wp_common_block_scripts_and_styles()
1255 + * Returns true for admin, REST, cron, WP-CLI and XML-RPC requests so the editor,
1256 + * the `/wp/v2/block-types` endpoint and server-side rendering keep seeing the full
1257 + * set of blocks. Returns false only for plain front-end web requests, where pure
1258 + * display blocks are registered just-in-time as they render.
1259 + *
1260 + * This runs at module-load time (around after_setup_theme), before core defines
1261 + * REST_REQUEST during parse_request, so self-hosted and Atomic REST requests are
1262 + * detected from the request URL instead of the constant. That URL check cannot
1263 + * work on WordPress.com Simple: its public API filters `rest_url_prefix` to an
1264 + * empty string, so rest_get_url_prefix() returns '' and the REST roots computed
1265 + * below collapse to '//', which no request path can match. Simple's requests are
1266 + * detected via REST_API_REQUEST instead, which its API entry points define before
1267 + * wp-load.php runs.
1268 + *
1269 + * @since 16.0
1270 + *
1271 + * @return bool True for block-editor (non-front-end) contexts, false for plain front-end requests.
815 1272 */
816 - public static function load_independent_blocks() {
817 - if ( self::should_load() ) {
818 - /**
819 - * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
820 - * If available, load them.
821 - */
822 - $directories = array( 'blocks', 'plugins', 'extended-blocks', 'shared', 'store' );
1273 + private static function is_block_editor_context() {
1274 + if ( is_admin() ) {
1275 + return true;
1276 + }
823 1277
824 - foreach ( static::get_extensions() as $extension ) {
825 - foreach ( $directories as $dirname ) {
826 - $path = JETPACK__PLUGIN_DIR . "extensions/{$dirname}/{$extension}/{$extension}.php";
1278 + /*
1279 + * Treat any non-front-end execution context as block-editor. These are not the
1280 + * front-end hot path this gate optimizes, and some still render block content
1281 + * (e.g. cron-generated subscription e-mails) that depends on full registration.
1282 + *
1283 + * Core defines REST_REQUEST during parse_request, after this runs, so it is
1284 + * normally still unset here; it is checked anyway so the result stays correct
1285 + * if this is ever called later in the request. REST_API_REQUEST is what catches
1286 + * WordPress.com Simple, where the URL check below cannot work at all (see the
1287 + * method docblock).
1288 + */
1289 + if (
1290 + Constants::is_true( 'DOING_CRON' )
1291 + || Constants::is_true( 'WP_CLI' )
1292 + || Constants::is_true( 'XMLRPC_REQUEST' )
1293 + || Constants::is_true( 'REST_REQUEST' )
1294 + || Constants::is_true( 'REST_API_REQUEST' )
1295 + ) {
1296 + return true;
1297 + }
827 1298
828 - if ( file_exists( $path ) ) {
829 - include_once $path;
830 - continue 2;
831 - }
1299 + /*
1300 + * No request URI means a non-web execution context (WP-CLI without it, test
1301 + * suites, etc.). A genuine front-end page request always carries one, so it
1302 + * costs nothing on the hot path to treat the empty case as "load eagerly".
1303 + */
1304 + $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
1305 + if ( '' === $request_uri ) {
1306 + return true;
1307 + }
1308 +
1309 + /*
1310 + * Anchor the REST root (home path + prefix) at the start of the request path,
1311 + * so a front-end URL that merely carries the prefix in a query value or a
1312 + * deeper path segment is not misread as a REST request. home_url() is used
1313 + * rather than rest_url() so detection does not depend on permalink structure.
1314 + * Both the rewritten `/wp-json/` form and the index-permalink
1315 + * `/index.php/wp-json/` form (used when the site lacks pretty permalinks) are
1316 + * matched.
1317 + */
1318 + $path = (string) wp_parse_url( $request_uri, PHP_URL_PATH );
1319 + if ( '' !== $path ) {
1320 + $home_path = trailingslashit( (string) wp_parse_url( home_url(), PHP_URL_PATH ) );
1321 + $rest_prefix = trailingslashit( rest_get_url_prefix() );
1322 + $rest_roots = array(
1323 + $home_path . $rest_prefix,
1324 + $home_path . 'index.php/' . $rest_prefix,
1325 + );
1326 + foreach ( $rest_roots as $rest_root ) {
1327 + if ( str_starts_with( trailingslashit( $path ), $rest_root ) ) {
1328 + return true;
832 1329 }
833 1330 }
834 1331 }
1332 +
1333 + // Plain-permalink REST uses a `rest_route` query var; match the exact key.
1334 + $query = (string) wp_parse_url( $request_uri, PHP_URL_QUERY );
1335 + if ( '' !== $query ) {
1336 + parse_str( $query, $query_vars );
1337 + if ( ! empty( $query_vars['rest_route'] ) ) {
1338 + return true;
1339 + }
1340 + }
1341 +
1342 + return false;
835 1343 }
836 1344
837 1345 /**
1346 + * Editor-oriented extensions that nonetheless have front-end side effects and must
1347 + * therefore keep loading on every request, even outside the block editor.
1348 + *
1349 + * Keyed by directory ('plugins' / 'extended-blocks') for an exact, intentional match.
1350 + *
1351 + * @since 16.0
1352 + *
1353 + * @var array
1354 + */
1355 + private static $frontend_editor_extensions = array(
1356 + 'plugins' => array(
1357 + // Mounts the Reader Chat widget on the front end (wp_enqueue_scripts) and
1358 + // wires the AI sidebar/provider registration AI Assistant depends on.
1359 + 'ai-assistant-plugin',
1360 + // Signals Big Sky via the jetpack_image_studio_enabled filter on `init`,
1361 + // which can run on the front end.
1362 + 'image-studio',
1363 + ),
1364 + 'extended-blocks' => array(
1365 + // Registers the videopress/video block on `init`, required to render it on the front end.
1366 + 'videopress-video',
1367 + // Registers the `premium-content/container` plan availability that the Premium Content
1368 + // block's front-end render reads via required_plan_checks(); skipping it breaks the paywall.
1369 + 'premium-content-container',
1370 + ),
1371 + );
1372 +
1373 + /**
838 1374 * Loads PHP components of block editor extensions.
839 1375 *
840 1376 * @since 8.9.0
841 1377 */
@@ -846,15 +1382,30 @@
846 1382 'extended-blocks',
847 1383 'plugins',
848 1384 );
849 1385
1386 + $is_editor_context = self::is_block_editor_context();
1387 +
850 1388 // Collect the extension paths.
851 1389 foreach ( $extensions_to_load as $extension_to_load ) {
852 1390 $extensions_folder = glob( JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/*' );
853 1391
1392 + $frontend_allow_list = self::$frontend_editor_extensions[ $extension_to_load ] ?? array();
1393 +
854 1394 // Require each of the extension files, in case it exists.
855 1395 foreach ( $extensions_folder as $extension_folder ) {
856 - $name = basename( $extension_folder );
1396 + $name = basename( $extension_folder );
1397 +
1398 + /*
1399 + * On plain front-end requests, only load extensions that have known
1400 + * front-end side effects. Editor-only extensions are skipped here and
1401 + * loaded on admin/REST (block-editor) requests instead, reducing the
1402 + * per-front-end-request PHP/opcache footprint.
1403 + */
1404 + if ( ! $is_editor_context && ! in_array( $name, $frontend_allow_list, true ) ) {
1405 + continue;
1406 + }
1407 +
857 1408 $extension_file_path = JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/' . $name . '/' . $name . '.php';
858 1409
859 1410 if ( file_exists( $extension_file_path ) ) {
860 1411 include_once $extension_file_path;
@@ -864,24 +1415,8 @@
864 1415 }
865 1416 }
866 1417
867 1418 /**
868 - * Get CSS classes for a block.
869 - *
870 - * @since 7.7.0
871 - *
872 - * @param string $slug Block slug.
873 - * @param array $attr Block attributes.
874 - * @param array $extra Potential extra classes you may want to provide.
875 - *
876 - * @return string $classes List of CSS classes for a block.
877 - */
878 - public static function block_classes( $slug, $attr, $extra = array() ) {
879 - _deprecated_function( __METHOD__, '9.0.0', 'Automattic\\Jetpack\\Blocks::classes' );
880 - return Blocks::classes( $slug, $attr, $extra );
881 - }
882 -
883 - /**
884 1419 * Determine whether a site should use the default set of blocks, or a custom set.
885 1420 * Possible variations are currently beta, experimental, and production.
886 1421 *
887 1422 * @since 8.1.0
@@ -977,9 +1512,9 @@
977 1512 * Get a list of extensions available for the variation you chose.
978 1513 *
979 1514 * @since 8.1.0
980 1515 *
981 - * @param obj $preset_extensions_manifest List of extensions available in Jetpack.
1516 + * @param object $preset_extensions_manifest List of extensions available in Jetpack.
982 1517 * @param string $blocks_variation Subset of blocks. production|beta|experimental.
983 1518 *
984 1519 * @return array $preset_extensions Array of extensions for that variation
985 1520 */
@@ -1051,11 +1586,11 @@
1051 1586
1052 1587 // Normalize URL.
1053 1588 $url = sprintf(
1054 1589 '%s://%s%s%s',
1055 - isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
1590 + $url_components['scheme'] ?? 'https',
1056 1591 $url_components['host'],
1057 - isset( $url_components['path'] ) ? $url_components['path'] : '/',
1592 + $url_components['path'] ?? '/',
1058 1593 isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
1059 1594 );
1060 1595
1061 1596 if ( ! empty( $url_components['fragment'] ) ) {
@@ -1243,8 +1778,12 @@
1243 1778 }
1244 1779
1245 1780 if ( ! empty( $features_data['available'][ $slug ] ) ) {
1246 1781 $plan = $features_data['available'][ $slug ][0];
1782 + } elseif ( isset( self::$wpcom_minimum_plan_fallbacks[ $slug ] ) ) {
1783 + // Fallback for features with conditional availability (e.g., sticker-based gating)
1784 + // that don't appear in features_data['available'].
1785 + $plan = self::$wpcom_minimum_plan_fallbacks[ $slug ];
1247 1786 }
1248 1787 } else {
1249 1788 // Jetpack sites.
1250 1789 $plan = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
@@ -1271,15 +1810,15 @@
1271 1810 return function ( $prepared_attributes, $block_content, $block ) use ( $render_callback, $slug ) {
1272 1811 $availability = self::get_cached_availability();
1273 1812 $bare_slug = self::remove_extension_prefix( $slug );
1274 1813 if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1275 - return call_user_func( $render_callback, $prepared_attributes, $block_content );
1814 + return call_user_func( $render_callback, $prepared_attributes, $block_content, $block );
1276 1815 }
1277 1816
1278 1817 // A preview of the block is rendered for admins on the frontend with an upgrade nudge.
1279 1818 if ( isset( $availability[ $bare_slug ] ) ) {
1280 1819 if ( self::should_show_frontend_preview( $availability[ $bare_slug ] ) ) {
1281 - $block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content );
1820 + $block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content, $block );
1282 1821
1283 1822 // If the upgrade nudge isn't already being displayed by a parent block, display the nudge.
1284 1823 if ( isset( $block->attributes['shouldDisplayFrontendBanner'] ) && $block->attributes['shouldDisplayFrontendBanner'] ) {
1285 1824 $upgrade_nudge = self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
@@ -1305,9 +1844,9 @@
1305 1844 *
1306 1845 * @return string
1307 1846 */
1308 1847 public static function display_deprecated_block_message( $block_content, $block ) {
1309 - if ( in_array( $block['blockName'], self::$deprecated_blocks, true ) ) {
1848 + if ( isset( $block['blockName'] ) && in_array( $block['blockName'], self::$deprecated_blocks, true ) ) {
1310 1849 if ( current_user_can( 'edit_posts' ) ) {
1311 1850 $block_content = self::notice(
1312 1851 __( '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' ),
1313 1852 'warning',
@@ -1319,8 +1858,67 @@
1319 1858 }
1320 1859
1321 1860 return $block_content;
1322 1861 }
1862 +
1863 + /**
1864 + * Register block metadata collection for Jetpack blocks.
1865 + * This allows for more efficient block metadata loading by avoiding
1866 + * individual block.json file reads at runtime.
1867 + *
1868 + * Uses wp_register_block_metadata_collection() if the manifest file
1869 + * exists. The manifest file is auto-generated during the build process.
1870 + *
1871 + * Runs on plugins_loaded to ensure registration happens before individual
1872 + * blocks register themselves on init.
1873 + *
1874 + * @static
1875 + * @since 14.1
1876 + * @return void
1877 + */
1878 + public static function register_block_metadata_collection() {
1879 + $meta_file_path = JETPACK__PLUGIN_DIR . '_inc/blocks/blocks-manifest.php';
1880 + if ( file_exists( $meta_file_path ) ) {
1881 + wp_register_block_metadata_collection(
1882 + JETPACK__PLUGIN_DIR . '_inc/blocks/',
1883 + $meta_file_path
1884 + );
1885 + }
1886 + }
1887 +
1888 + /**
1889 + * Set the JS loading strategy for a block.
1890 + *
1891 + * @param string $block_name The block name.
1892 + * @param array|bool $strategy The JS loading strategy.
1893 + *
1894 + * @since 15.0
1895 + */
1896 + public static function set_block_js_loading_strategy( $block_name, $strategy ) {
1897 + self::$block_js_loading_strategies[ $block_name ] = $strategy;
1898 + }
1899 +
1900 + /**
1901 + * Get the JS loading strategy for a block.
1902 + *
1903 + * @param string $block_name The block name.
1904 + *
1905 + * @return array|bool The JS loading strategy for the block.
1906 + *
1907 + * @since 15.0
1908 + */
1909 + public static function get_block_js_loading_strategy( $block_name ) {
1910 + $strategy = array(
1911 + 'strategy' => 'defer',
1912 + 'in_footer' => true,
1913 + );
1914 +
1915 + if ( isset( self::$block_js_loading_strategies[ $block_name ] ) ) {
1916 + $strategy = self::$block_js_loading_strategies[ $block_name ];
1917 + }
1918 +
1919 + return $strategy;
1920 + }
1323 1921 }
1324 1922
1325 1923 if ( ( new Host() )->is_woa_site() ) {
1326 1924 /**
@@ -1330,12 +1928,5 @@
1330 1928 *
1331 1929 * More doc: https://github.com/Automattic/jetpack/blob/trunk/projects/plugins/jetpack/extensions/README.md#upgrades-for-blocks
1332 1930 */
1333 1931 add_filter( 'jetpack_block_editor_enable_upgrade_nudge', '__return_true' );
1334 -
1335 - /**
1336 - * Load block editor styles inline for iframed editors.
1337 - *
1338 - * @see paYJgx-1Kl-p2
1339 - */
1340 - add_action( 'admin_init', array( 'Jetpack_Gutenberg', 'add_iframed_editor_style' ) );
1341 1932 }