Completed
Push — use/blocks-package-registratio... ( 96065a )
by Jeremy
08:23
created

class.jetpack-gutenberg.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 Jetpack
7
 */
8
9
use Automattic\Jetpack\Blocks;
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Status;
12
13
/**
14
 * Wrapper function to safely register a gutenberg block type
15
 *
16
 * @param string $slug Slug of the block.
17
 * @param array  $args Arguments that are passed into register_block_type.
18
 *
19
 * @see register_block_type
20
 *
21
 * @since 6.7.0
22
 *
23
 * @return WP_Block_Type|false The registered block type on success, or false on failure.
24
 */
25
function jetpack_register_block( $slug, $args = array() ) {
26 View Code Duplication
	if ( 0 !== strpos( $slug, 'jetpack/' ) && ! strpos( $slug, '/' ) ) {
27
		_doing_it_wrong( 'jetpack_register_block', 'Prefix the block with jetpack/ ', '7.1.0' );
28
		$slug = 'jetpack/' . $slug;
29
	}
30
31 View Code Duplication
	if ( isset( $args['version_requirements'] )
32
		&& ! Jetpack_Gutenberg::is_gutenberg_version_available( $args['version_requirements'], $slug ) ) {
33
		return false;
34
	}
35
36
	// Checking whether block is registered to ensure it isn't registered twice.
37
	if ( Jetpack_Gutenberg::is_registered( $slug ) ) {
38
		return false;
39
	}
40
41
	$feature_name = Jetpack_Gutenberg::remove_extension_prefix( $slug );
42
	// If the block is dynamic, and a Jetpack block, wrap the render_callback to check availability.
43
	if (
44
		isset( $args['plan_check'] )
45
		&& true === $args['plan_check']
46
	) {
47
		if ( isset( $args['render_callback'] ) ) {
48
			$args['render_callback'] = Jetpack_Gutenberg::get_render_callback_with_availability_check( $feature_name, $args['render_callback'] );
49
		}
50
		$method_name = 'set_availability_for_plan';
51
	} else {
52
		$method_name = 'set_extension_available';
53
	}
54
55
	add_action(
56
		'jetpack_register_gutenberg_extensions',
57
		function() use ( $feature_name, $method_name ) {
58
			call_user_func( array( 'Jetpack_Gutenberg', $method_name ), $feature_name );
59
		}
60
	);
61
62
	return register_block_type( $slug, $args );
63
}
64
65
/**
66
 * Helper function to register a Jetpack Gutenberg plugin
67
 *
68
 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_available() instead
69
 *
70
 * @param string $slug Slug of the plugin.
71
 *
72
 * @since 6.9.0
73
 *
74
 * @return void
75
 */
76
function jetpack_register_plugin( $slug ) {
77
	_deprecated_function( __FUNCTION__, '7.1', 'Jetpack_Gutenberg::set_extension_available' );
78
79
	Jetpack_Gutenberg::register_plugin( $slug );
80
}
81
82
/**
83
 * Set the reason why an extension (block or plugin) is unavailable
84
 *
85
 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_unavailable() instead
86
 *
87
 * @param string $slug Slug of the block.
88
 * @param string $reason A string representation of why the extension is unavailable.
89
 *
90
 * @since 7.0.0
91
 *
92
 * @return void
93
 */
94
function jetpack_set_extension_unavailability_reason( $slug, $reason ) {
95
	_deprecated_function( __FUNCTION__, '7.1', 'Jetpack_Gutenberg::set_extension_unavailable' );
96
97
	Jetpack_Gutenberg::set_extension_unavailability_reason( $slug, $reason );
98
}
99
100
/**
101
 * General Gutenberg editor specific functionality
102
 */
