PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 12.9.3
Jetpack – WP Security, Backup, Speed, & Growth v12.9.3
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 14.4.2 All 500 releases
jetpack / class.jetpack-gutenberg.php
class.jetpack-gutenberg.php
1,298 lines 41.2 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 ( str_starts_with( $extension_name, 'jetpack/' ) || str_starts_with( $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 or absolute path to the block source code directory.
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 // Retrieve the feature from block.json if a path is passed.
482 if ( path_is_absolute( $type ) ) {
483 $metadata = Blocks::get_block_metadata_from_file( Blocks::get_path_to_block_metadata( $type ) );
484 $feature = Blocks::get_block_feature_from_metadata( $metadata );
485
486 if ( ! empty( $feature ) ) {
487 $type = $feature;
488 }
489 }
490
491 $type = sanitize_title_with_dashes( $type );
492 self::load_styles_as_required( $type );
493 self::load_scripts_as_required( $type, $script_dependencies );
494 }
495
496 /**
497 * Only enqueue block sytles when needed.
498 *
499 * @param string $type Slug of the block.
500 *
501 * @since 7.2.0
502 *
503 * @return void
504 */
505 public static function load_styles_as_required( $type ) {
506 if ( is_admin() ) {
507 // A block's view assets will not be required in wp-admin.
508 return;
509 }
510
511 // Enqueue styles.
512 $style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
513 if ( self::block_has_asset( $style_relative_path ) ) {
514 $style_version = self::get_asset_version( $style_relative_path );
515 $view_style = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
516 $view_style = add_query_arg( 'minify', 'false', $view_style );
517
518 // If this is a customizer preview, render the style directly to the preview after autosave.
519 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
520 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
521 // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
522 echo '<link rel="stylesheet" id="jetpack-block-' . esc_attr( $type ) . '" href="' . esc_attr( $view_style ) . '&amp;ver=' . esc_attr( $style_version ) . '" media="all">';
523 } else {
524 wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
525 wp_style_add_data( 'jetpack-block-' . $type, 'path', JETPACK__PLUGIN_DIR . $style_relative_path );
526 }
527 }
528 }
529
530 /**
531 * Only enqueue block scripts when needed.
532 *
533 * @param string $type Slug of the block.
534 * @param array $script_dependencies Script dependencies. Will be merged with automatically
535 * detected script dependencies from the webpack build.
536 *
537 * @since 7.2.0
538 *
539 * @return void
540 */
541 public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
542 if ( is_admin() ) {
543 // A block's view assets will not be required in wp-admin.
544 return;
545 }
546
547 // Enqueue script.
548 $script_relative_path = self::get_blocks_directory() . $type . '/view.js';
549 $script_deps_path = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
550 $script_dependencies[] = 'wp-polyfill';
551 if ( file_exists( $script_deps_path ) ) {
552 $asset_manifest = include $script_deps_path;
553 $script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
554 }
555
556 if ( ! Blocks::is_amp_request() && self::block_has_asset( $script_relative_path ) ) {
557 $script_version = self::get_asset_version( $script_relative_path );
558 $view_script = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
559 $view_script = add_query_arg( 'minify', 'false', $view_script );
560
561 // Enqueue dependencies.
562 wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
563
564 // If this is a customizer preview, enqueue the dependencies and render the script directly to the preview after autosave.
565 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
566 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
567 // The Map block is dependent on wp-element, and it doesn't appear to to be possible to load
568 // this dynamically into the customizer iframe currently.
569 if ( 'map' === $type ) {
570 echo '<div>' . esc_html_e( 'No map preview available. Publish and refresh to see this widget.', 'jetpack' ) . '</div>';
571 echo '<script>';
572 echo 'Array.from(document.getElementsByClassName(\'wp-block-jetpack-map\')).forEach(function(element){element.style.display = \'none\';})';
573 echo '</script>';
574 } else {
575 echo '<script id="jetpack-block-' . esc_attr( $type ) . '" src="' . esc_attr( $view_script ) . '&amp;ver=' . esc_attr( $script_version ) . '"></script>';
576 }
577 }
578 }
579
580 wp_localize_script(
581 'jetpack-block-' . $type,
582 'Jetpack_Block_Assets_Base_Url',
583 array(
584 'url' => plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE ),
585 )
586 );
587 }
588
589 /**
590 * Check if an asset exists for a block.
591 *
592 * @param string $file Path of the file we are looking for.
593 *
594 * @return bool $block_has_asset Does the file exist.
595 */
596 public static function block_has_asset( $file ) {
597 return file_exists( JETPACK__PLUGIN_DIR . $file );
598 }
599
600 /**
601 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
602 *
603 * @param string $file Path of the file we are looking for.
604 *
605 * @return string $script_version Version number.
606 */
607 public static function get_asset_version( $file ) {
608 return Jetpack::is_development_version() && self::block_has_asset( $file )
609 ? filemtime( JETPACK__PLUGIN_DIR . $file )
610 : JETPACK__VERSION;
611 }
612
613 /**
614 * Load Gutenberg editor assets
615 *
616 * @since 6.7.0
617 *
618 * @return void
619 */
620 public static function enqueue_block_editor_assets() {
621 if ( ! self::should_load() ) {
622 return;
623 }
624
625 /**
626 * This can be called multiple times per page load in the admin, during the `enqueue_block_assets` action.
627 * These assets are necessary for the admin for editing but are not necessary for each pattern preview.
628 * Therefore we dequeue them, so they don't load for each pattern preview iframe.
629 */
630 if ( ! wp_should_load_block_editor_scripts_and_styles() ) {
631 wp_dequeue_script( 'jp-tracks' );
632 wp_dequeue_script( 'jetpack-blocks-editor' );
633
634 return;
635 }
636
637 $status = new Status();
638
639 // Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
640 if ( ! $status->is_offline_mode() && Jetpack::is_connection_ready() ) {
641 wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
642 }
643
644 $blocks_dir = self::get_blocks_directory();
645 $blocks_variation = self::blocks_variation();
646
647 if ( 'production' !== $blocks_variation ) {
648 $blocks_env = '-' . esc_attr( $blocks_variation );
649 } else {
650 $blocks_env = '';
651 }
652
653 Assets::register_script(
654 'jetpack-blocks-editor',
655 "{$blocks_dir}editor{$blocks_env}.js",
656 JETPACK__PLUGIN_FILE,
657 array( 'textdomain' => 'jetpack' )
658 );
659
660 // Hack around #20357 (specifically, that the editor bundle depends on
661 // wp-edit-post but wp-edit-post's styles break the Widget Editor and
662 // Site Editor) until a real fix gets unblocked.
663 // @todo Remove this once #20357 is properly fixed.
664 wp_styles()->query( 'jetpack-blocks-editor', 'registered' )->deps = array();
665
666 Assets::enqueue_script( 'jetpack-blocks-editor' );
667
668 wp_localize_script(
669 'jetpack-blocks-editor',
670 'Jetpack_Block_Assets_Base_Url',
671 array(
672 'url' => plugins_url( $blocks_dir . '/', JETPACK__PLUGIN_FILE ),
673 )
674 );
675
676 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
677 $user = wp_get_current_user();
678 $user_data = array(
679 'email' => $user->user_email,
680 'userid' => $user->ID,
681 'username' => $user->user_login,
682 );
683 $blog_id = get_current_blog_id();
684 $is_current_user_connected = true;
685 } else {
686 $user_data = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
687 $blog_id = Jetpack_Options::get_option( 'id', 0 );
688 $is_current_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected();
689 }
690
691 // AI Assistant
692 $ai_assistant_state = array(
693 'is-enabled' => apply_filters( 'jetpack_ai_enabled', true ),
694 'is-playground-visible' => Constants::is_true( 'JETPACK_AI_ASSISTANT_PLAYGROUND' ),
695 );
696
697 $screen_base = null;
698 if ( function_exists( 'get_current_screen' ) ) {
699 $screen_base = get_current_screen()->base;
700 }
701
702 $initial_state = array(
703 'available_blocks' => self::get_availability(),
704 'jetpack' => array(
705 'is_active' => Jetpack::is_connection_ready(),
706 'is_current_user_connected' => $is_current_user_connected,
707 /** This filter is documented in class.jetpack-gutenberg.php */
708 'enable_upgrade_nudge' => apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ),
709 'is_private_site' => $status->is_private_site(),
710 'is_coming_soon' => $status->is_coming_soon(),
711 'is_offline_mode' => $status->is_offline_mode(),
712 'is_newsletter_feature_enabled' => class_exists( '\Jetpack_Memberships' ),
713 /**
714 * Enable the RePublicize UI in the block editor context.
715 *
716 * @module publicize
717 *
718 * @since 10.3.0
719 * @deprecated $$next_version$$ This is a feature flag that is no longer used.
720 *
721 * @param bool true Enable the RePublicize UI in the block editor context. Defaults to true.
722 */
723 'republicize_enabled' => apply_filters( 'jetpack_block_editor_republicize_feature', true ),
724 /**
725 * Prevent the registration of the blocks from extensions/blocks/contact-form
726 * if the Forms package is enabled.
727 */
728 'is_form_package_enabled' => apply_filters( 'jetpack_contact_form_use_package', true ),
729 ),
730 'siteFragment' => $status->get_site_suffix(),
731 'adminUrl' => esc_url( admin_url() ),
732 'tracksUserData' => $user_data,
733 'wpcomBlogId' => $blog_id,
734 'allowedMimeTypes' => wp_get_mime_types(),
735 'siteLocale' => str_replace( '_', '-', get_locale() ),
736 'ai-assistant' => $ai_assistant_state,
737 'screenBase' => $screen_base,
738 );
739
740 if ( Jetpack::is_module_active( 'publicize' ) && function_exists( 'publicize_init' ) ) {
741 $publicize = publicize_init();
742 $sig_settings = new Automattic\Jetpack\Publicize\Social_Image_Generator\Settings();
743 $auto_conversion_settings = new Automattic\Jetpack\Publicize\Auto_Conversion\Settings();
744
745 $initial_state['social'] = array(
746 'sharesData' => $publicize->get_publicize_shares_info( $blog_id ),
747 'hasPaidPlan' => $publicize->has_paid_plan(),
748 'isEnhancedPublishingEnabled' => $publicize->has_enhanced_publishing_feature(),
749 'isSocialImageGeneratorAvailable' => $sig_settings->is_available(),
750 'isSocialImageGeneratorEnabled' => $sig_settings->is_enabled(),
751 'dismissedNotices' => $publicize->get_dismissed_notices(),
752 'supportedAdditionalConnections' => $publicize->get_supported_additional_connections(),
753 'autoConversionSettings' => array(
754 'available' => $auto_conversion_settings->is_available( 'image' ),
755 'image' => $auto_conversion_settings->is_enabled( 'image' ),
756 ),
757 'jetpackSharingSettingsUrl' => esc_url_raw( admin_url( 'admin.php?page=jetpack#/sharing' ) ),
758 );
759 }
760
761 wp_localize_script(
762 'jetpack-blocks-editor',
763 'Jetpack_Editor_Initial_State',
764 $initial_state
765 );
766
767 // Adds Connection package initial state.
768 Connection_Initial_State::render_script( 'jetpack-blocks-editor' );
769 }
770
771 /**
772 * Some blocks do not depend on a specific module,
773 * and can consequently be loaded outside of the usual modules.
774 * We will look for such modules in the extensions/ directory.
775 *
776 * @since 7.1.0
777 * @see wp_common_block_scripts_and_styles()
778 */
779 public static function load_independent_blocks() {
780 if ( self::should_load() ) {
781 /**
782 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
783 * If available, load them.
784 */
785 $directories = array( 'blocks', 'plugins', 'extended-blocks', 'shared', 'store' );
786
787 foreach ( static::get_extensions() as $extension ) {
788 foreach ( $directories as $dirname ) {
789 $path = JETPACK__PLUGIN_DIR . "extensions/{$dirname}/{$extension}/{$extension}.php";
790
791 if ( file_exists( $path ) ) {
792 include_once $path;
793 continue 2;
794 }
795 }
796 }
797 }
798 }
799
800 /**
801 * Loads PHP components of block editor extensions.
802 *
803 * @since 8.9.0
804 */
805 public static function load_block_editor_extensions() {
806 if ( self::should_load() ) {
807 // Block editor extensions to load.
808 $extensions_to_load = array(
809 'extended-blocks',
810 'plugins',
811 );
812
813 // Collect the extension paths.
814 foreach ( $extensions_to_load as $extension_to_load ) {
815 $extensions_folder = glob( JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/*' );
816
817 // Require each of the extension files, in case it exists.
818 foreach ( $extensions_folder as $extension_folder ) {
819 $name = basename( $extension_folder );
820 $extension_file_path = JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/' . $name . '/' . $name . '.php';
821
822 if ( file_exists( $extension_file_path ) ) {
823 include_once $extension_file_path;
824 }
825 }
826 }
827 }
828 }
829
830 /**
831 * Get CSS classes for a block.
832 *
833 * @since 7.7.0
834 *
835 * @param string $slug Block slug.
836 * @param array $attr Block attributes.
837 * @param array $extra Potential extra classes you may want to provide.
838 *
839 * @return string $classes List of CSS classes for a block.
840 */
841 public static function block_classes( $slug, $attr, $extra = array() ) {
842 _deprecated_function( __METHOD__, '9.0.0', 'Automattic\\Jetpack\\Blocks::classes' );
843 return Blocks::classes( $slug, $attr, $extra );
844 }
845
846 /**
847 * Determine whether a site should use the default set of blocks, or a custom set.
848 * Possible variations are currently beta, experimental, and production.
849 *
850 * @since 8.1.0
851 *
852 * @return string $block_varation production|beta|experimental
853 */
854 public static function blocks_variation() {
855 // Default to production blocks.
856 $block_varation = 'production';
857
858 /*
859 * Prefer to use this JETPACK_BLOCKS_VARIATION constant
860 * or the jetpack_blocks_variation filter
861 * to set the block variation in your code.
862 */
863 $default = Constants::get_constant( 'JETPACK_BLOCKS_VARIATION' );
864 if ( ! empty( $default ) && in_array( $default, array( 'beta', 'experimental', 'production' ), true ) ) {
865 $block_varation = $default;
866 }
867
868 /**
869 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
870 *
871 * @since 6.9.0
872 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
873 *
874 * @param boolean
875 */
876 $is_beta = apply_filters_deprecated(
877 'jetpack_load_beta_blocks',
878 array( false ),
879 'jetpack-11.8.0',
880 'jetpack_blocks_variation'
881 );
882
883 /*
884 * Switch to beta blocks if you use the JETPACK_BETA_BLOCKS constant
885 * or the deprecated jetpack_load_beta_blocks filter.
886 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
887 */
888 if (
889 empty( $default )
890 && (
891 $is_beta
892 || Constants::is_true( 'JETPACK_BETA_BLOCKS' )
893 )
894 ) {
895 $block_varation = 'beta';
896 }
897
898 /**
899 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
900 *
901 * @since 6.9.0
902 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
903 *
904 * @param boolean
905 */
906 $is_experimental = apply_filters_deprecated(
907 'jetpack_load_experimental_blocks',
908 array( false ),
909 'jetpack-11.8.0',
910 'jetpack_blocks_variation'
911 );
912
913 /*
914 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant
915 * or the deprecated jetpack_load_experimental_blocks filter.
916 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
917 */
918 if (
919 empty( $default )
920 && (
921 $is_experimental
922 || Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' )
923 )
924 ) {
925 $block_varation = 'experimental';
926 }
927
928 /**
929 * Allow customizing the variation of blocks in use on a site.
930 * Overwrites any previously set values, whether by constant or filter.
931 *
932 * @since 8.1.0
933 *
934 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
935 */
936 return apply_filters( 'jetpack_blocks_variation', $block_varation );
937 }
938
939 /**
940 * Get a list of extensions available for the variation you chose.
941 *
942 * @since 8.1.0
943 *
944 * @param obj $preset_extensions_manifest List of extensions available in Jetpack.
945 * @param string $blocks_variation Subset of blocks. production|beta|experimental.
946 *
947 * @return array $preset_extensions Array of extensions for that variation
948 */
949 public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
950 $preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
951 ? (array) $preset_extensions_manifest->{ $blocks_variation }
952 : array();
953
954 /*
955 * Experimental and Beta blocks need the production blocks as well.
956 */
957 if (
958 'experimental' === $blocks_variation
959 || 'beta' === $blocks_variation
960 ) {
961 $production_extensions = isset( $preset_extensions_manifest->production )
962 ? (array) $preset_extensions_manifest->production
963 : array();
964
965 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
966 }
967
968 /*
969 * Beta blocks need the experimental blocks as well.
970 *
971 * If you've chosen to see Beta blocks,
972 * we want to make all blocks available to you:
973 * - Production
974 * - Experimental
975 * - Beta
976 */
977 if ( 'beta' === $blocks_variation ) {
978 $production_extensions = isset( $preset_extensions_manifest->experimental )
979 ? (array) $preset_extensions_manifest->experimental
980 : array();
981
982 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
983 }
984
985 return $preset_extensions;
986 }
987
988 /**
989 * Validate a URL used in a SSR block.
990 *
991 * @since 8.3.0
992 *
993 * @param string $url URL saved as an attribute in block.
994 * @param array $allowed Array of allowed hosts for that block, or regexes to check against.
995 * @param bool $is_regex Array of regexes matching the URL that could be used in block.
996 *
997 * @return bool|string
998 */
999 public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
1000 if (
1001 empty( $url )
1002 || ! is_array( $allowed )
1003 || empty( $allowed )
1004 ) {
1005 return false;
1006 }
1007
1008 $url_components = wp_parse_url( $url );
1009
1010 // Bail early if we cannot find a host.
1011 if ( empty( $url_components['host'] ) ) {
1012 return false;
1013 }
1014
1015 // Normalize URL.
1016 $url = sprintf(
1017 '%s://%s%s%s',
1018 isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
1019 $url_components['host'],
1020 isset( $url_components['path'] ) ? $url_components['path'] : '/',
1021 isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
1022 );
1023
1024 if ( ! empty( $url_components['fragment'] ) ) {
1025 $url = $url . '#' . rawurlencode( $url_components['fragment'] );
1026 }
1027
1028 /*
1029 * If we're using an allowed list of hosts,
1030 * check if the URL belongs to one of the domains allowed for that block.
1031 */
1032 if (
1033 false === $is_regex
1034 && in_array( $url_components['host'], $allowed, true )
1035 ) {
1036 return $url;
1037 }
1038
1039 /*
1040 * If we are using an array of regexes to check against,
1041 * loop through that.
1042 */
1043 if ( true === $is_regex ) {
1044 foreach ( $allowed as $regex ) {
1045 if ( 1 === preg_match( $regex, $url ) ) {
1046 return $url;
1047 }
1048 }
1049 }
1050
1051 return false;
1052 }
1053
1054 /**
1055 * Determines whether a preview of the block with an upgrade nudge should
1056 * be displayed for admins on the site frontend.
1057 *
1058 * @since 8.4.0
1059 *
1060 * @param array $availability_for_block The availability for the block.
1061 *
1062 * @return bool
1063 */
1064 public static function should_show_frontend_preview( $availability_for_block ) {
1065 return (
1066 isset( $availability_for_block['details']['required_plan'] )
1067 && current_user_can( 'manage_options' )
1068 && ! is_feed()
1069 );
1070 }
1071
1072 /**
1073 * Output an UpgradeNudge Component on the frontend of a site.
1074 *
1075 * @since 8.4.0
1076 *
1077 * @param string $plan The plan that users need to purchase to make the block work.
1078 *
1079 * @return string
1080 */
1081 public static function upgrade_nudge( $plan ) {
1082 require_once JETPACK__PLUGIN_DIR . '_inc/lib/components.php';
1083 return Jetpack_Components::render_upgrade_nudge(
1084 array(
1085 'plan' => $plan,
1086 )
1087 );
1088 }
1089
1090 /**
1091 * Output a notice within a block.
1092 *
1093 * @since 8.6.0
1094 *
1095 * @param string $message Notice we want to output.
1096 * @param string $status Status of the notice. Can be one of success, info, warning, error. info by default.
1097 * @param string $classes List of CSS classes.
1098 *
1099 * @return string
1100 */
1101 public static function notice( $message, $status = 'info', $classes = '' ) {
1102 if (
1103 empty( $message )
1104 || ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1105 ) {
1106 return '';
1107 }
1108
1109 $color = '';
1110 switch ( $status ) {
1111 case 'success':
1112 $color = '#00a32a';
1113 break;
1114 case 'warning':
1115 $color = '#dba617';
1116 break;
1117 case 'error':
1118 $color = '#d63638';
1119 break;
1120 case 'info':
1121 default:
1122 $color = '#72aee6';
1123 break;
1124 }
1125
1126 return sprintf(
1127 '<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1128 esc_attr( $status ),
1129 wp_kses(
1130 $message,
1131 array(
1132 'br' => array(),
1133 'p' => array(),
1134 'a' => array(
1135 'href' => array(),
1136 'target' => array(),
1137 'rel' => array(),
1138 ),
1139 )
1140 ),
1141 esc_attr( $classes ),
1142 sanitize_hex_color( $color )
1143 );
1144 }
1145
1146 /**
1147 * Retrieve site-specific features for Simple sites.
1148 *
1149 * We're caching the data for the lifetime of the request, because it can be slow to calculate,
1150 * and it can be called multiple times per single request.
1151 *
1152 * We intentionally don't use object caching or any other type of persistent caching,
1153 * in order to avoid complex cache invalidation on subscription addition or removal.
1154 *
1155 * @since 10.7
1156 *
1157 * @return array
1158 */
1159 private static function get_site_specific_features() {
1160 $current_blog_id = get_current_blog_id();
1161
1162 if ( isset( self::$site_specific_features[ $current_blog_id ] ) ) {
1163 return self::$site_specific_features[ $current_blog_id ];
1164 }
1165
1166 if ( ! class_exists( 'Store_Product_List' ) ) {
1167 require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1168 }
1169
1170 $site_specific_features = Store_Product_List::get_site_specific_features_data( $current_blog_id );
1171 self::$site_specific_features[ $current_blog_id ] = $site_specific_features;
1172
1173 return $site_specific_features;
1174 }
1175
1176 /**
1177 * Set the availability of the block as the editor
1178 * is loaded.
1179 *
1180 * @param string $slug Slug of the block.
1181 */
1182 public static function set_availability_for_plan( $slug ) {
1183 $slug = self::remove_extension_prefix( $slug );
1184
1185 if ( Jetpack_Plan::supports( $slug ) ) {
1186 self::set_extension_available( $slug );
1187 return;
1188 }
1189
1190 // Check what's the minimum plan where the feature is available.
1191 $plan = '';
1192 $features_data = array();
1193 $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
1194 $is_atomic_site = ( new Host() )->is_woa_site();
1195
1196 if ( $is_simple_site || $is_atomic_site ) {
1197 // Simple sites.
1198 if ( $is_simple_site ) {
1199 $features_data = self::get_site_specific_features();
1200 } else {
1201 // Atomic sites.
1202 $option = get_option( 'jetpack_active_plan' );
1203 if ( isset( $option['features'] ) ) {
1204 $features_data = $option['features'];
1205 }
1206 }
1207
1208 if ( ! empty( $features_data['available'][ $slug ] ) ) {
1209 $plan = $features_data['available'][ $slug ][0];
1210 }
1211 } else {
1212 // Jetpack sites.
1213 $plan = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1214 }
1215
1216 self::set_extension_unavailable(
1217 $slug,
1218 'missing_plan',
1219 array(
1220 'required_feature' => $slug,
1221 'required_plan' => $plan,
1222 )
1223 );
1224 }
1225
1226 /**
1227 * Wraps the suplied render_callback in a function to check
1228 * the availability of the block before rendering it.
1229 *
1230 * @param string $slug The block slug, used to check for availability.
1231 * @param callable $render_callback The render_callback that will be called if the block is available.
1232 */
1233 public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1234 return function ( $prepared_attributes, $block_content, $block ) use ( $render_callback, $slug ) {
1235 $availability = self::get_cached_availability();
1236 $bare_slug = self::remove_extension_prefix( $slug );
1237 if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1238 return call_user_func( $render_callback, $prepared_attributes, $block_content );
1239 }
1240
1241 // A preview of the block is rendered for admins on the frontend with an upgrade nudge.
1242 if ( isset( $availability[ $bare_slug ] ) ) {
1243 if ( self::should_show_frontend_preview( $availability[ $bare_slug ] ) ) {
1244 $block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content );
1245
1246 // If the upgrade nudge isn't already being displayed by a parent block, display the nudge.
1247 if ( isset( $block->attributes['shouldDisplayFrontendBanner'] ) && $block->attributes['shouldDisplayFrontendBanner'] ) {
1248 $upgrade_nudge = self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
1249 return $upgrade_nudge . $block_preview;
1250 }
1251
1252 return $block_preview;
1253 }
1254 }
1255
1256 return null;
1257 };
1258 }
1259
1260 /**
1261 * Display a message to site editors and roles above when a block is no longer supported.
1262 * This is only displayed on the frontend.
1263 *
1264 * @since 12.3
1265 *
1266 * @param string $block_content The block content.
1267 * @param array $block The full block, including name and attributes.
1268 *
1269 * @return string
1270 */
1271 public static function display_deprecated_block_message( $block_content, $block ) {
1272 if ( in_array( $block['blockName'], self::$deprecated_blocks, true ) ) {
1273 if ( current_user_can( 'edit_posts' ) ) {
1274 $block_content = self::notice(
1275 __( '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' ),
1276 'warning',
1277 'jetpack-block-deprecated'
1278 );
1279 } else {
1280 $block_content = '';
1281 }
1282 }
1283
1284 return $block_content;
1285 }
1286 }
1287
1288 if ( ( new Host() )->is_woa_site() ) {
1289 /**
1290 * Enable upgrade nudge for Atomic sites.
1291 * This feature is false as default,
1292 * so let's enable it through this filter.
1293 *
1294 * More doc: https://github.com/Automattic/jetpack/blob/trunk/projects/plugins/jetpack/extensions/README.md#upgrades-for-blocks
1295 */
1296 add_filter( 'jetpack_block_editor_enable_upgrade_nudge', '__return_true' );
1297 }
1298