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

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