103
class Jetpack_Gutenberg {
104
105
	/**
106
	 * Only these extensions can be registered. Used to control availability of beta blocks.
107
	 *
108
	 * @var array Extensions allowed list.
109
	 */
110
	private static $extensions = array();
111
112
	/**
113
	 * Keeps track of the reasons why a given extension is unavailable.
114
	 *
115
	 * @var array Extensions availability information
116
	 */
117
	private static $availability = array();
118
119
	/**
120
	 * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
121
	 * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
122
	 * optionally fall back to that.
123
	 *
124
	 * @param array  $version_requirements An array containing the required Gutenberg version and, if known, the WordPress version that was released with this minimum version.
125
	 * @param string $slug The slug of the block or plugin that has the gutenberg version requirement.
126
	 *
127
	 * @since 8.3.0
128
	 *
129
	 * @return boolean True if the version of gutenberg required by the block or plugin is available.
130
	 */
131 View Code Duplication
	public static function is_gutenberg_version_available( $version_requirements, $slug ) {
132
		global $wp_version;
133
134
		// Bail if we don't at least have the gutenberg version requirement, the WP version is optional.
135
		if ( empty( $version_requirements['gutenberg'] ) ) {
136
			return false;
137
		}
138
139
		// If running a local dev build of gutenberg plugin GUTENBERG_DEVELOPMENT_MODE is set so assume correct version.
140
		if ( defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE ) {
141
			return true;
142
		}
143
144
		$version_available = false;
145
146
		// If running a production build of the gutenberg plugin then GUTENBERG_VERSION is set, otherwise if WP version
147
		// with required version of Gutenberg is known check that.
148
		if ( defined( 'GUTENBERG_VERSION' ) ) {
149
			$version_available = version_compare( GUTENBERG_VERSION, $version_requirements['gutenberg'], '>=' );
150
		} elseif ( ! empty( $version_requirements['wp'] ) ) {
151
			$version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
152
		}
153
154
		if ( ! $version_available ) {
155
			self::set_extension_unavailable(
156
				$slug,
157
				'incorrect_gutenberg_version',
158
				array(
159
					'required_feature' => $slug,
160
					'required_version' => $version_requirements,
161
					'current_version'  => array(
162
						'wp'        => $wp_version,
163
						'gutenberg' => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null,
164
					),
165
				)
166
			);
167
		}
168
169
		return $version_available;
170
	}
171
172
	/**
173
	 * Prepend the 'jetpack/' prefix to a block name
174
	 *
175
	 * @param string $block_name The block name.
176
	 *
177
	 * @return string The prefixed block name.
178
	 */
179
	private static function prepend_block_prefix( $block_name ) {
180
		return 'jetpack/' . $block_name;
181
	}
182
183
	/**
184
	 * Remove the 'jetpack/' or jetpack-' prefix from an extension name
185
	 *
186
	 * @param string $extension_name The extension name.
187
	 *
188
	 * @return string The unprefixed extension name.
189
	 */
190
	public static function remove_extension_prefix( $extension_name ) {
191 View Code Duplication
		if ( 0 === strpos( $extension_name, 'jetpack/' ) || 0 === strpos( $extension_name, 'jetpack-' ) ) {
192
			return substr( $extension_name, strlen( 'jetpack/' ) );
193
		}
194
		return $extension_name;
195
	}
196
197
	/**
198
	 * Whether two arrays share at least one item
199
	 *
200
	 * @param array $a An array.
201
	 * @param array $b Another array.
202
	 *
203
	 * @return boolean True if $a and $b share at least one item
204
	 */
205
	protected static function share_items( $a, $b ) {
206
		return count( array_intersect( $a, $b ) ) > 0;
207
	}
208
209
	/**
210
	 * Register a block
211
	 *
212
	 * @deprecated 7.1.0 Use jetpack_register_block() instead
213
	 *
214
	 * @param string $slug Slug of the block.
215
	 * @param array  $args Arguments that are passed into register_block_type().
216
	 */
217
	public static function register_block( $slug, $args ) {
218
		_deprecated_function( __METHOD__, '7.1', 'jetpack_register_block' );
219
220
		jetpack_register_block( 'jetpack/' . $slug, $args );
221
	}
222
223
	/**
224
	 * Register a plugin
225
	 *
226
	 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_available() instead
227
	 *
228
	 * @param string $slug Slug of the plugin.
229
	 */
230
	public static function register_plugin( $slug ) {
231
		_deprecated_function( __METHOD__, '7.1', 'Jetpack_Gutenberg::set_extension_available' );
232
233
		self::set_extension_available( $slug );
234
	}
235
236
	/**
237
	 * Register a block
238
	 *
239
	 * @deprecated 7.0.0 Use jetpack_register_block() instead
240
	 *
241
	 * @param string $slug Slug of the block.
242
	 * @param array  $args Arguments that are passed into the register_block_type.
243
	 * @param array  $availability array containing if a block is available and the reason when it is not.
244
	 */
245
	public static function register( $slug, $args, $availability ) {
246
		_deprecated_function( __METHOD__, '7.0', 'jetpack_register_block' );
247
248
		if ( isset( $availability['available'] ) && ! $availability['available'] ) {
249
			self::set_extension_unavailability_reason( $slug, $availability['unavailable_reason'] );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Gutenberg::set_e...unavailability_reason() has been deprecated with message: 7.1.0 Use set_extension_unavailable() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
250
		} else {
251
			self::register_block( $slug, $args );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Gutenberg::register_block() has been deprecated with message: 7.1.0 Use jetpack_register_block() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
252
		}
253
	}
254
255
	/**
256
	 * Set a (non-block) extension as available
257
	 *
258
	 * @param string $slug Slug of the extension.
259
	 */
260
	public static function set_extension_available( $slug ) {
261
		self::$availability[ self::remove_extension_prefix( $slug ) ] = true;
262
	}
263
264
	/**
265
	 * Set the reason why an extension (block or plugin) is unavailable
266
	 *
267
	 * @param string $slug Slug of the extension.
268
	 * @param string $reason A string representation of why the extension is unavailable.
269
	 * @param array  $details A free-form array containing more information on why the extension is unavailable.
270
	 */
271
	public static function set_extension_unavailable( $slug, $reason, $details = array() ) {
272
		if (
273
			// Extensions that require a plan may be eligible for upgrades.
274
			'missing_plan' === $reason
275
			&& (
276
				/**
277
				 * Filter 'jetpack_block_editor_enable_upgrade_nudge' with `true` to enable or `false`
278
				 * to disable paid feature upgrade nudges in the block editor.
279
				 *
280
				 * When this is changed to default to `true`, you should also update `modules/memberships/class-jetpack-memberships.php`
281
				 * See https://github.com/Automattic/jetpack/pull/13394#pullrequestreview-293063378
282
				 *
283
				 * @since 7.7.0
284
				 *
285
				 * @param boolean
286
				 */
287
				! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
288
				/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
289
				|| ! apply_filters( 'jetpack_show_promotions', true )
290
			)
291
		) {
292
			// The block editor may apply an upgrade nudge if `missing_plan` is the reason.
293
			// Add a descriptive suffix to disable behavior but provide informative reason.
294
			$reason .= '__nudge_disabled';
295
		}
296
297
		self::$availability[ self::remove_extension_prefix( $slug ) ] = array(
298
			'reason'  => $reason,
299
			'details' => $details,
300
		);
301
	}
302
303
	/**
304
	 * Set the reason why an extension (block or plugin) is unavailable
305
	 *
306
	 * @deprecated 7.1.0 Use set_extension_unavailable() instead
307
	 *
308
	 * @param string $slug Slug of the extension.
309
	 * @param string $reason A string representation of why the extension is unavailable.
310
	 */
311
	public static function set_extension_unavailability_reason( $slug, $reason ) {
312
		_deprecated_function( __METHOD__, '7.1', 'Jetpack_Gutenberg::set_extension_unavailable' );
313
314
		self::set_extension_unavailable( $slug, $reason );
315
	}
316
317
	/**
318
	 * Set up a list of allowed block editor extensions
319
	 *
320
	 * @return void
321
	 */
322
	public static function init() {
323
		if ( ! self::should_load() ) {
324
			return;
325
		}
326
327
		/**
328
		 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
329
		 *
330
		 * @since 6.9.0
331
		 *
332
		 * @param boolean
333
		 */
334
		if ( apply_filters( 'jetpack_load_beta_blocks', false ) ) {
335
			Constants::set_constant( 'JETPACK_BETA_BLOCKS', true );
336
		}
337
338
		/**
339
		 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
340
		 *
341
		 * @since 8.4.0
342
		 *
343
		 * @param boolean
344
		 */
345
		if ( apply_filters( 'jetpack_load_experimental_blocks', false ) ) {
346
			Constants::set_constant( 'JETPACK_EXPERIMENTAL_BLOCKS', true );
347
		}
348
349
		/**
350
		 * Filter the list of block editor extensions that are available through Jetpack.
351
		 *
352
		 * @since 7.0.0
353
		 *
354
		 * @param array
355
		 */
356
		self::$extensions = apply_filters( 'jetpack_set_available_extensions', self::get_available_extensions() );
357
358
		/**
359
		 * Filter the list of block editor plugins that are available through Jetpack.
360
		 *
361
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
362
		 *
363
		 * @since 6.8.0
364
		 *
365
		 * @param array
366
		 */
367
		self::$extensions = apply_filters( 'jetpack_set_available_blocks', self::$extensions );
368
369
		/**
370
		 * Filter the list of block editor plugins that are available through Jetpack.
371
		 *
372
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
373
		 *
374
		 * @since 6.9.0
375
		 *
376
		 * @param array
377
		 */
378
		self::$extensions = apply_filters( 'jetpack_set_available_plugins', self::$extensions );
379
	}
380
381
	/**
382
	 * Resets the class to its original state
383
	 *
384
	 * Used in unit tests
385
	 *
386
	 * @return void
387
	 */
388
	public static function reset() {
389
		self::$extensions   = array();
390
		self::$availability = array();
391
	}
392
393
	/**
394
	 * Return the Gutenberg extensions (blocks and plugins) directory
395
	 *
396
	 * @return string The Gutenberg extensions directory
397
	 */
398
	public static function get_blocks_directory() {
399
		/**
400
		 * Filter to select Gutenberg blocks directory
401
		 *
402
		 * @since 6.9.0
403
		 *
404
		 * @param string default: '_inc/blocks/'
405
		 */
406
		return apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
407
	}
408
409
	/**
410
	 * Checks for a given .json file in the blocks folder.
411
	 *
412
	 * @param string $preset The name of the .json file to look for.
413
	 *
414
	 * @return bool True if the file is found.
415
	 */
416
	public static function preset_exists( $preset ) {
417
		return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
418
	}
419
420
	/**
421
	 * Decodes JSON loaded from a preset file in the blocks folder
422
	 *
423
	 * @param string $preset The name of the .json file to load.
424
	 *
425
	 * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
426
	 */
427
	public static function get_preset( $preset ) {
428
		return json_decode(
429
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
430
			file_get_contents( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' )
431
		);
432
	}
433
434
	/**
435
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
436
	 *
437
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
438
	 */
439
	public static function get_jetpack_gutenberg_extensions_allowed_list() {
440
		$preset_extensions_manifest = self::preset_exists( 'index' )
441
			? self::get_preset( 'index' )
442
			: (object) array();
443
		$blocks_variation           = self::blocks_variation();
444
445
		return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
446
	}
447
448
	/**
449
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
450
	 *
451
	 * @deprecated 8.7.0 Use get_jetpack_gutenberg_extensions_allowed_list()
452
	 *
453
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
454
	 */
455
	public static function get_jetpack_gutenberg_extensions_whitelist() {
456
		_deprecated_function( __FUNCTION__, 'jetpack-8.7.0', 'Jetpack_Gutenberg::get_jetpack_gutenberg_extensions_allowed_list' );
457
		return self::get_jetpack_gutenberg_extensions_allowed_list();
458
	}
459
460
	/**
461
	 * Returns a diff from a combined list of allowed extensions and extensions determined to be excluded
462
	 *
463
	 * @param  array $allowed_extensions An array of allowed extensions.
464
	 *
465
	 * @return array A list of blocks: eg array( 'publicize', 'markdown' )
466
	 */
467
	public static function get_available_extensions( $allowed_extensions = null ) {
468
		$exclusions         = get_option( 'jetpack_excluded_extensions', array() );
469
		$allowed_extensions = is_null( $allowed_extensions ) ? self::get_jetpack_gutenberg_extensions_allowed_list() : $allowed_extensions;
470
471
		return array_diff( $allowed_extensions, $exclusions );
472
	}
473
474
	/**
475
	 * Return true if the extension has been registered and there's nothing in the availablilty array.
476
	 *
477
	 * @param string $extension The name of the extension.
478
	 *
479
	 * @return bool whether the extension has been registered and there's nothing in the availablilty array.
480
	 */
481
	public static function is_registered_and_no_entry_in_availability( $extension ) {
482
		return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
483
	}
484
485
	/**
486
	 * Return true if the extension has a true entry in the availablilty array.
487
	 *
488
	 * @param string $extension The name of the extension.
489
	 *
490
	 * @return bool whether the extension has a true entry in the availablilty array.
491
	 */
492
	public static function is_available( $extension ) {
493
		return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
494
	}
495
496
	/**
497
	 * Get availability of each block / plugin.
498
	 *
499
	 * @return array A list of block and plugins and their availablity status
500
	 */
501
	public static function get_availability() {
502
		/**
503
		 * Fires before Gutenberg extensions availability is computed.
504
		 *
505
		 * In the function call you supply, use `jetpack_register_block()` to set a block as available.
506
		 * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
507
		 * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
508
		 * but marked as unavailable).
509
		 *
510
		 * @since 7.0.0
511
		 */
512
		do_action( 'jetpack_register_gutenberg_extensions' );
513
514
		$available_extensions = array();
515
516
		foreach ( self::$extensions as $extension ) {
517
			$is_available                       = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
518
			$available_extensions[ $extension ] = array(
519
				'available' => $is_available,
520
			);
521
522
			if ( ! $is_available ) {
523
				$reason  = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
524
				$details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
525
				$available_extensions[ $extension ]['unavailable_reason'] = $reason;
526
				$available_extensions[ $extension ]['details']            = $details;
527
			}
528
		}
529
530
		return $available_extensions;
531
	}
532
533
	/**
534
	 * Check if an extension/block is already registered
535
	 *
536
	 * @since 7.2
537
	 *
538
	 * @param string $slug Name of extension/block to check.
539
	 *
540
	 * @return bool
541
	 */
542
	public static function is_registered( $slug ) {
543
		return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
544
	}
545
546
	/**
547
	 * Check if Gutenberg editor is available
548
	 *
549
	 * @since 6.7.0
550
	 *
551
	 * @return bool
552
	 */
553
	public static function is_gutenberg_available() {
554
		return true;
555
	}
556
557
	/**
558
	 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
559
	 *
560
	 * Loading blocks and plugins is enabled by default and may be disabled via filter:
561
	 *   add_filter( 'jetpack_gutenberg', '__return_false' );
562
	 *
563
	 * @since 6.9.0
564
	 *
565
	 * @return bool
566
	 */
567
	public static function should_load() {
568
		if ( ! Jetpack::is_active() && ! ( new Status() )->is_offline_mode() ) {
569
			return false;
570
		}
571
572
		/**
573
		 * Filter to disable Gutenberg blocks
574
		 *
575
		 * @since 6.5.0
576
		 *
577
		 * @param bool true Whether to load Gutenberg blocks
578
		 */
579
		return (bool) apply_filters( 'jetpack_gutenberg', true );
580
	}
581
582
	/**
583
	 * Only enqueue block assets when needed.
584
	 *
585
	 * @param string $type Slug of the block.
586
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
587
	 *                                    detected script dependencies from the webpack build.
588
	 *
589
	 * @return void
590
	 */
591
	public static function load_assets_as_required( $type, $script_dependencies = array() ) {
592
		if ( is_admin() ) {
593
			// A block's view assets will not be required in wp-admin.
594
			return;
595
		}
596
597
		$type = sanitize_title_with_dashes( $type );
598
		self::load_styles_as_required( $type );
599
		self::load_scripts_as_required( $type, $script_dependencies );
600
	}
601
602
	/**
603
	 * Only enqueue block sytles when needed.
604
	 *
605
	 * @param string $type Slug of the block.
606
	 *
607
	 * @since 7.2.0
608
	 *
609
	 * @return void
610
	 */
611
	public static function load_styles_as_required( $type ) {
612
		if ( is_admin() ) {
613
			// A block's view assets will not be required in wp-admin.
614
			return;
615
		}
616
617
		// Enqueue styles.
618
		$style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
619
		if ( self::block_has_asset( $style_relative_path ) ) {
620
			$style_version = self::get_asset_version( $style_relative_path );
621
			$view_style    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
622
			wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
623
		}
624
625
	}
626
627
	/**
628
	 * Only enqueue block scripts when needed.
629
	 *
630
	 * @param string $type Slug of the block.
631
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
632
	 *                             detected script dependencies from the webpack build.
633
	 *
634
	 * @since 7.2.0
635
	 *
636
	 * @return void
637
	 */
638
	public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
639
		if ( is_admin() ) {
640
			// A block's view assets will not be required in wp-admin.
641
			return;
642
		}
643
644
		// Enqueue script.
645
		$script_relative_path  = self::get_blocks_directory() . $type . '/view.js';
646
		$script_deps_path      = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
647
		$script_dependencies[] = 'wp-polyfill';
648
		if ( file_exists( $script_deps_path ) ) {
649
			$asset_manifest      = include $script_deps_path;
650
			$script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
651
		}
652
653
		if ( ! Blocks::is_amp_request() && self::block_has_asset( $script_relative_path ) ) {
654
			$script_version = self::get_asset_version( $script_relative_path );
655
			$view_script    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
656
			wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
657
		}
658
659
		wp_localize_script(
660
			'jetpack-block-' . $type,
661
			'Jetpack_Block_Assets_Base_Url',
662
			plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE )
663
		);
664
	}
