PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 13.1.2
Jetpack – WP Security, Backup, Speed, & Growth v13.1.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 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / class.jetpack-gutenberg.php
class.jetpack-gutenberg.php
1,320 lines 42.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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\Blocks;
11 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
12 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13 use Automattic\Jetpack\Constants;
14 use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
15 use Automattic\Jetpack\Publicize\Jetpack_Social_Settings\Dismissed_Notices;
16 use Automattic\Jetpack\Status;
17 use Automattic\Jetpack\Status\Host;
18
19 // phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move the functions and such to some other file.
20
21 /**
22 * Wrapper function to safely register a gutenberg block type
23 *
24 * @deprecated 9.1.0 Use Automattic\\Jetpack\\Blocks::jetpack_register_block instead
25 *
26 * @see register_block_type
27 *
28 * @since 6.7.0
29 *
30 * @param string $slug Slug of the block.
31 * @param array $args Arguments that are passed into register_block_type.
32 *
33 * @return WP_Block_Type|false The registered block type on success, or false on failure.
34 */
35 function jetpack_register_block( $slug, $args = array() ) {
36 _deprecated_function( __METHOD__, '9.1.0', 'Automattic\\Jetpack\\Blocks::jetpack_register_block' );
37 return Blocks::jetpack_register_block( $slug, $args );
38 }
39
40 /**
41 * General Gutenberg editor specific functionality
42 */
43 class Jetpack_Gutenberg {
44
45 /**
46 * Only these extensions can be registered. Used to control availability of beta blocks.
47 *
48 * @var array|null Extensions allowed list or `null` if not initialized yet.
49 * @see static::get_extensions()
50 */
51 private static $extensions = null;
52
53 /**
54 * Keeps track of the reasons why a given extension is unavailable.
55 *
56 * @var array Extensions availability information
57 */
58 private static $availability = array();
59
60 /**
61 * A cached array of the fully processed availability data. Keeps track of
62 * reasons why an extension is unavailable or missing.
63 *
64 * @var array Extensions availability information.
65 */
66 private static $cached_availability = null;
67
68 /**
69 * Site-specific features available.
70 * Their calculation can be expensive and slow, so we're caching it for the request.
71 *
72 * @var array Site-specific features
73 */
74 private static $site_specific_features = array();
75
76 /**
77 * List of deprecated blocks.
78 *
79 * @var array List of deprecated blocks.
80 */
81 private static $deprecated_blocks = array(
82 'jetpack/revue',
83 );
84
85 /**
86 * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
87 * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
88 * optionally fall back to that.
89 *
90 * @param array $version_requirements An array containing the required Gutenberg version and, if known, the WordPress version that was released with this minimum version.
91 * @param string $slug The slug of the block or plugin that has the gutenberg version requirement.
92 *
93 * @since 8.3.0
94 *
95 * @return boolean True if the version of gutenberg required by the block or plugin is available.
96 */
97 public static function is_gutenberg_version_available( $version_requirements, $slug ) {
98 global $wp_version;
99
100 // Bail if we don't at least have the gutenberg version requirement, the WP version is optional.
101 if ( empty( $version_requirements['gutenberg'] ) ) {
102 return false;
103 }
104
105 // If running a local dev build of gutenberg plugin GUTENBERG_DEVELOPMENT_MODE is set so assume correct version.
106 if ( defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE ) {
107 return true;
108 }
109
110 $version_available = false;
111
112 // If running a production build of the gutenberg plugin then GUTENBERG_VERSION is set, otherwise if WP version
113 // with required version of Gutenberg is known check that.
114 if ( defined( 'GUTENBERG_VERSION' ) ) {
115 $version_available = version_compare( GUTENBERG_VERSION, $version_requirements['gutenberg'], '>=' );
116 } elseif ( ! empty( $version_requirements['wp'] ) ) {
117 $version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
118 }
119
120 if ( ! $version_available ) {
121 self::set_extension_unavailable(
122 $slug,
123 'incorrect_gutenberg_version',
124 array(
125 'required_feature' => $slug,
126 'required_version' => $version_requirements,
127 'current_version' => array(
128 'wp' => $wp_version,
129 'gutenberg' => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null,
130 ),
131 )
132 );
133 }
134
135 return $version_available;
136 }
137
138 /**
139 * Prepend the 'jetpack/' prefix to a block name
140 *
141 * @param string $block_name The block name.
142 *
143 * @return string The prefixed block name.
144 */
145 private static function prepend_block_prefix( $block_name ) {
146 return 'jetpack/' . $block_name;
147 }
148
149 /**
150 * Remove the 'jetpack/' or jetpack-' prefix from an extension name
151 *
152 * @param string $extension_name The extension name.
153 *
154 * @return string The unprefixed extension name.
155 */
156 public static function remove_extension_prefix( $extension_name ) {
157 if ( str_starts_with( $extension_name, 'jetpack/' ) || str_starts_with( $extension_name, 'jetpack-' ) ) {
158 return substr( $extension_name, strlen( 'jetpack/' ) );
159 }
160 return $extension_name;
161 }
162
163 /**
164 * Whether two arrays share at least one item
165 *
166 * @param array $a An array.
167 * @param array $b Another array.
168 *
169 * @return boolean True if $a and $b share at least one item
170 */
171 protected static function share_items( $a, $b ) {
172 return array_intersect( $a, $b ) !== array();
173 }
174
175 /**
176 * Set a (non-block) extension as available
177 *
178 * @param string $slug Slug of the extension.
179 */
180 public static function set_extension_available( $slug ) {
181 self::$availability[ self::remove_extension_prefix( $slug ) ] = true;
182 }
183
184 /**
185 * Set the reason why an extension (block or plugin) is unavailable
186 *
187 * @param string $slug Slug of the extension.
188 * @param string $reason A string representation of why the extension is unavailable.
189 * @param array $details A free-form array containing more information on why the extension is unavailable.
190 */
191 public static function set_extension_unavailable( $slug, $reason, $details = array() ) {
192 if (
193 // Extensions that require a plan may be eligible for upgrades.
194 'missing_plan' === $reason
195 && (
196 /**
197 * Filter 'jetpack_block_editor_enable_upgrade_nudge' with `true` to enable or `false`
198 * to disable paid feature upgrade nudges in the block editor.
199 *
200 * When this is changed to default to `true`, you should also update `modules/memberships/class-jetpack-memberships.php`
201 * See https://github.com/Automattic/jetpack/pull/13394#pullrequestreview-293063378
202 *
203 * @since 7.7.0
204 *
205 * @param boolean
206 */
207 ! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
208 /** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
209 || ! apply_filters( 'jetpack_show_promotions', true )
210 )
211 ) {
212 // The block editor may apply an upgrade nudge if `missing_plan` is the reason.
213 // Add a descriptive suffix to disable behavior but provide informative reason.
214 $reason .= '__nudge_disabled';
215 }
216
217 self::$availability[ self::remove_extension_prefix( $slug ) ] = array(
218 'reason' => $reason,
219 'details' => $details,
220 );
221 }
222
223 /**
224 * Used to initialize the class, no longer in use.
225 *
226 * @return void
227 * @deprecated 12.2 No longer needed.
228 */
229 public static function init() {
230 _deprecated_function( __METHOD__, '12.2' );
231 }
232
233 /**
234 * Resets the class to its original state
235 *
236 * Used in unit tests
237 *
238 * @return void
239 */
240 public static function reset() {
241 self::$extensions = null;
242 self::$availability = array();
243 self::$cached_availability = null;
244 }
245
246 /**
247 * Return the Gutenberg extensions (blocks and plugins) directory
248 *
249 * @return string The Gutenberg extensions directory
250 */
251 public static function get_blocks_directory() {
252 /**
253 * Filter to select Gutenberg blocks directory
254 *
255 * @since 6.9.0
256 *
257 * @param string default: '_inc/blocks/'
258 */
259 return apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
260 }
261
262 /**
263 * Checks for a given .json file in the blocks folder.
264 *
265 * @param string $preset The name of the .json file to look for.
266 *
267 * @return bool True if the file is found.
268 */
269 public static function preset_exists( $preset ) {
270 return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
271 }
272
273 /**
274 * Decodes JSON loaded from a preset file in the blocks folder
275 *
276 * @param string $preset The name of the .json file to load.
277 *
278 * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
279 */
280 public static function get_preset( $preset ) {
281 return json_decode(
282 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
283 file_get_contents( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' )
284 );
285 }
286
287 /**
288 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
289 *
290 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
291 */
292 public static function get_jetpack_gutenberg_extensions_allowed_list() {
293 $preset_extensions_manifest = self::preset_exists( 'index' )
294 ? self::get_preset( 'index' )
295 : (object) array();
296 $blocks_variation = self::blocks_variation();
297
298 return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
299 }
300
301 /**
302 * Returns a diff from a combined list of allowed extensions and extensions determined to be excluded
303 *
304 * @param array $allowed_extensions An array of allowed extensions.
305 *
306 * @return array A list of blocks: eg array( 'publicize', 'markdown' )
307 */
308 public static function get_available_extensions( $allowed_extensions = null ) {
309 $exclusions = get_option( 'jetpack_excluded_extensions', array() );
310 $allowed_extensions = $allowed_extensions === null ? self::get_jetpack_gutenberg_extensions_allowed_list() : $allowed_extensions;
311
312 return array_diff( $allowed_extensions, $exclusions );
313 }
314
315 /**
316 * Return true if the extension has been registered and there's nothing in the availablilty array.
317 *
318 * @param string $extension The name of the extension.
319 *
320 * @return bool whether the extension has been registered and there's nothing in the availablilty array.
321 */
322 public static function is_registered_and_no_entry_in_availability( $extension ) {
323 return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
324 }
325
326 /**
327 * Return true if the extension has a true entry in the availablilty array.
328 *
329 * @param string $extension The name of the extension.
330 *
331 * @return bool whether the extension has a true entry in the availablilty array.
332 */
333 public static function is_available( $extension ) {
334 return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
335 }
336
337 /**
338 * Get the availability of each block / plugin, or return the cached availability
339 * if it has already been calculated. Avoids re-registering extensions when not
340 * necessary.
341 *
342 * @return array A list of block and plugins and their availability status.
343 */
344 public static function get_cached_availability() {
345 if ( null === self::$cached_availability ) {
346 self::$cached_availability = self::get_availability();
347 }
348 return self::$cached_availability;
349 }
350
351 /**
352 * Get availability of each block / plugin.
353 *
354 * @return array A list of block and plugins and their availablity status
355 */
356 public static function get_availability() {
357 /**
358 * Fires before Gutenberg extensions availability is computed.
359 *
360 * In the function call you supply, use `Blocks::jetpack_register_block()` to set a block as available.
361 * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
362 * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
363 * but marked as unavailable).
364 *
365 * @since 7.0.0
366 */
367 do_action( 'jetpack_register_gutenberg_extensions' );
368
369 $available_extensions = array();
370
371 foreach ( static::get_extensions() as $extension ) {
372 $is_available = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
373 $available_extensions[ $extension ] = array(
374 'available' => $is_available,
375 );
376
377 if ( ! $is_available ) {
378 $reason = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
379 $details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
380 $available_extensions[ $extension ]['unavailable_reason'] = $reason;
381 $available_extensions[ $extension ]['details'] = $details;
382 }
383 }
384
385 return $available_extensions;
386 }
387
388 /**
389 * Return the list of extensions that are available.
390 *
391 * @since 11.9
392 *
393 * @return array A list of block and plugins and their availability status.
394 */
395 public static function get_extensions() {
396 if ( ! static::should_load() ) {
397 return array();
398 }
399
400 if ( null === self::$extensions ) {
401 /**
402 * Filter the list of block editor extensions that are available through Jetpack.
403 *
404 * @since 7.0.0
405 *
406 * @param array
407 */
408 self::$extensions = apply_filters( 'jetpack_set_available_extensions', self::get_available_extensions() );
409 }
410
411 return self::$extensions;
412 }
413
414 /**
415 * Check if an extension/block is already registered
416 *
417 * @since 7.2
418 *
419 * @param string $slug Name of extension/block to check.
420 *
421 * @return bool
422 */
423 public static function is_registered( $slug ) {
424 return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
425 }
426
427 /**
428 * Check if Gutenberg editor is available
429 *
430 * @since 6.7.0
431 *
432 * @return bool
433 */
434 public static function is_gutenberg_available() {
435 return true;
436 }
437
438 /**
439 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
440 *
441 * Loading blocks and plugins is enabled by default and may be disabled via filter:
442 * add_filter( 'jetpack_gutenberg', '__return_false' );
443 *
444 * @since 6.9.0
445 *
446 * @return bool
447 */
448 public static function should_load() {
449 if ( ! Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
450 return false;
451 }
452
453 if ( get_option( 'jetpack_blocks_disabled', false ) ) {
454 return false;
455 }
456
457 /**
458 * Filter to disable Gutenberg blocks
459 *
460 * @since 6.5.0
461 *
462 * @param bool true Whether to load Gutenberg blocks
463 */
464 return (bool) apply_filters( 'jetpack_gutenberg', true );
465 }
466
467 /**
468 * Queue a script to set `Jetpack_Block_Assets_Base_Url`.
469 *
470 * In certain cases Webpack needs to know a base to load additional assets from.
471 * Normally it can determine that itself, but when JS concatenation is involved that tends to confuse it.
472 * We work around that by explicitly outputting a variable with the correct URL.
473 * We set that as its own "script" so we can reliably only output it once.
474 */
475 private static function register_blocks_assets_base_url() {
476 if ( ! wp_script_is( 'jetpack-blocks-assets-base-url', 'registered' ) ) {
477 // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- No actual script, so no version needed.
478 wp_register_script( 'jetpack-blocks-assets-base-url', false, array(), null, array( 'in_footer' => false ) );
479 wp_add_inline_script(
480 'jetpack-blocks-assets-base-url',
481 'var Jetpack_Block_Assets_Base_Url=' . wp_json_encode( plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';',
482 'before'
483 );
484 }
485 }
486
487 /**
488 * Only enqueue block assets when needed.
489 *
490 * @param string $type Slug of the block or absolute path to the block source code directory.
491 * @param array $script_dependencies Script dependencies. Will be merged with automatically
492 * detected script dependencies from the webpack build.
493 *
494 * @return void
495 */
496 public static function load_assets_as_required( $type, $script_dependencies = array() ) {
497 if ( is_admin() ) {
498 // A block's view assets will not be required in wp-admin.
499 return;
500 }
501
502 // Retrieve the feature from block.json if a path is passed.
503 if ( path_is_absolute( $type ) ) {
504 $metadata = Blocks::get_block_metadata_from_file( Blocks::get_path_to_block_metadata( $type ) );
505 $feature = Blocks::get_block_feature_from_metadata( $metadata );
506
507 if ( ! empty( $feature ) ) {
508 $type = $feature;
509 }
510 }
511
512 $type = sanitize_title_with_dashes( $type );
513 self::load_styles_as_required( $type );
514 self::load_scripts_as_required( $type, $script_dependencies );
515 }
516
517 /**
518 * Only enqueue block sytles when needed.
519 *
520 * @param string $type Slug of the block.
521 *
522 * @since 7.2.0
523 *
524 * @return void
525 */
526 public static function load_styles_as_required( $type ) {
527 if ( is_admin() ) {
528 // A block's view assets will not be required in wp-admin.
529 return;
530 }
531
532 // Enqueue styles.
533 $style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
534 if ( self::block_has_asset( $style_relative_path ) ) {
535 $style_version = self::get_asset_version( $style_relative_path );
536 $view_style = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
537 $view_style = add_query_arg( 'minify', 'false', $view_style );
538
539 // If this is a customizer preview, render the style directly to the preview after autosave.
540 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
541 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
542 // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
543 echo '<link rel="stylesheet" id="jetpack-block-' . esc_attr( $type ) . '" href="' . esc_attr( $view_style ) . '&amp;ver=' . esc_attr( $style_version ) . '" media="all">';
544 } else {
545 wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
546 wp_style_add_data( 'jetpack-block-' . $type, 'path', JETPACK__PLUGIN_DIR . $style_relative_path );
547 }
548 }
549 }
550
551 /**
552 * Only enqueue block scripts when needed.
553 *
554 * @param string $type Slug of the block.
555 * @param array $script_dependencies Script dependencies. Will be merged with automatically
556 * detected script dependencies from the webpack build.
557 *
558 * @since 7.2.0
559 *
560 * @return void
561 */
562 public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
563 if ( is_admin() ) {
564 // A block's view assets will not be required in wp-admin.
565 return;
566 }
567
568 self::register_blocks_assets_base_url();
569
570 // Enqueue script.
571 $script_relative_path = self::get_blocks_directory() . $type . '/view.js';
572 $script_deps_path = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
573 $script_dependencies[] = 'wp-polyfill';
574 $script_dependencies[] = 'jetpack-blocks-assets-base-url';
575 if ( file_exists( $script_deps_path ) ) {
576 $asset_manifest = include $script_deps_path;
577 $script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
578 }
579
580 if ( ! Blocks::is_amp_request() && self::block_has_asset( $script_relative_path ) ) {
581 $script_version = self::get_asset_version( $script_relative_path );
582 $view_script = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
583 $view_script = add_query_arg( 'minify', 'false', $view_script );
584
585 // Enqueue dependencies.
586 wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
587
588 // If this is a customizer preview, enqueue the dependencies and render the script directly to the preview after autosave.
589 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
590 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
591 // The Map block is dependent on wp-element, and it doesn't appear to to be possible to load
592 // this dynamically into the customizer iframe currently.
593 if ( 'map' === $type ) {
594 echo '<div>' . esc_html_e( 'No map preview available. Publish and refresh to see this widget.', 'jetpack' ) . '</div>';
595 echo '<script>';
596 echo 'Array.from(document.getElementsByClassName(\'wp-block-jetpack-map\')).forEach(function(element){element.style.display = \'none\';})';
597 echo '</script>';
598 } else {
599 echo '<script id="jetpack-block-' . esc_attr( $type ) . '" src="' . esc_attr( $view_script ) . '&amp;ver=' . esc_attr( $script_version ) . '"></script>';
600 }
601 }
602 }
603 }
604
605 /**
606 * Check if an asset exists for a block.
607 *
608 * @param string $file Path of the file we are looking for.
609 *
610 * @return bool $block_has_asset Does the file exist.
611 */
612 public static function block_has_asset( $file ) {
613 return file_exists( JETPACK__PLUGIN_DIR . $file );
614 }
615
616 /**
617 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
618 *
619 * @param string $file Path of the file we are looking for.
620 *
621 * @return string $script_version Version number.
622 */
623 public static function get_asset_version( $file ) {
624 return Jetpack::is_development_version() && self::block_has_asset( $file )
625 ? filemtime( JETPACK__PLUGIN_DIR . $file )
626 : JETPACK__VERSION;
627 }
628
629 /**
630 * Load Gutenberg editor assets
631 *
632 * @since 6.7.0
633 *
634 * @return void
635 */
636 public static function enqueue_block_editor_assets() {
637 if ( ! self::should_load() ) {
638 return;
639 }
640
641 /**
642 * This can be called multiple times per page load in the admin, during the `enqueue_block_assets` action.
643 * These assets are necessary for the admin for editing but are not necessary for each pattern preview.
644 * Therefore we dequeue them, so they don't load for each pattern preview iframe.
645 */
646 if ( ! wp_should_load_block_editor_scripts_and_styles() ) {
647 wp_dequeue_script( 'jp-tracks' );
648 wp_dequeue_script( 'jetpack-blocks-editor' );
649
650 return;
651 }
652
653 $status = new Status();
654
655 // Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
656 if ( ! $status->is_offline_mode() && Jetpack::is_connection_ready() ) {
657 wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
658 }
659
660 $blocks_dir = self::get_blocks_directory();
661 $blocks_variation = self::blocks_variation();
662
663 if ( 'production' !== $blocks_variation ) {
664 $blocks_env = '-' . esc_attr( $blocks_variation );
665 } else {
666 $blocks_env = '';
667 }
668
669 self::register_blocks_assets_base_url();
670
671 Assets::register_script(
672 'jetpack-blocks-editor',
673 "{$blocks_dir}editor{$blocks_env}.js",
674 JETPACK__PLUGIN_FILE,
675 array(
676 'textdomain' => 'jetpack',
677 'dependencies' => array( 'jetpack-blocks-assets-base-url' ),
678 )
679 );
680
681 // Hack around #20357 (specifically, that the editor bundle depends on
682 // wp-edit-post but wp-edit-post's styles break the Widget Editor and
683 // Site Editor) until a real fix gets unblocked.
684 // @todo Remove this once #20357 is properly fixed.
685 wp_styles()->query( 'jetpack-blocks-editor', 'registered' )->deps = array();
686
687 Assets::enqueue_script( 'jetpack-blocks-editor' );
688
689 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
690 $user = wp_get_current_user();
691 $user_data = array(
692 'email' => $user->user_email,
693 'userid' => $user->ID,
694 'username' => $user->user_login,
695 );
696 $blog_id = get_current_blog_id();
697 $is_current_user_connected = true;
698 } else {
699 $user_data = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
700 $blog_id = Jetpack_Options::get_option( 'id', 0 );
701 $is_current_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected();
702 }
703
704 if ( $blocks_variation === 'beta' && $is_current_user_connected ) {
705 wp_enqueue_style( 'recoleta-font', '//s1.wp.com/i/fonts/recoleta/css/400.min.css', array(), Constants::get_constant( 'JETPACK__VERSION' ) );
706 }
707 // AI Assistant
708 $ai_assistant_state = array(
709 'is-enabled' => apply_filters( 'jetpack_ai_enabled', true ),
710 'is-playground-visible' => Constants::is_true( 'JETPACK_AI_ASSISTANT_PLAYGROUND' ),
711 );
712
713 $screen_base = null;
714 if ( function_exists( 'get_current_screen' ) ) {
715 $screen_base = get_current_screen()->base;
716 }
717
718 $modules = array();
719 if ( class_exists( 'Jetpack_Core_API_Module_List_Endpoint' ) ) {
720 $module_list_endpoint = new Jetpack_Core_API_Module_List_Endpoint();
721 $modules = $module_list_endpoint->get_modules();
722 }
723
724 $initial_state = array(
725 'available_blocks' => self::get_availability(),
726 'blocks_variation' => $blocks_variation,
727 'modules' => $modules,
728 'jetpack' => array(
729 'is_active' => Jetpack::is_connection_ready(),
730 'is_current_user_connected' => $is_current_user_connected,
731 /** This filter is documented in class.jetpack-gutenberg.php */
732 'enable_upgrade_nudge' => apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ),
733 'is_private_site' => $status->is_private_site(),
734 'is_coming_soon' => $status->is_coming_soon(),
735 'is_offline_mode' => $status->is_offline_mode(),
736 'is_newsletter_feature_enabled' => class_exists( '\Jetpack_Memberships' ),
737 /**
738 * Enable the RePublicize UI in the block editor context.
739 *
740 * @module publicize
741 *
742 * @since 10.3.0
743 * @deprecated $$next_version$$ This is a feature flag that is no longer used.
744 *
745 * @param bool true Enable the RePublicize UI in the block editor context. Defaults to true.
746 */
747 'republicize_enabled' => apply_filters( 'jetpack_block_editor_republicize_feature', true ),
748 /**
749 * Prevent the registration of the blocks from extensions/blocks/contact-form
750 * if the Forms package is enabled.
751 */
752 'is_form_package_enabled' => apply_filters( 'jetpack_contact_form_use_package', true ),
753 ),
754 'siteFragment' => $status->get_site_suffix(),
755 'adminUrl' => esc_url( admin_url() ),
756 'tracksUserData' => $user_data,
757 'wpcomBlogId' => $blog_id,
758 'allowedMimeTypes' => wp_get_mime_types(),
759 'siteLocale' => str_replace( '_', '-', get_locale() ),
760 'ai-assistant' => $ai_assistant_state,
761 'screenBase' => $screen_base,
762 'pluginBasePath' => plugins_url( '', Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
763 );
764
765 if ( Jetpack::is_module_active( 'publicize' ) && function_exists( 'publicize_init' ) ) {
766 $publicize = publicize_init();
767 $jetpack_social_settings = new Automattic\Jetpack\Publicize\Jetpack_Social_Settings\Settings();
768 $settings = $jetpack_social_settings->get_settings( true );
769
770 $initial_state['social'] = array(
771 'sharesData' => $publicize->get_publicize_shares_info( $blog_id ),
772 'hasPaidPlan' => $publicize->has_paid_plan(),
773 'isEnhancedPublishingEnabled' => $publicize->has_enhanced_publishing_feature(),
774 'isSocialImageGeneratorAvailable' => $settings['socialImageGeneratorSettings']['available'],
775 'isSocialImageGeneratorEnabled' => $settings['socialImageGeneratorSettings']['enabled'],
776 'dismissedNotices' => Dismissed_Notices::get_dismissed_notices(),
777 'supportedAdditionalConnections' => $publicize->get_supported_additional_connections(),
778 'autoConversionSettings' => $settings['autoConversionSettings'],
779 'jetpackSharingSettingsUrl' => esc_url_raw( admin_url( 'admin.php?page=jetpack#/sharing' ) ),
780 );
781 }
782
783 wp_localize_script(
784 'jetpack-blocks-editor',
785 'Jetpack_Editor_Initial_State',
786 $initial_state
787 );
788
789 // Adds Connection package initial state.
790 Connection_Initial_State::render_script( 'jetpack-blocks-editor' );
791 }
792
793 /**
794 * Some blocks do not depend on a specific module,
795 * and can consequently be loaded outside of the usual modules.
796 * We will look for such modules in the extensions/ directory.
797 *
798 * @since 7.1.0
799 * @see wp_common_block_scripts_and_styles()
800 */
801 public static function load_independent_blocks() {
802 if ( self::should_load() ) {
803 /**
804 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
805 * If available, load them.
806 */
807 $directories = array( 'blocks', 'plugins', 'extended-blocks', 'shared', 'store' );
808
809 foreach ( static::get_extensions() as $extension ) {
810 foreach ( $directories as $dirname ) {
811 $path = JETPACK__PLUGIN_DIR . "extensions/{$dirname}/{$extension}/{$extension}.php";
812
813 if ( file_exists( $path ) ) {
814 include_once $path;
815 continue 2;
816 }
817 }
818 }
819 }
820 }
821
822 /**
823 * Loads PHP components of block editor extensions.
824 *
825 * @since 8.9.0
826 */
827 public static function load_block_editor_extensions() {
828 if ( self::should_load() ) {
829 // Block editor extensions to load.
830 $extensions_to_load = array(
831 'extended-blocks',
832 'plugins',
833 );
834
835 // Collect the extension paths.
836 foreach ( $extensions_to_load as $extension_to_load ) {
837 $extensions_folder = glob( JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/*' );
838
839 // Require each of the extension files, in case it exists.
840 foreach ( $extensions_folder as $extension_folder ) {
841 $name = basename( $extension_folder );
842 $extension_file_path = JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/' . $name . '/' . $name . '.php';
843
844 if ( file_exists( $extension_file_path ) ) {
845 include_once $extension_file_path;
846 }
847 }
848 }
849 }
850 }
851
852 /**
853 * Get CSS classes for a block.
854 *
855 * @since 7.7.0
856 *
857 * @param string $slug Block slug.
858 * @param array $attr Block attributes.
859 * @param array $extra Potential extra classes you may want to provide.
860 *
861 * @return string $classes List of CSS classes for a block.
862 */
863 public static function block_classes( $slug, $attr, $extra = array() ) {
864 _deprecated_function( __METHOD__, '9.0.0', 'Automattic\\Jetpack\\Blocks::classes' );
865 return Blocks::classes( $slug, $attr, $extra );
866 }
867
868 /**
869 * Determine whether a site should use the default set of blocks, or a custom set.
870 * Possible variations are currently beta, experimental, and production.
871 *
872 * @since 8.1.0
873 *
874 * @return string $block_varation production|beta|experimental
875 */
876 public static function blocks_variation() {
877 // Default to production blocks.
878 $block_varation = 'production';
879
880 /*
881 * Prefer to use this JETPACK_BLOCKS_VARIATION constant
882 * or the jetpack_blocks_variation filter
883 * to set the block variation in your code.
884 */
885 $default = Constants::get_constant( 'JETPACK_BLOCKS_VARIATION' );
886 if ( ! empty( $default ) && in_array( $default, array( 'beta', 'experimental', 'production' ), true ) ) {
887 $block_varation = $default;
888 }
889
890 /**
891 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
892 *
893 * @since 6.9.0
894 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
895 *
896 * @param boolean
897 */
898 $is_beta = apply_filters_deprecated(
899 'jetpack_load_beta_blocks',
900 array( false ),
901 'jetpack-11.8.0',
902 'jetpack_blocks_variation'
903 );
904
905 /*
906 * Switch to beta blocks if you use the JETPACK_BETA_BLOCKS constant
907 * or the deprecated jetpack_load_beta_blocks filter.
908 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
909 */
910 if (
911 empty( $default )
912 && (
913 $is_beta
914 || Constants::is_true( 'JETPACK_BETA_BLOCKS' )
915 )
916 ) {
917 $block_varation = 'beta';
918 }
919
920 /**
921 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
922 *
923 * @since 6.9.0
924 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
925 *
926 * @param boolean
927 */
928 $is_experimental = apply_filters_deprecated(
929 'jetpack_load_experimental_blocks',
930 array( false ),
931 'jetpack-11.8.0',
932 'jetpack_blocks_variation'
933 );
934
935 /*
936 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant
937 * or the deprecated jetpack_load_experimental_blocks filter.
938 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
939 */
940 if (
941 empty( $default )
942 && (
943 $is_experimental
944 || Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' )
945 )
946 ) {
947 $block_varation = 'experimental';
948 }
949
950 /**
951 * Allow customizing the variation of blocks in use on a site.
952 * Overwrites any previously set values, whether by constant or filter.
953 *
954 * @since 8.1.0
955 *
956 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
957 */
958 return apply_filters( 'jetpack_blocks_variation', $block_varation );
959 }
960
961 /**
962 * Get a list of extensions available for the variation you chose.
963 *
964 * @since 8.1.0
965 *
966 * @param obj $preset_extensions_manifest List of extensions available in Jetpack.
967 * @param string $blocks_variation Subset of blocks. production|beta|experimental.
968 *
969 * @return array $preset_extensions Array of extensions for that variation
970 */
971 public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
972 $preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
973 ? (array) $preset_extensions_manifest->{ $blocks_variation }
974 : array();
975
976 /*
977 * Experimental and Beta blocks need the production blocks as well.
978 */
979 if (
980 'experimental' === $blocks_variation
981 || 'beta' === $blocks_variation
982 ) {
983 $production_extensions = isset( $preset_extensions_manifest->production )
984 ? (array) $preset_extensions_manifest->production
985 : array();
986
987 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
988 }
989
990 /*
991 * Beta blocks need the experimental blocks as well.
992 *
993 * If you've chosen to see Beta blocks,
994 * we want to make all blocks available to you:
995 * - Production
996 * - Experimental
997 * - Beta
998 */
999 if ( 'beta' === $blocks_variation ) {
1000 $production_extensions = isset( $preset_extensions_manifest->experimental )
1001 ? (array) $preset_extensions_manifest->experimental
1002 : array();
1003
1004 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
1005 }
1006
1007 return $preset_extensions;
1008 }
1009
1010 /**
1011 * Validate a URL used in a SSR block.
1012 *
1013 * @since 8.3.0
1014 *
1015 * @param string $url URL saved as an attribute in block.
1016 * @param array $allowed Array of allowed hosts for that block, or regexes to check against.
1017 * @param bool $is_regex Array of regexes matching the URL that could be used in block.
1018 *
1019 * @return bool|string
1020 */
1021 public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
1022 if (
1023 empty( $url )
1024 || ! is_array( $allowed )
1025 || empty( $allowed )
1026 ) {
1027 return false;
1028 }
1029
1030 $url_components = wp_parse_url( $url );
1031
1032 // Bail early if we cannot find a host.
1033 if ( empty( $url_components['host'] ) ) {
1034 return false;
1035 }
1036
1037 // Normalize URL.
1038 $url = sprintf(
1039 '%s://%s%s%s',
1040 isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
1041 $url_components['host'],
1042 isset( $url_components['path'] ) ? $url_components['path'] : '/',
1043 isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
1044 );
1045
1046 if ( ! empty( $url_components['fragment'] ) ) {
1047 $url = $url . '#' . rawurlencode( $url_components['fragment'] );
1048 }
1049
1050 /*
1051 * If we're using an allowed list of hosts,
1052 * check if the URL belongs to one of the domains allowed for that block.
1053 */
1054 if (
1055 false === $is_regex
1056 && in_array( $url_components['host'], $allowed, true )
1057 ) {
1058 return $url;
1059 }
1060
1061 /*
1062 * If we are using an array of regexes to check against,
1063 * loop through that.
1064 */
1065 if ( true === $is_regex ) {
1066 foreach ( $allowed as $regex ) {
1067 if ( 1 === preg_match( $regex, $url ) ) {
1068 return $url;
1069 }
1070 }
1071 }
1072
1073 return false;
1074 }
1075
1076 /**
1077 * Determines whether a preview of the block with an upgrade nudge should
1078 * be displayed for admins on the site frontend.
1079 *
1080 * @since 8.4.0
1081 *
1082 * @param array $availability_for_block The availability for the block.
1083 *
1084 * @return bool
1085 */
1086 public static function should_show_frontend_preview( $availability_for_block ) {
1087 return (
1088 isset( $availability_for_block['details']['required_plan'] )
1089 && current_user_can( 'manage_options' )
1090 && ! is_feed()
1091 );
1092 }
1093
1094 /**
1095 * Output an UpgradeNudge Component on the frontend of a site.
1096 *
1097 * @since 8.4.0
1098 *
1099 * @param string $plan The plan that users need to purchase to make the block work.
1100 *
1101 * @return string
1102 */
1103 public static function upgrade_nudge( $plan ) {
1104 require_once JETPACK__PLUGIN_DIR . '_inc/lib/components.php';
1105 return Jetpack_Components::render_upgrade_nudge(
1106 array(
1107 'plan' => $plan,
1108 )
1109 );
1110 }
1111
1112 /**
1113 * Output a notice within a block.
1114 *
1115 * @since 8.6.0
1116 *
1117 * @param string $message Notice we want to output.
1118 * @param string $status Status of the notice. Can be one of success, info, warning, error. info by default.
1119 * @param string $classes List of CSS classes.
1120 *
1121 * @return string
1122 */
1123 public static function notice( $message, $status = 'info', $classes = '' ) {
1124 if (
1125 empty( $message )
1126 || ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1127 ) {
1128 return '';
1129 }
1130
1131 $color = '';
1132 switch ( $status ) {
1133 case 'success':
1134 $color = '#00a32a';
1135 break;
1136 case 'warning':
1137 $color = '#dba617';
1138 break;
1139 case 'error':
1140 $color = '#d63638';
1141 break;
1142 case 'info':
1143 default:
1144 $color = '#72aee6';
1145 break;
1146 }
1147
1148 return sprintf(
1149 '<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1150 esc_attr( $status ),
1151 wp_kses(
1152 $message,
1153 array(
1154 'br' => array(),
1155 'p' => array(),
1156 'a' => array(
1157 'href' => array(),
1158 'target' => array(),
1159 'rel' => array(),
1160 ),
1161 )
1162 ),
1163 esc_attr( $classes ),
1164 sanitize_hex_color( $color )
1165 );
1166 }
1167
1168 /**
1169 * Retrieve site-specific features for Simple sites.
1170 *
1171 * We're caching the data for the lifetime of the request, because it can be slow to calculate,
1172 * and it can be called multiple times per single request.
1173 *
1174 * We intentionally don't use object caching or any other type of persistent caching,
1175 * in order to avoid complex cache invalidation on subscription addition or removal.
1176 *
1177 * @since 10.7
1178 *
1179 * @return array
1180 */
1181 private static function get_site_specific_features() {
1182 $current_blog_id = get_current_blog_id();
1183
1184 if ( isset( self::$site_specific_features[ $current_blog_id ] ) ) {
1185 return self::$site_specific_features[ $current_blog_id ];
1186 }
1187
1188 if ( ! class_exists( 'Store_Product_List' ) ) {
1189 require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1190 }
1191
1192 $site_specific_features = Store_Product_List::get_site_specific_features_data( $current_blog_id );
1193 self::$site_specific_features[ $current_blog_id ] = $site_specific_features;
1194
1195 return $site_specific_features;
1196 }
1197
1198 /**
1199 * Set the availability of the block as the editor
1200 * is loaded.
1201 *
1202 * @param string $slug Slug of the block.
1203 */
1204 public static function set_availability_for_plan( $slug ) {
1205 $slug = self::remove_extension_prefix( $slug );
1206
1207 if ( Jetpack_Plan::supports( $slug ) ) {
1208 self::set_extension_available( $slug );
1209 return;
1210 }
1211
1212 // Check what's the minimum plan where the feature is available.
1213 $plan = '';
1214 $features_data = array();
1215 $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
1216 $is_atomic_site = ( new Host() )->is_woa_site();
1217
1218 if ( $is_simple_site || $is_atomic_site ) {
1219 // Simple sites.
1220 if ( $is_simple_site ) {
1221 $features_data = self::get_site_specific_features();
1222 } else {
1223 // Atomic sites.
1224 $option = get_option( 'jetpack_active_plan' );
1225 if ( isset( $option['features'] ) ) {
1226 $features_data = $option['features'];
1227 }
1228 }
1229
1230 if ( ! empty( $features_data['available'][ $slug ] ) ) {
1231 $plan = $features_data['available'][ $slug ][0];
1232 }
1233 } else {
1234 // Jetpack sites.
1235 $plan = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1236 }
1237
1238 self::set_extension_unavailable(
1239 $slug,
1240 'missing_plan',
1241 array(
1242 'required_feature' => $slug,
1243 'required_plan' => $plan,
1244 )
1245 );
1246 }
1247
1248 /**
1249 * Wraps the suplied render_callback in a function to check
1250 * the availability of the block before rendering it.
1251 *
1252 * @param string $slug The block slug, used to check for availability.
1253 * @param callable $render_callback The render_callback that will be called if the block is available.
1254 */
1255 public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1256 return function ( $prepared_attributes, $block_content, $block ) use ( $render_callback, $slug ) {
1257 $availability = self::get_cached_availability();
1258 $bare_slug = self::remove_extension_prefix( $slug );
1259 if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1260 return call_user_func( $render_callback, $prepared_attributes, $block_content );
1261 }
1262
1263 // A preview of the block is rendered for admins on the frontend with an upgrade nudge.
1264 if ( isset( $availability[ $bare_slug ] ) ) {
1265 if ( self::should_show_frontend_preview( $availability[ $bare_slug ] ) ) {
1266 $block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content );
1267
1268 // If the upgrade nudge isn't already being displayed by a parent block, display the nudge.
1269 if ( isset( $block->attributes['shouldDisplayFrontendBanner'] ) && $block->attributes['shouldDisplayFrontendBanner'] ) {
1270 $upgrade_nudge = self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
1271 return $upgrade_nudge . $block_preview;
1272 }
1273
1274 return $block_preview;
1275 }
1276 }
1277
1278 return null;
1279 };
1280 }
1281
1282 /**
1283 * Display a message to site editors and roles above when a block is no longer supported.
1284 * This is only displayed on the frontend.
1285 *
1286 * @since 12.3
1287 *
1288 * @param string $block_content The block content.
1289 * @param array $block The full block, including name and attributes.
1290 *
1291 * @return string
1292 */
1293 public static function display_deprecated_block_message( $block_content, $block ) {
1294 if ( in_array( $block['blockName'], self::$deprecated_blocks, true ) ) {
1295 if ( current_user_can( 'edit_posts' ) ) {
1296 $block_content = self::notice(
1297 __( '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' ),
1298 'warning',
1299 'jetpack-block-deprecated'
1300 );
1301 } else {
1302 $block_content = '';
1303 }
1304 }
1305
1306 return $block_content;
1307 }
1308 }
1309
1310 if ( ( new Host() )->is_woa_site() ) {
1311 /**
1312 * Enable upgrade nudge for Atomic sites.
1313 * This feature is false as default,
1314 * so let's enable it through this filter.
1315 *
1316 * More doc: https://github.com/Automattic/jetpack/blob/trunk/projects/plugins/jetpack/extensions/README.md#upgrades-for-blocks
1317 */
1318 add_filter( 'jetpack_block_editor_enable_upgrade_nudge', '__return_true' );
1319 }
1320