PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 12.5
Jetpack – WP Security, Backup, Speed, & Growth v12.5
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 in Jetpack – WP Security, Backup, Speed, & Growth 12.5, at class.jetpack-gutenberg.php

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