665
666
	/**
667
	 * Check if an asset exists for a block.
668
	 *
669
	 * @param string $file Path of the file we are looking for.
670
	 *
671
	 * @return bool $block_has_asset Does the file exist.
672
	 */
673
	public static function block_has_asset( $file ) {
674
		return file_exists( JETPACK__PLUGIN_DIR . $file );
675
	}
676
677
	/**
678
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
679
	 *
680
	 * @param string $file Path of the file we are looking for.
681
	 *
682
	 * @return string $script_version Version number.
683
	 */
684
	public static function get_asset_version( $file ) {
685
		return Jetpack::is_development_version() && self::block_has_asset( $file )
686
			? filemtime( JETPACK__PLUGIN_DIR . $file )
687
			: JETPACK__VERSION;
688
	}
689
690
	/**
691
	 * Load Gutenberg editor assets
692
	 *
693
	 * @since 6.7.0
694
	 *
695
	 * @return void
696
	 */
697
	public static function enqueue_block_editor_assets() {
698
		if ( ! self::should_load() ) {
699
			return;
700
		}
701
702
		// Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
703
		if ( ! ( new Status() )->is_offline_mode() && Jetpack::is_active() ) {
704
			wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
705
		}
706
707
		$rtl              = is_rtl() ? '.rtl' : '';
708
		$blocks_dir       = self::get_blocks_directory();
709
		$blocks_variation = self::blocks_variation();
710
711
		if ( 'production' !== $blocks_variation ) {
712
			$blocks_env = '-' . esc_attr( $blocks_variation );
713
		} else {
714
			$blocks_env = '';
715
		}
716
717
		$editor_script = plugins_url( "{$blocks_dir}editor{$blocks_env}.js", JETPACK__PLUGIN_FILE );
718
		$editor_style  = plugins_url( "{$blocks_dir}editor{$blocks_env}{$rtl}.css", JETPACK__PLUGIN_FILE );
719
720
		$editor_deps_path = JETPACK__PLUGIN_DIR . $blocks_dir . "editor{$blocks_env}.asset.php";
721
		$editor_deps      = array( 'wp-polyfill' );
722
		if ( file_exists( $editor_deps_path ) ) {
723
			$asset_manifest = include $editor_deps_path;
724
			$editor_deps    = $asset_manifest['dependencies'];
725
		}
726
727
		$version = Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
728
			? filemtime( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
729
			: JETPACK__VERSION;
730
731
		if ( method_exists( 'Jetpack', 'build_raw_urls' ) ) {
732
			$site_fragment = Jetpack::build_raw_urls( home_url() );
733
		} elseif ( class_exists( 'WPCOM_Masterbar' ) && method_exists( 'WPCOM_Masterbar', 'get_calypso_site_slug' ) ) {
734
			$site_fragment = WPCOM_Masterbar::get_calypso_site_slug( get_current_blog_id() );
735
		} else {
736
			$site_fragment = '';
737
		}
738
739
		wp_enqueue_script(
740
			'jetpack-blocks-editor',
741
			$editor_script,
742
			$editor_deps,
743
			$version,
744
			false
745
		);
746
747
		wp_localize_script(
748
			'jetpack-blocks-editor',
749
			'Jetpack_Block_Assets_Base_Url',
750
			plugins_url( $blocks_dir . '/', JETPACK__PLUGIN_FILE )
751
		);
752
753
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
754
			$user                      = wp_get_current_user();
755
			$user_data                 = array(
756
				'userid'   => $user->ID,
757
				'username' => $user->user_login,
758
			);
759
			$blog_id                   = get_current_blog_id();
760
			$is_current_user_connected = true;
761
		} else {
762
			$user_data                 = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
763
			$blog_id                   = Jetpack_Options::get_option( 'id', 0 );
764
			$is_current_user_connected = Jetpack::is_user_connected();
765
		}
766
767
		wp_localize_script(
768
			'jetpack-blocks-editor',
769
			'Jetpack_Editor_Initial_State',
770
			array(
771
				'available_blocks' => self::get_availability(),
772
				'jetpack'          => array(
773
					'is_active'                 => Jetpack::is_active(),
774
					'is_current_user_connected' => $is_current_user_connected,
775
					/** This filter is documented in class.jetpack-gutenberg.php */
776
					'enable_upgrade_nudge'      => apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ),
777
				),
778
				'siteFragment'     => $site_fragment,
779
				'adminUrl'         => esc_url( admin_url() ),
780
				'tracksUserData'   => $user_data,
781
				'wpcomBlogId'      => $blog_id,
782
				'allowedMimeTypes' => wp_get_mime_types(),
783
			)
784
		);
