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

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