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