785
786
		wp_set_script_translations( 'jetpack-blocks-editor', 'jetpack' );
787
788
		wp_enqueue_style( 'jetpack-blocks-editor', $editor_style, array(), $version );
789
	}
790
791
	/**
792
	 * Some blocks do not depend on a specific module,
793
	 * and can consequently be loaded outside of the usual modules.
794
	 * We will look for such modules in the extensions/ directory.
795
	 *
796
	 * @since 7.1.0
797
	 */
798
	public static function load_independent_blocks() {
799
		if ( self::should_load() ) {
800
			/**
801
			 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
802
			 * If available, load them.
803
			 */
804
			foreach ( self::$extensions as $extension ) {
805
				$extension_file_glob = glob( JETPACK__PLUGIN_DIR . 'extensions/*/' . $extension . '/' . $extension . '.php' );
806
				if ( ! empty( $extension_file_glob ) ) {
807
					include_once $extension_file_glob[0];
808
				}
809
			}
810
		}
811
	}
812
813
	/**
814
	 * Loads PHP components of extended-blocks.
815
	 *
816
	 * @since 8.9.0
817
	 */
818
	public static function load_extended_blocks() {
819
		if ( self::should_load() ) {
820
			$extended_blocks = glob( JETPACK__PLUGIN_DIR . 'extensions/extended-blocks/*' );
821
822
			foreach ( $extended_blocks as $block ) {
823
				$name = basename( $block );
824
				$path = JETPACK__PLUGIN_DIR . 'extensions/extended-blocks/' . $name . '/' . $name . '.php';
825
826
				if ( file_exists( $path ) ) {
827
					include_once $path;
828
				}
829
			}
830
		}
831
	}
