PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 12.2
Jetpack – WP Security, Backup, Speed, & Growth v12.2
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / class.jetpack-gutenberg.php

class.jetpack-gutenberg.php in Jetpack – WP Security, Backup, Speed, & Growth 12.2, at class.jetpack-gutenberg.php

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