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

1,353 lines 42.5 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' => (
697 /**
698 * Enable the Paid Newsletters feature in the block editor context.
699 *
700 * @module subscriptions
701 * @since 11.8
702 *
703 * @param bool false Enable the Paid Newsletters feature in the block editor context.
704 */
705 apply_filters( 'jetpack_subscriptions_newsletter_feature_enabled', true )
706 && class_exists( '\Jetpack_Memberships' )
707 ),
708 /**
709 * Enable the RePublicize UI in the block editor context.
710 *
711 * @module publicize
712 *
713 * @since 10.3.0
714 * @deprecated $$next_version$$ This is a feature flag that is no longer used.
715 *
716 * @param bool true Enable the RePublicize UI in the block editor context. Defaults to true.
717 */
718 'republicize_enabled' => apply_filters( 'jetpack_block_editor_republicize_feature', true ),
719 /**
720 * Prevent the registration of the blocks from extensions/blocks/contact-form
721 * if the Forms package is enabled.
722 */
723 'is_form_package_enabled' => apply_filters( 'jetpack_contact_form_use_package', true ),
724 ),
725 'siteFragment' => $status->get_site_suffix(),
726 'adminUrl' => esc_url( admin_url() ),
727 'tracksUserData' => $user_data,
728 'wpcomBlogId' => $blog_id,
729 'allowedMimeTypes' => wp_get_mime_types(),
730 'siteLocale' => str_replace( '_', '-', get_locale() ),
731 'ai-assistant' => $ai_assistant_state,
732 'screenBase' => $screen_base,
733 );
734
735 if ( Jetpack::is_module_active( 'publicize' ) && function_exists( 'publicize_init' ) ) {
736 $publicize = publicize_init();
737 $sig_settings = new Automattic\Jetpack\Publicize\Social_Image_Generator\Settings();
738 $initial_state['social'] = array(
739 'sharesData' => $publicize->get_publicize_shares_info( $blog_id ),
740 'hasPaidPlan' => $publicize->has_paid_plan(),
741 'isEnhancedPublishingEnabled' => $publicize->has_enhanced_publishing_feature(),
742 'isSocialImageGeneratorAvailable' => $sig_settings->is_available(),
743 'isSocialImageGeneratorEnabled' => $sig_settings->is_enabled(),
744 'dismissedNotices' => $publicize->get_dismissed_notices(),
745 'isInstagramConnectionSupported' => $publicize->has_instagram_connection_feature(),
746 'isMastodonConnectionSupported' => $publicize->has_mastodon_connection_feature(),
747 );
748 }
749
750 wp_localize_script(
751 'jetpack-blocks-editor',
752 'Jetpack_Editor_Initial_State',
753 $initial_state
754 );
755
756 // Adds Connection package initial state.
757 wp_add_inline_script( 'jetpack-blocks-editor', Connection_Initial_State::render(), 'before' );
758 }
759
760 /**
761 * Add the Gutenberg editor stylesheet to iframed editors, such as the site editor,
762 * which don't have access to stylesheets added with `wp_enqueue_style`.
763 *
764 * This workaround is currently used by WordPress.com Simple and Atomic sites.
765 *
766 * @since 10.7
767 *
768 * @return void
769 */
770 public static function add_iframed_editor_style() {
771 if ( ! self::should_load() ) {
772 return;
773 }
774
775 global $pagenow;
776 if ( ! isset( $pagenow ) ) {
777 return;
778 }
779
780 // Pre 13.7 pages that still need to be supported if < 13.7 is
781 // still installed.
782 $allowed_old_pages = array( 'admin.php', 'themes.php' );
783 $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
784 // For Gutenberg > 13.7, the core `site-editor.php` route is used instead
785 $is_site_editor_page = 'site-editor.php' === $pagenow;
786
787 $should_skip_adding_styles = ! $is_site_editor_page && ! $is_old_site_editor_page;
788 if ( $should_skip_adding_styles ) {
789 return;
790 }
791
792 $blocks_dir = self::get_blocks_directory();
793 $blocks_variation = self::blocks_variation();
794
795 if ( 'production' !== $blocks_variation ) {
796 $blocks_env = '-' . esc_attr( $blocks_variation );
797 } else {
798 $blocks_env = '';
799 }
800
801 $path = "{$blocks_dir}editor{$blocks_env}.css";
802 $dir = dirname( JETPACK__PLUGIN_FILE );
803
804 if ( file_exists( "$dir/$path" ) ) {
805 if ( is_rtl() ) {
806 $rtlcsspath = substr( $path, 0, -4 ) . '.rtl.css';
807 if ( file_exists( "$dir/$rtlcsspath" ) ) {
808 $path = $rtlcsspath;
809 }
810 }
811
812 $url = Assets::normalize_path( plugins_url( $path, JETPACK__PLUGIN_FILE ) );
813 $url = add_query_arg( 'minify', 'false', $url );
814
815 add_editor_style( $url );
816 }
817 }
818
819 /**
820 * Some blocks do not depend on a specific module,
821 * and can consequently be loaded outside of the usual modules.
822 * We will look for such modules in the extensions/ directory.
823 *
824 * @since 7.1.0
825 * @see wp_common_block_scripts_and_styles()
826 */
827 public static function load_independent_blocks() {
828 if ( self::should_load() ) {
829 /**
830 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
831 * If available, load them.
832 */
833 $directories = array( 'blocks', 'plugins', 'extended-blocks', 'shared', 'store' );
834
835 foreach ( static::get_extensions() as $extension ) {
836 foreach ( $directories as $dirname ) {
837 $path = JETPACK__PLUGIN_DIR . "extensions/{$dirname}/{$extension}/{$extension}.php";
838
839 if ( file_exists( $path ) ) {
840 include_once $path;
841 continue 2;
842 }
843 }
844 }
845 }
846 }
847
848 /**
849 * Loads PHP components of block editor extensions.
850 *
851 * @since 8.9.0
852 */
853 public static function load_block_editor_extensions() {
854 if ( self::should_load() ) {
855 // Block editor extensions to load.
856 $extensions_to_load = array(
857 'extended-blocks',
858 'plugins',
859 );
860
861 // Collect the extension paths.
862 foreach ( $extensions_to_load as $extension_to_load ) {
863 $extensions_folder = glob( JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/*' );
864
865 // Require each of the extension files, in case it exists.
866 foreach ( $extensions_folder as $extension_folder ) {
867 $name = basename( $extension_folder );
868 $extension_file_path = JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/' . $name . '/' . $name . '.php';
869
870 if ( file_exists( $extension_file_path ) ) {
871 include_once $extension_file_path;
872 }
873 }
874 }
875 }
876 }
877
878 /**
879 * Get CSS classes for a block.
880 *
881 * @since 7.7.0
882 *
883 * @param string $slug Block slug.
884 * @param array $attr Block attributes.
885 * @param array $extra Potential extra classes you may want to provide.
886 *
887 * @return string $classes List of CSS classes for a block.
888 */
889 public static function block_classes( $slug, $attr, $extra = array() ) {
890 _deprecated_function( __METHOD__, '9.0.0', 'Automattic\\Jetpack\\Blocks::classes' );
891 return Blocks::classes( $slug, $attr, $extra );
892 }
893
894 /**
895 * Determine whether a site should use the default set of blocks, or a custom set.
896 * Possible variations are currently beta, experimental, and production.
897 *
898 * @since 8.1.0
899 *
900 * @return string $block_varation production|beta|experimental
901 */
902 public static function blocks_variation() {
903 // Default to production blocks.
904 $block_varation = 'production';
905
906 /*
907 * Prefer to use this JETPACK_BLOCKS_VARIATION constant
908 * or the jetpack_blocks_variation filter
909 * to set the block variation in your code.
910 */
911 $default = Constants::get_constant( 'JETPACK_BLOCKS_VARIATION' );
912 if ( ! empty( $default ) && in_array( $default, array( 'beta', 'experimental', 'production' ), true ) ) {
913 $block_varation = $default;
914 }
915
916 /**
917 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
918 *
919 * @since 6.9.0
920 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
921 *
922 * @param boolean
923 */
924 $is_beta = apply_filters_deprecated(
925 'jetpack_load_beta_blocks',
926 array( false ),
927 'jetpack-11.8.0',
928 'jetpack_blocks_variation'
929 );
930
931 /*
932 * Switch to beta blocks if you use the JETPACK_BETA_BLOCKS constant
933 * or the deprecated jetpack_load_beta_blocks filter.
934 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
935 */
936 if (
937 empty( $default )
938 && (
939 $is_beta
940 || Constants::is_true( 'JETPACK_BETA_BLOCKS' )
941 )
942 ) {
943 $block_varation = 'beta';
944 }
945
946 /**
947 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
948 *
949 * @since 6.9.0
950 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
951 *
952 * @param boolean
953 */
954 $is_experimental = apply_filters_deprecated(
955 'jetpack_load_experimental_blocks',
956 array( false ),
957 'jetpack-11.8.0',
958 'jetpack_blocks_variation'
959 );
960
961 /*
962 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant
963 * or the deprecated jetpack_load_experimental_blocks filter.
964 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
965 */
966 if (
967 empty( $default )
968 && (
969 $is_experimental
970 || Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' )
971 )
972 ) {
973 $block_varation = 'experimental';
974 }
975
976 /**
977 * Allow customizing the variation of blocks in use on a site.
978 * Overwrites any previously set values, whether by constant or filter.
979 *
980 * @since 8.1.0
981 *
982 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
983 */
984 return apply_filters( 'jetpack_blocks_variation', $block_varation );
985 }
986
987 /**
988 * Get a list of extensions available for the variation you chose.
989 *
990 * @since 8.1.0
991 *
992 * @param obj $preset_extensions_manifest List of extensions available in Jetpack.
993 * @param string $blocks_variation Subset of blocks. production|beta|experimental.
994 *
995 * @return array $preset_extensions Array of extensions for that variation
996 */
997 public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
998 $preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
999 ? (array) $preset_extensions_manifest->{ $blocks_variation }
1000 : array();
1001
1002 /*
1003 * Experimental and Beta blocks need the production blocks as well.
1004 */
1005 if (
1006 'experimental' === $blocks_variation
1007 || 'beta' === $blocks_variation
1008 ) {
1009 $production_extensions = isset( $preset_extensions_manifest->production )
1010 ? (array) $preset_extensions_manifest->production
1011 : array();
1012
1013 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
1014 }
1015
1016 /*
1017 * Beta blocks need the experimental blocks as well.
1018 *
1019 * If you've chosen to see Beta blocks,
1020 * we want to make all blocks available to you:
1021 * - Production
1022 * - Experimental
1023 * - Beta
1024 */
1025 if ( 'beta' === $blocks_variation ) {
1026 $production_extensions = isset( $preset_extensions_manifest->experimental )
1027 ? (array) $preset_extensions_manifest->experimental
1028 : array();
1029
1030 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
1031 }
1032
1033 return $preset_extensions;
1034 }
1035
1036 /**
1037 * Validate a URL used in a SSR block.
1038 *
1039 * @since 8.3.0
1040 *
1041 * @param string $url URL saved as an attribute in block.
1042 * @param array $allowed Array of allowed hosts for that block, or regexes to check against.
1043 * @param bool $is_regex Array of regexes matching the URL that could be used in block.
1044 *
1045 * @return bool|string
1046 */
1047 public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
1048 if (
1049 empty( $url )
1050 || ! is_array( $allowed )
1051 || empty( $allowed )
1052 ) {
1053 return false;
1054 }
1055
1056 $url_components = wp_parse_url( $url );
1057
1058 // Bail early if we cannot find a host.
1059 if ( empty( $url_components['host'] ) ) {
1060 return false;
1061 }
1062
1063 // Normalize URL.
1064 $url = sprintf(
1065 '%s://%s%s%s',
1066 isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
1067 $url_components['host'],
1068 isset( $url_components['path'] ) ? $url_components['path'] : '/',
1069 isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
1070 );
1071
1072 if ( ! empty( $url_components['fragment'] ) ) {
1073 $url = $url . '#' . rawurlencode( $url_components['fragment'] );
1074 }
1075
1076 /*
1077 * If we're using an allowed list of hosts,
1078 * check if the URL belongs to one of the domains allowed for that block.
1079 */
1080 if (
1081 false === $is_regex
1082 && in_array( $url_components['host'], $allowed, true )
1083 ) {
1084 return $url;
1085 }
1086
1087 /*
1088 * If we are using an array of regexes to check against,
1089 * loop through that.
1090 */
1091 if ( true === $is_regex ) {
1092 foreach ( $allowed as $regex ) {
1093 if ( 1 === preg_match( $regex, $url ) ) {
1094 return $url;
1095 }
1096 }
1097 }
1098
1099 return false;
1100 }
1101
1102 /**
1103 * Determines whether a preview of the block with an upgrade nudge should
1104 * be displayed for admins on the site frontend.
1105 *
1106 * @since 8.4.0
1107 *
1108 * @param array $availability_for_block The availability for the block.
1109 *
1110 * @return bool
1111 */
1112 public static function should_show_frontend_preview( $availability_for_block ) {
1113 return (
1114 isset( $availability_for_block['details']['required_plan'] )
1115 && current_user_can( 'manage_options' )
1116 && ! is_feed()
1117 );
1118 }
1119
1120 /**
1121 * Output an UpgradeNudge Component on the frontend of a site.
1122 *
1123 * @since 8.4.0
1124 *
1125 * @param string $plan The plan that users need to purchase to make the block work.
1126 *
1127 * @return string
1128 */
1129 public static function upgrade_nudge( $plan ) {
1130 require_once JETPACK__PLUGIN_DIR . '_inc/lib/components.php';
1131 return Jetpack_Components::render_upgrade_nudge(
1132 array(
1133 'plan' => $plan,
1134 )
1135 );
1136 }
1137
1138 /**
1139 * Output a notice within a block.
1140 *
1141 * @since 8.6.0
1142 *
1143 * @param string $message Notice we want to output.
1144 * @param string $status Status of the notice. Can be one of success, info, warning, error. info by default.
1145 * @param string $classes List of CSS classes.
1146 *
1147 * @return string
1148 */
1149 public static function notice( $message, $status = 'info', $classes = '' ) {
1150 if (
1151 empty( $message )
1152 || ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1153 ) {
1154 return '';
1155 }
1156
1157 $color = '';
1158 switch ( $status ) {
1159 case 'success':
1160 $color = '#00a32a';
1161 break;
1162 case 'warning':
1163 $color = '#dba617';
1164 break;
1165 case 'error':
1166 $color = '#d63638';
1167 break;
1168 case 'info':
1169 default:
1170 $color = '#72aee6';
1171 break;
1172 }
1173
1174 return sprintf(
1175 '<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1176 esc_attr( $status ),
1177 wp_kses(
1178 $message,
1179 array(
1180 'br' => array(),
1181 'p' => array(),
1182 'a' => array(
1183 'href' => array(),
1184 'target' => array(),
1185 'rel' => array(),
1186 ),
1187 )
1188 ),
1189 esc_attr( $classes ),
1190 sanitize_hex_color( $color )
1191 );
1192 }
1193
1194 /**
1195 * Retrieve site-specific features for Simple sites.
1196 *
1197 * We're caching the data for the lifetime of the request, because it can be slow to calculate,
1198 * and it can be called multiple times per single request.
1199 *
1200 * We intentionally don't use object caching or any other type of persistent caching,
1201 * in order to avoid complex cache invalidation on subscription addition or removal.
1202 *
1203 * @since 10.7
1204 *
1205 * @return array
1206 */
1207 private static function get_site_specific_features() {
1208 $current_blog_id = get_current_blog_id();
1209
1210 if ( isset( self::$site_specific_features[ $current_blog_id ] ) ) {
1211 return self::$site_specific_features[ $current_blog_id ];
1212 }
1213
1214 if ( ! class_exists( 'Store_Product_List' ) ) {
1215 require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1216 }
1217
1218 $site_specific_features = Store_Product_List::get_site_specific_features_data( $current_blog_id );
1219 self::$site_specific_features[ $current_blog_id ] = $site_specific_features;
1220
1221 return $site_specific_features;
1222 }
1223
1224 /**
1225 * Set the availability of the block as the editor
1226 * is loaded.
1227 *
1228 * @param string $slug Slug of the block.
1229 */
1230 public static function set_availability_for_plan( $slug ) {
1231 $slug = self::remove_extension_prefix( $slug );
1232
1233 if ( Jetpack_Plan::supports( $slug ) ) {
1234 self::set_extension_available( $slug );
1235 return;
1236 }
1237
1238 // Check what's the minimum plan where the feature is available.
1239 $plan = '';
1240 $features_data = array();
1241 $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
1242 $is_atomic_site = ( new Host() )->is_woa_site();
1243
1244 if ( $is_simple_site || $is_atomic_site ) {
1245 // Simple sites.
1246 if ( $is_simple_site ) {
1247 $features_data = self::get_site_specific_features();
1248 } else {
1249 // Atomic sites.
1250 $option = get_option( 'jetpack_active_plan' );
1251 if ( isset( $option['features'] ) ) {
1252 $features_data = $option['features'];
1253 }
1254 }
1255
1256 if ( ! empty( $features_data['available'][ $slug ] ) ) {
1257 $plan = $features_data['available'][ $slug ][0];
1258 }
1259 } else {
1260 // Jetpack sites.
1261 $plan = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1262 }
1263
1264 self::set_extension_unavailable(
1265 $slug,
1266 'missing_plan',
1267 array(
1268 'required_feature' => $slug,
1269 'required_plan' => $plan,
1270 )
1271 );
1272 }
1273
1274 /**
1275 * Wraps the suplied render_callback in a function to check
1276 * the availability of the block before rendering it.
1277 *
1278 * @param string $slug The block slug, used to check for availability.
1279 * @param callable $render_callback The render_callback that will be called if the block is available.
1280 */
1281 public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1282 return function ( $prepared_attributes, $block_content, $block ) use ( $render_callback, $slug ) {
1283 $availability = self::get_cached_availability();
1284 $bare_slug = self::remove_extension_prefix( $slug );
1285 if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1286 return call_user_func( $render_callback, $prepared_attributes, $block_content );
1287 }
1288
1289 // A preview of the block is rendered for admins on the frontend with an upgrade nudge.
1290 if ( isset( $availability[ $bare_slug ] ) ) {
1291 if ( self::should_show_frontend_preview( $availability[ $bare_slug ] ) ) {
1292 $block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content );
1293
1294 // If the upgrade nudge isn't already being displayed by a parent block, display the nudge.
1295 if ( isset( $block->attributes['shouldDisplayFrontendBanner'] ) && $block->attributes['shouldDisplayFrontendBanner'] ) {
1296 $upgrade_nudge = self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
1297 return $upgrade_nudge . $block_preview;
1298 }
1299
1300 return $block_preview;
1301 }
1302 }
1303
1304 return null;
1305 };
1306 }
1307
1308 /**
1309 * Display a message to site editors and roles above when a block is no longer supported.
1310 * This is only displayed on the frontend.
1311 *
1312 * @since 12.3
1313 *
1314 * @param string $block_content The block content.
1315 * @param array $block The full block, including name and attributes.
1316 *
1317 * @return string
1318 */
1319 public static function display_deprecated_block_message( $block_content, $block ) {
1320 if ( in_array( $block['blockName'], self::$deprecated_blocks, true ) ) {
1321 if ( current_user_can( 'edit_posts' ) ) {
1322 $block_content = self::notice(
1323 __( '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' ),
1324 'warning',
1325 'jetpack-block-deprecated'
1326 );
1327 } else {
1328 $block_content = '';
1329 }
1330 }
1331
1332 return $block_content;
1333 }
1334 }
1335
1336 if ( ( new Host() )->is_woa_site() ) {
1337 /**
1338 * Enable upgrade nudge for Atomic sites.
1339 * This feature is false as default,
1340 * so let's enable it through this filter.
1341 *
1342 * More doc: https://github.com/Automattic/jetpack/blob/trunk/projects/plugins/jetpack/extensions/README.md#upgrades-for-blocks
1343 */
1344 add_filter( 'jetpack_block_editor_enable_upgrade_nudge', '__return_true' );
1345
1346 /**
1347 * Load block editor styles inline for iframed editors.
1348 *
1349 * @see paYJgx-1Kl-p2
1350 */
1351 add_action( 'admin_init', array( 'Jetpack_Gutenberg', 'add_iframed_editor_style' ) );
1352 }
1353