832
833
	/**
834
	 * Get CSS classes for a block.
835
	 *
836
	 * @since 7.7.0
837
	 *
838
	 * @param string $slug  Block slug.
839
	 * @param array  $attr  Block attributes.
840
	 * @param array  $extra Potential extra classes you may want to provide.
841
	 *
842
	 * @return string $classes List of CSS classes for a block.
843
	 */
844
	public static function block_classes( $slug = '', $attr, $extra = array() ) {
845
		_deprecated_function( __METHOD__, '9.0.0', 'Automattic\\Jetpack\\Blocks::classes' );
846
		return Blocks::classes( $slug, $attr, $extra );
847
	}
848
849
	/**
850
	 * Determine whether a site should use the default set of blocks, or a custom set.
851
	 * Possible variations are currently beta, experimental, and production.
852
	 *
853
	 * @since 8.1.0
854
	 *
855
	 * @return string $block_varation production|beta|experimental
856
	 */
857
	public static function blocks_variation() {
858
		// Default to production blocks.
859
		$block_varation = 'production';
860
861
		if ( Constants::is_true( 'JETPACK_BETA_BLOCKS' ) ) {
862
			$block_varation = 'beta';
863
		}
864
865
		/*
866
		 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant.
867
		 */
868
		if ( Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' ) ) {
869
			$block_varation = 'experimental';
870
		}
871
872
		/**
873
		 * Allow customizing the variation of blocks in use on a site.
874
		 *
875
		 * @since 8.1.0
876
		 *
877
		 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
878
		 */
879
		return apply_filters( 'jetpack_blocks_variation', $block_varation );
880
	}
881
882
	/**
883
	 * Get a list of extensions available for the variation you chose.
884
	 *
885
	 * @since 8.1.0
886
	 *
887
	 * @param obj    $preset_extensions_manifest List of extensions available in Jetpack.
888
	 * @param string $blocks_variation           Subset of blocks. production|beta|experimental.
889
	 *
890
	 * @return array $preset_extensions Array of extensions for that variation
891
	 */
892
	public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
893
		$preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
894
				? (array) $preset_extensions_manifest->{ $blocks_variation }
895
				: array();
896
897
		/*
898
		 * Experimental and Beta blocks need the production blocks as well.
899
		 */
900 View Code Duplication
		if (
901
			'experimental' === $blocks_variation
902
			|| 'beta' === $blocks_variation
903
		) {
904
			$production_extensions = isset( $preset_extensions_manifest->production )
905
				? (array) $preset_extensions_manifest->production
906
				: array();
907
908
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
909
		}
910
911
		/*
912
		 * Beta blocks need the experimental blocks as well.
913
		 *
914
		 * If you've chosen to see Beta blocks,
915
		 * we want to make all blocks available to you:
916
		 * - Production
917
		 * - Experimental
918
		 * - Beta
919
		 */
920 View Code Duplication
		if ( 'beta' === $blocks_variation ) {
921
			$production_extensions = isset( $preset_extensions_manifest->experimental )
922
				? (array) $preset_extensions_manifest->experimental
923
				: array();
924
925
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
926
		}
927
928
		return $preset_extensions;
929
	}
930
931
	/**
932
	 * Validate a URL used in a SSR block.
933
	 *
934
	 * @since 8.3.0
935
	 *
936
	 * @param string $url      URL saved as an attribute in block.
937
	 * @param array  $allowed  Array of allowed hosts for that block, or regexes to check against.
938
	 * @param bool   $is_regex Array of regexes matching the URL that could be used in block.
939
	 *
940
	 * @return bool|string
941
	 */
942
	public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
943
		if (
944
			empty( $url )
945
			|| ! is_array( $allowed )
946
			|| empty( $allowed )
947
		) {
948
			return false;
949
		}
950
951
		$url_components = wp_parse_url( $url );
952
953
		// Bail early if we cannot find a host.
954
		if ( empty( $url_components['host'] ) ) {
955
			return false;
956
		}
957
958
		// Normalize URL.
959
		$url = sprintf(
960
			'%s://%s%s%s',
961
			isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
962
			$url_components['host'],
963
			isset( $url_components['path'] ) ? $url_components['path'] : '/',
964
			isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
965
		);
966
967
		if ( ! empty( $url_components['fragment'] ) ) {
968
			$url = $url . '#' . rawurlencode( $url_components['fragment'] );
969
		}
970
971
		/*
972
		 * If we're using an allowed list of hosts,
973
		 * check if the URL belongs to one of the domains allowed for that block.
974
		 */
975
		if (
976
			false === $is_regex
977
			&& in_array( $url_components['host'], $allowed, true )
978
		) {
979
			return $url;
980
		}
981
982
		/*
983
		 * If we are using an array of regexes to check against,
984
		 * loop through that.
985
		 */
986
		if ( true === $is_regex ) {
987
			foreach ( $allowed as $regex ) {
988
				if ( 1 === preg_match( $regex, $url ) ) {
989
					return $url;
990
				}
991
			}
992
		}
993
994
		return false;
995
	}
996
997
	/**
998
	 * Output an UpgradeNudge Component on the frontend of a site.
999
	 *
1000
	 * @since 8.4.0
1001
	 *
1002
	 * @param string $plan The plan that users need to purchase to make the block work.
1003
	 *
1004
	 * @return string
1005
	 */
1006
	public static function upgrade_nudge( $plan ) {
1007
		if (
1008
			! current_user_can( 'manage_options' )
1009
			/** This filter is documented in class.jetpack-gutenberg.php */
1010
			|| ! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
1011
			/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
1012
			|| ! apply_filters( 'jetpack_show_promotions', true )
1013
			|| is_feed()
1014
		) {
1015
			return;
1016
		}
1017
1018
		jetpack_require_lib( 'components' );
1019
		return Jetpack_Components::render_upgrade_nudge(
1020
			array(
1021
				'plan' => $plan,
1022
			)
1023
		);
1024
	}
1025
1026
	/**
1027
	 * Output a notice within a block.
1028
	 *
1029
	 * @since 8.6.0
1030
	 *
1031
	 * @param string $message Notice we want to output.
1032
	 * @param string $status  Status of the notice. Can be one of success, info, warning, error. info by default.
1033
	 * @param string $classes List of CSS classes.
1034
	 *
1035
	 * @return string
1036
	 */
1037
	public static function notice( $message, $status = 'info', $classes = '' ) {
1038
		if (
1039
			empty( $message )
1040
			|| ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1041
		) {
1042
			return '';
1043
		}
1044
1045
		$color = '';
1046
		switch ( $status ) {
1047
			case 'success':
1048
				$color = '#46b450';
1049
				break;
1050
			case 'warning':
1051
				$color = '#ffb900';
1052
				break;
1053
			case 'error':
1054
				$color = '#dc3232';
1055
				break;
1056
			case 'info':
1057
			default:
1058
				$color = '#00a0d2';
1059
				break;
1060
		}
1061
1062
		return sprintf(
1063
			'<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1064
			esc_attr( $status ),
1065
			wp_kses(
1066
				$message,
1067
				array(
1068
					'br' => array(),
1069
					'p'  => array(),
1070
				)
1071
			),
1072
			esc_attr( $classes ),
1073
			sanitize_hex_color( $color )
1074
		);
1075
	}
1076
1077
	/**
1078
	 * Set the availability of the block as the editor
1079
	 * is loaded.
1080
	 *
1081
	 * @param string $slug Slug of the block.
1082
	 */
1083
	public static function set_availability_for_plan( $slug ) {
1084
		$is_available = true;
1085
		$plan         = '';
1086
		$slug         = self::remove_extension_prefix( $slug );
1087
1088
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1089
			if ( ! class_exists( 'Store_Product_List' ) ) {
1090
				require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1091
			}
1092
			$features_data = Store_Product_List::get_site_specific_features_data();
1093
			$is_available  = in_array( $slug, $features_data['active'], true );
1094
			if ( ! empty( $features_data['available'][ $slug ] ) ) {
1095
				$plan = $features_data['available'][ $slug ][0];
1096
			}
1097
		} elseif ( ! jetpack_is_atomic_site() ) {
1098
			/*
1099
			 * If it's Atomic then assume all features are available
1100
			 * otherwise check against the Jetpack plan.
1101
			 */
1102
			$is_available = Jetpack_Plan::supports( $slug );
1103
			$plan         = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1104
		}
1105
		if ( $is_available ) {
1106
			self::set_extension_available( $slug );
1107
		} else {
1108
			self::set_extension_unavailable(
1109
				$slug,
1110
				'missing_plan',
1111
				array(
1112
					'required_feature' => $slug,
1113
					'required_plan'    => $plan,
1114
				)
1115
			);
1116
		}
1117
	}
1118
1119
	/**
1120
	 * Wraps the suplied render_callback in a function to check
1121
	 * the availability of the block before rendering it.
1122
	 *
1123
	 * @param string   $slug The block slug, used to check for availability.
1124
	 * @param callable $render_callback The render_callback that will be called if the block is available.
1125
	 */
1126
	public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1127
		return function ( $prepared_attributes, $block_content ) use ( $render_callback, $slug ) {
1128
			$availability = self::get_availability();
1129
			$bare_slug    = self::remove_extension_prefix( $slug );
1130
			if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1131
				return call_user_func( $render_callback, $prepared_attributes, $block_content );
1132
			}
1133
1134
			return null;
1135
		};
1136
	}
1137
}
1138